blob: ca807abbcfa7d5f66f8bb51bd8d393bed287dcbd [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070031import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080033import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080034import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070036import android.net.INetworkPolicyListener;
37import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070038import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070039import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080040import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070041import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070043import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070045import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070046import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070047import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070049import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070050import android.net.Proxy;
51import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070052import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.wifi.WifiStateTracker;
54import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040055import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070057import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070058import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070059import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070062import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070063import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070064import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.ServiceManager;
66import android.os.SystemProperties;
67import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070068import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080070import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070071import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Chia-chi Yeh2e467642011-07-04 03:23:12 -070073import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070074import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070075import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080076import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070077import com.android.server.connectivity.Vpn;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070078import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070079import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070082import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070084import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070085import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070086import java.net.InetAddress;
87import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070089import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070090import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070091import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070092import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
95/**
96 * @hide
97 */
98public class ConnectivityService extends IConnectivityManager.Stub {
99
Robert Greenwaltba175a52010-10-05 19:12:26 -0700100 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700101 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private static final String TAG = "ConnectivityService";
103
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700104 private static final boolean LOGD_RULES = false;
105
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106 // how long to wait before switching back to a radio's default network
107 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
108 // system property that can override the above value
109 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
110 "android.telephony.apn-restore";
111
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700112 // used in recursive route setting to add gateways for the host for which
113 // a host route was requested.
114 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
115
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800117 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800118
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700119 private Vpn mVpn;
120
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
122 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700123 /** Currently active network rules by UID. */
124 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125 /** Set of ifaces that are costly. */
126 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 /**
129 * Sometimes we want to refer to the individual network state
130 * trackers separately, and sometimes we just want to treat them
131 * abstractly.
132 */
133 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134
135 /**
Wink Savillee8222252011-07-13 13:44:13 -0700136 * The link properties that define the current links
137 */
138 private LinkProperties mCurrentLinkProperties[];
139
140 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141 * A per Net list of the PID's that requested access to the net
142 * used both as a refcount and for per-PID DNS selection
143 */
144 private List mNetRequestersPids[];
145
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146 // priority order of the nettrackers
147 // (excluding dynamically set mNetworkPreference)
148 // TODO - move mNetworkTypePreference into this
149 private int[] mPriorityList;
150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 private Context mContext;
152 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700153 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700154 // 0 is full bad, 100 is full good
155 private int mDefaultInetCondition = 0;
156 private int mDefaultInetConditionPublished = 0;
157 private boolean mInetConditionChangeInFlight = false;
158 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700160 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700162 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
164 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700165 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700167 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700169
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700170 private static final int ENABLED = 1;
171 private static final int DISABLED = 0;
172
173 // Share the event space with NetworkStateTracker (which can't see this
174 // internal class but sends us events). If you change these, change
175 // NetworkStateTracker.java too.
176 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
177 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
178
179 /**
180 * used internally as a delayed event to make us switch back to the
181 * default network
182 */
183 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
184 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
185
186 /**
187 * used internally to change our mobile data enabled flag
188 */
189 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
190 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
191
192 /**
193 * used internally to change our network preference setting
194 * arg1 = networkType to prefer
195 */
196 private static final int EVENT_SET_NETWORK_PREFERENCE =
197 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
198
199 /**
200 * used internally to synchronize inet condition reports
201 * arg1 = networkType
202 * arg2 = condition (0 bad, 100 good)
203 */
204 private static final int EVENT_INET_CONDITION_CHANGE =
205 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
206
207 /**
208 * used internally to mark the end of inet condition hold periods
209 * arg1 = networkType
210 */
211 private static final int EVENT_INET_CONDITION_HOLD_END =
212 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
213
214 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700215 * used internally to set enable/disable cellular data
216 * arg1 = ENBALED or DISABLED
217 */
218 private static final int EVENT_SET_MOBILE_DATA =
219 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
220
Robert Greenwaltf3331232010-09-24 14:32:21 -0700221 /**
222 * used internally to clear a wakelock when transitioning
223 * from one net to another
224 */
225 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
227
Robert Greenwalt434203a2010-10-11 16:00:27 -0700228 /**
229 * used internally to reload global proxy settings
230 */
231 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
232 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
233
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700234 /**
235 * used internally to set external dependency met/unmet
236 * arg1 = ENABLED (met) or DISABLED (unmet)
237 * arg2 = NetworkType
238 */
239 private static final int EVENT_SET_DEPENDENCY_MET =
240 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
241
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700242 /**
243 * used internally to restore DNS properties back to the
244 * default network
245 */
246 private static final int EVENT_RESTORE_DNS =
247 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
248
Wink Saville2b30afd2011-08-05 11:40:22 -0700249 /**
Wink Saville628b0852011-08-04 15:01:58 -0700250 * used internally to send a sticky broadcast delayed.
251 */
252 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville2b30afd2011-08-05 11:40:22 -0700253 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville628b0852011-08-04 15:01:58 -0700254
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700255 /**
256 * Used internally to
257 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
258 */
259 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
260
Robert Greenwalt42acef32009-08-12 16:08:25 -0700261 private Handler mHandler;
262
263 // list of DeathRecipients used to make sure features are turned off when
264 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500265 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700266
Mike Lockwood0f79b542009-08-14 14:18:49 -0400267 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800268 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400269
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700270 private PowerManager.WakeLock mNetTransitionWakeLock;
271 private String mNetTransitionWakeLockCausedBy = "";
272 private int mNetTransitionWakeLockSerialNumber;
273 private int mNetTransitionWakeLockTimeout;
274
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700275 private InetAddress mDefaultDns;
276
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700277 // this collection is used to refcount the added routes - if there are none left
278 // it's time to remove the route from the route table
279 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
280
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700281 // used in DBG mode to track inet condition reports
282 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
283 private ArrayList mInetLog;
284
Robert Greenwalt434203a2010-10-11 16:00:27 -0700285 // track the current default http proxy - tell the world if we get a new one (real change)
286 private ProxyProperties mDefaultProxy = null;
287 // track the global proxy.
288 private ProxyProperties mGlobalProxy = null;
289 private final Object mGlobalProxyLock = new Object();
290
291 private SettingsObserver mSettingsObserver;
292
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700293 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700294 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700295
Robert Greenwalt511288a2009-12-07 11:33:18 -0800296 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700297 public int mSimultaneity;
298 public int mType;
299 public RadioAttributes(String init) {
300 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700301 mType = Integer.parseInt(fragments[0]);
302 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700303 }
304 }
305 RadioAttributes[] mRadioAttributes;
306
Robert Greenwalt50393202011-06-21 17:26:14 -0700307 // the set of network types that can only be enabled by system/sig apps
308 List mProtectedNetworks;
309
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700310 public ConnectivityService(Context context, INetworkManagementService netd,
311 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800312 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800313
Wink Savillebb08caf2010-09-02 19:23:52 -0700314 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
315 handlerThread.start();
316 mHandler = new MyHandler(handlerThread.getLooper());
317
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800318 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800319 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
320 String id = Settings.Secure.getString(context.getContentResolver(),
321 Settings.Secure.ANDROID_ID);
322 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700323 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800324 SystemProperties.set("net.hostname", name);
325 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800326 }
327
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700328 // read our default dns server ip
329 String dns = Settings.Secure.getString(context.getContentResolver(),
330 Settings.Secure.DEFAULT_DNS_SERVER);
331 if (dns == null || dns.length() == 0) {
332 dns = context.getResources().getString(
333 com.android.internal.R.string.config_default_dns_server);
334 }
335 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800336 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
337 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800338 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700339 }
340
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700341 mContext = checkNotNull(context, "missing Context");
342 mNetd = checkNotNull(netd, "missing INetworkManagementService");
343 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700344
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700345 try {
346 mPolicyManager.registerListener(mPolicyListener);
347 } catch (RemoteException e) {
348 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700349 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700350 }
351
352 final PowerManager powerManager = (PowerManager) context.getSystemService(
353 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700354 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
355 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
356 com.android.internal.R.integer.config_networkTransitionTimeout);
357
Robert Greenwalt42acef32009-08-12 16:08:25 -0700358 mNetTrackers = new NetworkStateTracker[
359 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700360 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700363
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700364 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700365 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700366
Robert Greenwalt42acef32009-08-12 16:08:25 -0700367 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700368 String[] raStrings = context.getResources().getStringArray(
369 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700370 for (String raString : raStrings) {
371 RadioAttributes r = new RadioAttributes(raString);
372 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800373 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700374 continue;
375 }
376 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800377 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700378 r.mType);
379 continue;
380 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381 mRadioAttributes[r.mType] = r;
382 }
383
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700384 String[] naStrings = context.getResources().getStringArray(
385 com.android.internal.R.array.networkAttributes);
386 for (String naString : naStrings) {
387 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700388 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700389 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800390 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700391 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700392 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700393 }
Wink Saville975c8482011-04-07 14:23:45 -0700394 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800395 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700396 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 continue;
398 }
Wink Saville975c8482011-04-07 14:23:45 -0700399 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800400 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700401 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700402 continue;
403 }
Wink Saville975c8482011-04-07 14:23:45 -0700404 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700405 mNetworksDefined++;
406 } catch(Exception e) {
407 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700408 }
409 }
410
Robert Greenwalt50393202011-06-21 17:26:14 -0700411 mProtectedNetworks = new ArrayList<Integer>();
412 int[] protectedNetworks = context.getResources().getIntArray(
413 com.android.internal.R.array.config_protectedNetworks);
414 for (int p : protectedNetworks) {
415 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
416 mProtectedNetworks.add(p);
417 } else {
418 if (DBG) loge("Ignoring protectedNetwork " + p);
419 }
420 }
421
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700422 // high priority first
423 mPriorityList = new int[mNetworksDefined];
424 {
425 int insertionPoint = mNetworksDefined-1;
426 int currentLowest = 0;
427 int nextLowest = 0;
428 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700429 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700430 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700431 if (na.priority < currentLowest) continue;
432 if (na.priority > currentLowest) {
433 if (na.priority < nextLowest || nextLowest == 0) {
434 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 }
436 continue;
437 }
Wink Saville975c8482011-04-07 14:23:45 -0700438 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700439 }
440 currentLowest = nextLowest;
441 nextLowest = 0;
442 }
443 }
444
445 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
446 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700447 mNetRequestersPids[i] = new ArrayList();
448 }
449
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500450 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700451
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700452 mNumDnsEntries = 0;
453
454 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
455 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 /*
457 * Create the network state trackers for Wi-Fi and mobile
458 * data. Maybe this could be done with a factory class,
459 * but it's not clear that it's worth it, given that
460 * the number of different network types is not going
461 * to change very often.
462 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700463 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700464 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700465 case ConnectivityManager.TYPE_WIFI:
repo syncaea743a2011-07-29 23:55:49 -0700466 mNetTrackers[netType] = new WifiStateTracker(netType,
467 mNetConfigs[netType].name);
468 mNetTrackers[netType].startMonitoring(context, mHandler);
469 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700470 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700471 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700472 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700473 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700474 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800475 case ConnectivityManager.TYPE_DUMMY:
476 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700477 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800478 mNetTrackers[netType].startMonitoring(context, mHandler);
479 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800480 case ConnectivityManager.TYPE_BLUETOOTH:
481 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
482 mNetTrackers[netType].startMonitoring(context, mHandler);
483 break;
Benoit Goby19970692010-12-22 14:29:40 -0800484 case ConnectivityManager.TYPE_ETHERNET:
485 mNetTrackers[netType] = EthernetDataTracker.getInstance();
486 mNetTrackers[netType].startMonitoring(context, mHandler);
487 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700488 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800489 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700490 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700491 continue;
492 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700493 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700494 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700495 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800496
Chia-chi Yehc9338302011-05-11 16:35:13 -0700497 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
498 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
499
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700500 mTethering = new Tethering(mContext, nmService, statsService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700501 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700502 mTethering.getTetherableWifiRegexs().length != 0 ||
503 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700504 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800505
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700506 mVpn = new Vpn(mContext, new VpnCallback());
507
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700508 try {
509 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700510 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700511 } catch (RemoteException e) {
512 loge("Error registering observer :" + e);
513 }
514
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700515 if (DBG) {
516 mInetLog = new ArrayList();
517 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700518
519 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
520 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800521
522 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 }
524
525 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700526 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 * @param preference the new preference
528 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700529 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700531
532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
534
535 public int getNetworkPreference() {
536 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700537 int preference;
538 synchronized(this) {
539 preference = mNetworkPreference;
540 }
541 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700544 private void handleSetNetworkPreference(int preference) {
545 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700546 mNetConfigs[preference] != null &&
547 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700548 if (mNetworkPreference != preference) {
549 final ContentResolver cr = mContext.getContentResolver();
550 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
551 synchronized(this) {
552 mNetworkPreference = preference;
553 }
554 enforcePreference();
555 }
556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700558
Wink Saville628b0852011-08-04 15:01:58 -0700559 private int getConnectivityChangeDelay() {
560 final ContentResolver cr = mContext.getContentResolver();
561
562 /** Check system properties for the default value then use secure settings value, if any. */
563 int defaultDelay = SystemProperties.getInt(
564 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
565 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
566 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
567 defaultDelay);
568 }
569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 private int getPersistedNetworkPreference() {
571 final ContentResolver cr = mContext.getContentResolver();
572
573 final int networkPrefSetting = Settings.Secure
574 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
575 if (networkPrefSetting != -1) {
576 return networkPrefSetting;
577 }
578
579 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
580 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700583 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 * In this method, we only tear down a non-preferred network. Establishing
585 * a connection to the preferred network is taken care of when we handle
586 * the disconnect event from the non-preferred network
587 * (see {@link #handleDisconnect(NetworkInfo)}).
588 */
589 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700590 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 return;
592
Robert Greenwalt42acef32009-08-12 16:08:25 -0700593 if (!mNetTrackers[mNetworkPreference].isAvailable())
594 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595
Robert Greenwalt42acef32009-08-12 16:08:25 -0700596 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700597 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700598 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700599 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800600 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700601 " in enforcePreference");
602 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700603 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605 }
606 }
607
608 private boolean teardown(NetworkStateTracker netTracker) {
609 if (netTracker.teardown()) {
610 netTracker.setTeardownRequested(true);
611 return true;
612 } else {
613 return false;
614 }
615 }
616
617 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700618 * Check if UID should be blocked from using the network represented by the
619 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700620 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700621 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
622 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700623
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700624 final boolean networkCostly;
625 final int uidRules;
626 synchronized (mRulesLock) {
627 networkCostly = mMeteredIfaces.contains(iface);
628 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700629 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700630
631 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
632 return true;
633 }
634
635 // no restrictive rules; network is visible
636 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700637 }
638
639 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700640 * Return a filtered {@link NetworkInfo}, potentially marked
641 * {@link DetailedState#BLOCKED} based on
642 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700643 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700644 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
645 NetworkInfo info = tracker.getNetworkInfo();
646 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700647 // network is blocked; clone and override state
648 info = new NetworkInfo(info);
649 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700650 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700651 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700652 }
653
654 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * Return NetworkInfo for the active (i.e., connected) network interface.
656 * It is assumed that at most one network is active at a time. If more
657 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700658 * @return the info for the active network, or {@code null} if none is
659 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700661 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 enforceAccessPermission();
664 final int uid = Binder.getCallingUid();
665 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700668 @Override
669 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
670 enforceConnectivityInternalPermission();
671 return getNetworkInfo(mActiveDefaultNetwork, uid);
672 }
673
674 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 public NetworkInfo getNetworkInfo(int networkType) {
676 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700677 final int uid = Binder.getCallingUid();
678 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
680
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700681 private NetworkInfo getNetworkInfo(int networkType, int uid) {
682 NetworkInfo info = null;
683 if (isNetworkTypeValid(networkType)) {
684 final NetworkStateTracker tracker = mNetTrackers[networkType];
685 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700686 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700687 }
688 }
689 return info;
690 }
691
692 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 public NetworkInfo[] getAllNetworkInfo() {
694 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700695 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700696 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700697 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700698 for (NetworkStateTracker tracker : mNetTrackers) {
699 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700700 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700701 }
702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700704 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700707 @Override
708 public boolean isNetworkSupported(int networkType) {
709 enforceAccessPermission();
710 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
711 }
712
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700713 /**
714 * Return LinkProperties for the active (i.e., connected) default
715 * network interface. It is assumed that at most one default network
716 * is active at a time. If more than one is active, it is indeterminate
717 * which will be returned.
718 * @return the ip properties for the active network, or {@code null} if
719 * none is active
720 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700722 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700723 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700724 }
725
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700727 public LinkProperties getLinkProperties(int networkType) {
728 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 if (isNetworkTypeValid(networkType)) {
730 final NetworkStateTracker tracker = mNetTrackers[networkType];
731 if (tracker != null) {
732 return tracker.getLinkProperties();
733 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700734 }
735 return null;
736 }
737
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700738 @Override
739 public NetworkState[] getAllNetworkState() {
740 enforceAccessPermission();
741 final int uid = Binder.getCallingUid();
742 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700743 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700744 for (NetworkStateTracker tracker : mNetTrackers) {
745 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700746 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700747 result.add(new NetworkState(
748 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
749 }
750 }
751 }
752 return result.toArray(new NetworkState[result.size()]);
753 }
754
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700755 private NetworkState getNetworkStateUnchecked(int networkType) {
756 if (isNetworkTypeValid(networkType)) {
757 final NetworkStateTracker tracker = mNetTrackers[networkType];
758 if (tracker != null) {
759 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
760 tracker.getLinkCapabilities());
761 }
762 }
763 return null;
764 }
765
766 @Override
767 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
768 enforceAccessPermission();
769 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
770 if (state != null) {
771 try {
772 return mPolicyManager.getNetworkQuotaInfo(state);
773 } catch (RemoteException e) {
774 }
775 }
776 return null;
777 }
778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 public boolean setRadios(boolean turnOn) {
780 boolean result = true;
781 enforceChangePermission();
782 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 }
785 return result;
786 }
787
788 public boolean setRadio(int netType, boolean turnOn) {
789 enforceChangePermission();
790 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
791 return false;
792 }
793 NetworkStateTracker tracker = mNetTrackers[netType];
794 return tracker != null && tracker.setRadio(turnOn);
795 }
796
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700797 /**
798 * Used to notice when the calling process dies so we can self-expire
799 *
800 * Also used to know if the process has cleaned up after itself when
801 * our auto-expire timer goes off. The timer has a link to an object.
802 *
803 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700804 private class FeatureUser implements IBinder.DeathRecipient {
805 int mNetworkType;
806 String mFeature;
807 IBinder mBinder;
808 int mPid;
809 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800810 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700811
812 FeatureUser(int type, String feature, IBinder binder) {
813 super();
814 mNetworkType = type;
815 mFeature = feature;
816 mBinder = binder;
817 mPid = getCallingPid();
818 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800819 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700820
Robert Greenwalt42acef32009-08-12 16:08:25 -0700821 try {
822 mBinder.linkToDeath(this, 0);
823 } catch (RemoteException e) {
824 binderDied();
825 }
826 }
827
828 void unlinkDeathRecipient() {
829 mBinder.unlinkToDeath(this, 0);
830 }
831
832 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800833 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800834 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
835 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700836 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700837 }
838
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700839 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700840 if (VDBG) {
841 log("ConnectivityService FeatureUser expire(" +
842 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
843 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
844 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700845 stopUsingNetworkFeature(this, false);
846 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800847
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500848 public boolean isSameUser(FeatureUser u) {
849 if (u == null) return false;
850
851 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
852 }
853
854 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
855 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
856 TextUtils.equals(mFeature, feature)) {
857 return true;
858 }
859 return false;
860 }
861
Robert Greenwaltb9285352009-12-21 18:24:07 -0800862 public String toString() {
863 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
864 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
865 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700866 }
867
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700868 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700869 public int startUsingNetworkFeature(int networkType, String feature,
870 IBinder binder) {
Wink Savillec9acde92011-09-21 11:05:43 -0700871 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800872 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700875 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700876 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700877 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700879
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700880 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700881
repo syncaea743a2011-07-29 23:55:49 -0700882 // TODO - move this into individual networktrackers
883 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -0700884
885 if (mProtectedNetworks.contains(usedNetworkType)) {
886 enforceConnectivityInternalPermission();
887 }
888
Robert Greenwalt42acef32009-08-12 16:08:25 -0700889 NetworkStateTracker network = mNetTrackers[usedNetworkType];
890 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800891 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700893 NetworkInfo ni = network.getNetworkInfo();
894
895 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800896 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800897 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
898 return Phone.APN_TYPE_NOT_AVAILABLE;
899 } else {
900 // else make the attempt anyway - probably giving REQUEST_STARTED below
901 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700902 }
903
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500904 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
905
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700906 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500907 boolean addToList = true;
908 if (restoreTimer < 0) {
909 // In case there is no timer is specified for the feature,
910 // make sure we don't add duplicate entry with the same request.
911 for (FeatureUser u : mFeatureUsers) {
912 if (u.isSameUser(f)) {
913 // Duplicate user is found. Do not add.
914 addToList = false;
915 break;
916 }
917 }
918 }
919
920 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700921 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
922 // this gets used for per-pid dns when connected
923 mNetRequestersPids[usedNetworkType].add(currentPid);
924 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700925 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700926
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700927 if (restoreTimer >= 0) {
928 mHandler.sendMessageDelayed(
929 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
930 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700931
Robert Greenwalta64bf832009-08-19 20:19:33 -0700932 if ((ni.isConnectedOrConnecting() == true) &&
933 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700934 if (ni.isConnected() == true) {
935 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700936 handleDnsConfigurationChange(usedNetworkType);
Wink Savillec9acde92011-09-21 11:05:43 -0700937 if (VDBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700938 return Phone.APN_ALREADY_ACTIVE;
939 }
Wink Savillec9acde92011-09-21 11:05:43 -0700940 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700941 return Phone.APN_REQUEST_STARTED;
942 }
943
944 // check if the radio in play can make another contact
945 // assume if cannot for now
946
Wink Savillec9acde92011-09-21 11:05:43 -0700947 if (DBG) {
948 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
949 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700950 network.reconnect();
951 return Phone.APN_REQUEST_STARTED;
952 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800953 // need to remember this unsupported request so we respond appropriately on stop
954 synchronized(this) {
955 mFeatureUsers.add(f);
956 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
957 // this gets used for per-pid dns when connected
958 mNetRequestersPids[usedNetworkType].add(currentPid);
959 }
960 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700961 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700962 }
963 }
964 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700967 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700969 enforceChangePermission();
970
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700971 int pid = getCallingPid();
972 int uid = getCallingUid();
973
974 FeatureUser u = null;
975 boolean found = false;
976
977 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500978 for (FeatureUser x : mFeatureUsers) {
979 if (x.isSameUser(pid, uid, networkType, feature)) {
980 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700981 found = true;
982 break;
983 }
984 }
985 }
986 if (found && u != null) {
987 // stop regardless of how many other time this proc had called start
988 return stopUsingNetworkFeature(u, true);
989 } else {
990 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -0700991 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700992 return 1;
993 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700994 }
995
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700996 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
997 int networkType = u.mNetworkType;
998 String feature = u.mFeature;
999 int pid = u.mPid;
1000 int uid = u.mUid;
1001
1002 NetworkStateTracker tracker = null;
1003 boolean callTeardown = false; // used to carry our decision outside of sync block
1004
Wink Savillec9acde92011-09-21 11:05:43 -07001005 if (VDBG) {
1006 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001007 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001010 if (DBG) {
1011 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1012 ", net is invalid");
1013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 return -1;
1015 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001016
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001017 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1018 // sync block
1019 synchronized(this) {
1020 // check if this process still has an outstanding start request
1021 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001022 if (VDBG) {
1023 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1024 ", ignoring");
1025 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001026 return 1;
1027 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001028 u.unlinkDeathRecipient();
1029 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1030 // If we care about duplicate requests, check for that here.
1031 //
1032 // This is done to support the extension of a request - the app
1033 // can request we start the network feature again and renew the
1034 // auto-shutoff delay. Normal "stop" calls from the app though
1035 // do not pay attention to duplicate requests - in effect the
1036 // API does not refcount and a single stop will counter multiple starts.
1037 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001038 for (FeatureUser x : mFeatureUsers) {
1039 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001040 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001041 return 1;
1042 }
1043 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001044 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001045
repo syncaea743a2011-07-29 23:55:49 -07001046 // TODO - move to individual network trackers
1047 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1048
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001050 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001051 if (DBG) {
1052 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1053 " no known tracker for used net type " + usedNetworkType);
1054 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001055 return -1;
1056 }
1057 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001058 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001059 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001060 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001061 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001062 if (VDBG) {
1063 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1064 " others still using it");
1065 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001066 return 1;
1067 }
1068 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001069 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001070 if (DBG) {
1071 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1072 " not a known feature - dropping");
1073 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001074 }
1075 }
Wink Savillec9acde92011-09-21 11:05:43 -07001076
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001077 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001078 if (DBG) {
1079 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1080 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001081 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 return 1;
1083 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001084 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087
1088 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001089 * @deprecated use requestRouteToHostAddress instead
1090 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 * Ensure that a network route exists to deliver traffic to the specified
1092 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001093 * @param networkType the type of the network over which traffic to the
1094 * specified host is to be routed
1095 * @param hostAddress the IP address of the host to which the route is
1096 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * @return {@code true} on success, {@code false} on failure
1098 */
1099 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001100 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1101
1102 if (inetAddress == null) {
1103 return false;
1104 }
1105
1106 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1107 }
1108
1109 /**
1110 * Ensure that a network route exists to deliver traffic to the specified
1111 * host via the specified network interface.
1112 * @param networkType the type of the network over which traffic to the
1113 * specified host is to be routed
1114 * @param hostAddress the IP address of the host to which the route is
1115 * desired
1116 * @return {@code true} on success, {@code false} on failure
1117 */
1118 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001120 if (mProtectedNetworks.contains(networkType)) {
1121 enforceConnectivityInternalPermission();
1122 }
1123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1125 return false;
1126 }
1127 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001128
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001129 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1130 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001131 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001132 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001133 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001134 }
1135 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001137 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001138 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001139 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001140 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001141 } catch (UnknownHostException e) {}
1142 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001143 }
1144
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001145 private boolean addRoute(LinkProperties p, RouteInfo r) {
1146 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001147 }
1148
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001149 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1150 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1151 }
1152
Robert Greenwaltad55d352011-07-22 11:55:33 -07001153 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1154 return modifyRouteToAddress(lp, addr, true);
1155 }
1156
1157 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1158 return modifyRouteToAddress(lp, addr, false);
1159 }
1160
1161 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1162 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1163 if (bestRoute == null) {
1164 bestRoute = RouteInfo.makeHostRoute(addr);
1165 } else {
1166 if (bestRoute.getGateway().equals(addr)) {
1167 // if there is no better route, add the implied hostroute for our gateway
1168 bestRoute = RouteInfo.makeHostRoute(addr);
1169 } else {
1170 // if we will connect to this through another route, add a direct route
1171 // to it's gateway
1172 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1173 }
1174 }
1175 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1176 }
1177
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001178 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1179 boolean doAdd) {
1180 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1181
1182 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1183 loge("Error adding route - too much recursion");
1184 return false;
1185 }
1186
1187 if (r.isHostRoute() == false) {
1188 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1189 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001190 if (bestRoute.getGateway().equals(r.getGateway())) {
1191 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001192 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001193 } else {
1194 // if we will connect to our gateway through another route, add a direct
1195 // route to it's gateway
1196 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001197 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001198 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001199 }
1200 }
1201 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001202 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001203 mAddedRoutes.add(r);
1204 try {
1205 mNetd.addRoute(ifaceName, r);
1206 } catch (Exception e) {
1207 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001208 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001209 return false;
1210 }
1211 } else {
1212 // if we remove this one and there are no more like it, then refcount==0 and
1213 // we can remove it from the table
1214 mAddedRoutes.remove(r);
1215 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001216 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001217 try {
1218 mNetd.removeRoute(ifaceName, r);
1219 } catch (Exception e) {
1220 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001221 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001222 return false;
1223 }
1224 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001225 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001226 }
1227 }
1228 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
1230
1231 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001232 * @see ConnectivityManager#getMobileDataEnabled()
1233 */
1234 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001235 // TODO: This detail should probably be in DataConnectionTracker's
1236 // which is where we store the value and maybe make this
1237 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001238 enforceAccessPermission();
1239 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1240 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001241 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001242 return retVal;
1243 }
1244
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001245 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001246 enforceConnectivityInternalPermission();
1247
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001248 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1249 (met ? ENABLED : DISABLED), networkType));
1250 }
1251
1252 private void handleSetDependencyMet(int networkType, boolean met) {
1253 if (mNetTrackers[networkType] != null) {
1254 if (DBG) {
1255 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1256 }
1257 mNetTrackers[networkType].setDependencyMet(met);
1258 }
1259 }
1260
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1262 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001263 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001264 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001265 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001266
1267 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001268 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001269 }
1270
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001271 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001272 // skip update when we've already applied rules
1273 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1274 if (oldRules == uidRules) return;
1275
1276 mUidRules.put(uid, uidRules);
1277 }
1278
1279 // TODO: dispatch into NMS to push rules towards kernel module
1280 // TODO: notify UID when it has requested targeted updates
1281 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001282
1283 @Override
1284 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1285 // only someone like NPMS should only be calling us
1286 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1287
1288 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001289 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001290 }
1291
1292 synchronized (mRulesLock) {
1293 mMeteredIfaces.clear();
1294 for (String iface : meteredIfaces) {
1295 mMeteredIfaces.add(iface);
1296 }
1297 }
1298 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 };
1300
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001301 /**
1302 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1303 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001304 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001305 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001306 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001307
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001308 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001309 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001310 }
1311
1312 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001313 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001314 if (VDBG) {
1315 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001316 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001317 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1318 }
1319 }
1320
1321 @Override
1322 public void setPolicyDataEnable(int networkType, boolean enabled) {
1323 // only someone like NPMS should only be calling us
1324 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1325
1326 mHandler.sendMessage(mHandler.obtainMessage(
1327 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1328 }
1329
1330 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1331 if (isNetworkTypeValid(networkType)) {
1332 final NetworkStateTracker tracker = mNetTrackers[networkType];
1333 if (tracker != null) {
1334 tracker.setPolicyDataEnable(enabled);
1335 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001336 }
1337 }
1338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001340 mContext.enforceCallingOrSelfPermission(
1341 android.Manifest.permission.ACCESS_NETWORK_STATE,
1342 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
1344
1345 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001346 mContext.enforceCallingOrSelfPermission(
1347 android.Manifest.permission.CHANGE_NETWORK_STATE,
1348 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001351 // TODO Make this a special check when it goes public
1352 private void enforceTetherChangePermission() {
1353 mContext.enforceCallingOrSelfPermission(
1354 android.Manifest.permission.CHANGE_NETWORK_STATE,
1355 "ConnectivityService");
1356 }
1357
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001358 private void enforceTetherAccessPermission() {
1359 mContext.enforceCallingOrSelfPermission(
1360 android.Manifest.permission.ACCESS_NETWORK_STATE,
1361 "ConnectivityService");
1362 }
1363
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001364 private void enforceConnectivityInternalPermission() {
1365 mContext.enforceCallingOrSelfPermission(
1366 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1367 "ConnectivityService");
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001371 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1372 * network, we ignore it. If it is for the active network, we send out a
1373 * broadcast. But first, we check whether it might be possible to connect
1374 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 * @param info the {@code NetworkInfo} for the network
1376 */
1377 private void handleDisconnect(NetworkInfo info) {
1378
Robert Greenwalt42acef32009-08-12 16:08:25 -07001379 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380
Robert Greenwalt42acef32009-08-12 16:08:25 -07001381 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 /*
1383 * If the disconnected network is not the active one, then don't report
1384 * this as a loss of connectivity. What probably happened is that we're
1385 * getting the disconnect for a network that we explicitly disabled
1386 * in accordance with network preference policies.
1387 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001388 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001389 List pids = mNetRequestersPids[prevNetType];
1390 for (int i = 0; i<pids.size(); i++) {
1391 Integer pid = (Integer)pids.get(i);
1392 // will remove them because the net's no longer connected
1393 // need to do this now as only now do we know the pids and
1394 // can properly null things that are no longer referenced.
1395 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1401 if (info.isFailover()) {
1402 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1403 info.setFailover(false);
1404 }
1405 if (info.getReason() != null) {
1406 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1407 }
1408 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001409 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1410 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001412
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001413 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001414 tryFailover(prevNetType);
1415 if (mActiveDefaultNetwork != -1) {
1416 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001417 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1418 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001419 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001420 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1421 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001422 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001423 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001424
1425 // Reset interface if no other connections are using the same interface
1426 boolean doReset = true;
1427 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1428 if (linkProperties != null) {
1429 String oldIface = linkProperties.getInterfaceName();
1430 if (TextUtils.isEmpty(oldIface) == false) {
1431 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1432 if (networkStateTracker == null) continue;
1433 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1434 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1435 LinkProperties l = networkStateTracker.getLinkProperties();
1436 if (l == null) continue;
1437 if (oldIface.equals(l.getInterfaceName())) {
1438 doReset = false;
1439 break;
1440 }
1441 }
1442 }
1443 }
1444 }
1445
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001446 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001447 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001448
Jeff Sharkey961e3042011-08-29 16:02:57 -07001449 final Intent immediateIntent = new Intent(intent);
1450 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1451 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001452 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001453 /*
1454 * If the failover network is already connected, then immediately send
1455 * out a followup broadcast indicating successful failover
1456 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001457 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001458 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1459 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001460 }
1461 }
1462
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001463 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001464 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001465 * If this is a default network, check if other defaults are available.
1466 * Try to reconnect on all available and let them hash it out when
1467 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001468 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001469 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001470 if (mActiveDefaultNetwork == prevNetType) {
1471 mActiveDefaultNetwork = -1;
1472 }
1473
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001474 // don't signal a reconnect for anything lower or equal priority than our
1475 // current connected default
1476 // TODO - don't filter by priority now - nice optimization but risky
1477// int currentPriority = -1;
1478// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001479// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001480// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001481 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001482 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001483 if (mNetConfigs[checkType] == null) continue;
1484 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001485
1486// Enabling the isAvailable() optimization caused mobile to not get
1487// selected if it was in the middle of error handling. Specifically
1488// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1489// would not be available and we wouldn't get connected to anything.
1490// So removing the isAvailable() optimization below for now. TODO: This
1491// optimization should work and we need to investigate why it doesn't work.
1492// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1493// complete before it is really complete.
1494// if (!mNetTrackers[checkType].isAvailable()) continue;
1495
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001496// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001497
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001498 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1499 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1500 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1501 checkInfo.setFailover(true);
1502 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001503 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001504 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508
1509 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001510 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1511 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001512 }
1513
Wink Saville628b0852011-08-04 15:01:58 -07001514 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001515 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1516 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001517 }
1518
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001519 private void sendInetConditionBroadcast(NetworkInfo info) {
1520 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1521 }
1522
Wink Saville628b0852011-08-04 15:01:58 -07001523 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001524 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1526 if (info.isFailover()) {
1527 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1528 info.setFailover(false);
1529 }
1530 if (info.getReason() != null) {
1531 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1532 }
1533 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001534 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1535 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001537 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001538 return intent;
1539 }
1540
1541 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1542 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1543 }
1544
1545 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1546 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548
1549 /**
1550 * Called when an attempt to fail over to another network has failed.
1551 * @param info the {@link NetworkInfo} for the failed network
1552 */
1553 private void handleConnectionFailure(NetworkInfo info) {
1554 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555
Robert Greenwalt42acef32009-08-12 16:08:25 -07001556 String reason = info.getReason();
1557 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001558
Robert Greenwalt572172b2010-10-08 16:35:52 -07001559 String reasonText;
1560 if (reason == null) {
1561 reasonText = ".";
1562 } else {
1563 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001565 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001566
1567 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1568 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1569 if (getActiveNetworkInfo() == null) {
1570 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1571 }
1572 if (reason != null) {
1573 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1574 }
1575 if (extraInfo != null) {
1576 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1577 }
1578 if (info.isFailover()) {
1579 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1580 info.setFailover(false);
1581 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001582
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001583 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001584 tryFailover(info.getType());
1585 if (mActiveDefaultNetwork != -1) {
1586 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001587 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1588 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001589 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001590 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1591 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001592 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001593
Robert Greenwalt029be812010-09-20 18:01:43 -07001594 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001595
1596 final Intent immediateIntent = new Intent(intent);
1597 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1598 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001599 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001600 /*
1601 * If the failover network is already connected, then immediately send
1602 * out a followup broadcast indicating successful failover
1603 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001604 if (mActiveDefaultNetwork != -1) {
1605 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001606 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001607 }
1608
1609 private void sendStickyBroadcast(Intent intent) {
1610 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001611 if (!mSystemReady) {
1612 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001613 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001614 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001615 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001616 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001617 }
1618
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001620 }
1621 }
1622
Wink Saville628b0852011-08-04 15:01:58 -07001623 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1624 if (delayMs <= 0) {
1625 sendStickyBroadcast(intent);
1626 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001627 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001628 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1629 + intent.getAction());
1630 }
Wink Saville628b0852011-08-04 15:01:58 -07001631 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1632 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1633 }
1634 }
1635
Mike Lockwood0f79b542009-08-14 14:18:49 -04001636 void systemReady() {
1637 synchronized(this) {
1638 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001639 if (mInitialBroadcast != null) {
1640 mContext.sendStickyBroadcast(mInitialBroadcast);
1641 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001642 }
1643 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001644 // load the global proxy at startup
1645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647
1648 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001649 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650
1651 // snapshot isFailover, because sendConnectedBroadcast() resets it
1652 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001653 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654
Robert Greenwalt42acef32009-08-12 16:08:25 -07001655 // if this is a default net and other default is running
1656 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001657 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001658 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1659 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001660 mNetConfigs[mActiveDefaultNetwork].priority >
1661 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001662 mNetworkPreference == mActiveDefaultNetwork) {
1663 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001664 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001665 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001666 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001667 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001668 teardown(thisNet);
1669 return;
1670 } else {
1671 // tear down the other
1672 NetworkStateTracker otherNet =
1673 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001674 if (DBG) {
1675 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001676 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001677 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001679 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001680 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001681 return;
1682 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001683 }
1684 }
1685 synchronized (ConnectivityService.this) {
1686 // have a new default network, release the transition wakelock in a second
1687 // if it's held. The second pause is to allow apps to reconnect over the
1688 // new network
1689 if (mNetTransitionWakeLock.isHeld()) {
1690 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001691 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001692 mNetTransitionWakeLockSerialNumber, 0),
1693 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001694 }
1695 }
1696 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001697 // this will cause us to come up initially as unconnected and switching
1698 // to connected after our normal pause unless somebody reports us as reall
1699 // disconnected
1700 mDefaultInetConditionPublished = 0;
1701 mDefaultConnectionSequence++;
1702 mInetConditionChangeInFlight = false;
1703 // Don't do this - if we never sign in stay, grey
1704 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001707 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001708 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001709 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001713 * After a change in the connectivity state of a network. We're mainly
1714 * concerned with making sure that the list of DNS servers is set up
1715 * according to which networks are connected, and ensuring that the
1716 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001718 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001719 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001722 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001723 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001725 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001727 LinkProperties curLp = mCurrentLinkProperties[netType];
1728 LinkProperties newLp = null;
1729
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001730 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001731 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001732 if (VDBG) {
1733 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1734 " doReset=" + doReset + " resetMask=" + resetMask +
1735 "\n curLp=" + curLp +
1736 "\n newLp=" + newLp);
1737 }
1738
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001739 if (curLp != null) {
1740 if (curLp.isIdenticalInterfaceName(newLp)) {
1741 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1742 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1743 for (LinkAddress linkAddr : car.removed) {
1744 if (linkAddr.getAddress() instanceof Inet4Address) {
1745 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1746 }
1747 if (linkAddr.getAddress() instanceof Inet6Address) {
1748 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1749 }
Wink Savillee8222252011-07-13 13:44:13 -07001750 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001751 if (DBG) {
1752 log("handleConnectivityChange: addresses changed" +
1753 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1754 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001755 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001756 } else {
1757 if (DBG) {
1758 log("handleConnectivityChange: address are the same reset per doReset" +
1759 " linkProperty[" + netType + "]:" +
1760 " resetMask=" + resetMask);
1761 }
Wink Savillee8222252011-07-13 13:44:13 -07001762 }
1763 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001764 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001765 if (DBG) {
1766 log("handleConnectivityChange: interface not not equivalent reset both" +
1767 " linkProperty[" + netType + "]:" +
1768 " resetMask=" + resetMask);
1769 }
Wink Savillee8222252011-07-13 13:44:13 -07001770 }
Wink Savillee8222252011-07-13 13:44:13 -07001771 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001772 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001773 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001774 }
1775 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001776 if (VDBG) {
1777 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1778 " doReset=" + doReset + " resetMask=" + resetMask +
1779 "\n curLp=" + curLp +
1780 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001783 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001784 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001785
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001786 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001787 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1788 if (linkProperties != null) {
1789 String iface = linkProperties.getInterfaceName();
1790 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001791 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001792 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1793 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001794
1795 // Tell VPN the interface is down. It is a temporary
1796 // but effective fix to make VPN aware of the change.
1797 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1798 mVpn.interfaceStatusChanged(iface, false);
1799 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001800 }
1801 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001802 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001803 try {
1804 mNetd.flushInterfaceDnsCache(iface);
1805 } catch (Exception e) {
1806 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001807 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001808 }
1809 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001810 }
1811 }
1812 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001813
1814 // TODO: Temporary notifying upstread change to Tethering.
1815 // @see bug/4455071
1816 /** Notify TetheringService if interface name has been changed. */
1817 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1818 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1819 if (isTetheringSupported()) {
1820 mTethering.handleTetherIfaceChange();
1821 }
1822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001825 /**
1826 * Add and remove routes using the old properties (null if not previously connected),
1827 * new properties (null if becoming disconnected). May even be double null, which
1828 * is a noop.
1829 * Uses isLinkDefault to determine if default routes should be set or conversely if
1830 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07001831 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001832 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07001833 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1834 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001835 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001836 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1837 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001838 if (curLp != null) {
1839 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001840 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001841 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001842 } else if (newLp != null) {
1843 routeDiff.added = newLp.getRoutes();
1844 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001845 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001846
Robert Greenwaltf125a092011-08-15 12:31:55 -07001847 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1848
Robert Greenwaltad55d352011-07-22 11:55:33 -07001849 for (RouteInfo r : routeDiff.removed) {
1850 if (isLinkDefault || ! r.isDefaultRoute()) {
1851 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001852 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001853 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001854
Robert Greenwaltad55d352011-07-22 11:55:33 -07001855 for (RouteInfo r : routeDiff.added) {
1856 if (isLinkDefault || ! r.isDefaultRoute()) {
1857 addRoute(newLp, r);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001858 } else {
1859 // many radios add a default route even when we don't want one.
1860 // remove the default route unless somebody else has asked for it
1861 String ifaceName = newLp.getInterfaceName();
1862 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07001863 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001864 try {
1865 mNetd.removeRoute(ifaceName, r);
1866 } catch (Exception e) {
1867 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001868 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001869 }
1870 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001871 }
1872 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001873
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001874 if (!isLinkDefault) {
1875 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07001876 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001877 // routes changed - remove all old dns entries and add new
1878 if (curLp != null) {
1879 for (InetAddress oldDns : curLp.getDnses()) {
1880 removeRouteToAddress(curLp, oldDns);
1881 }
1882 }
1883 if (newLp != null) {
1884 for (InetAddress newDns : newLp.getDnses()) {
1885 addRouteToAddress(newLp, newDns);
1886 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001887 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001888 } else {
1889 // no change in routes, check for change in dns themselves
1890 for (InetAddress oldDns : dnsDiff.removed) {
1891 removeRouteToAddress(curLp, oldDns);
1892 }
1893 for (InetAddress newDns : dnsDiff.added) {
1894 addRouteToAddress(newLp, newDns);
1895 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001896 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001897 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001898 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001899 }
1900
1901
Irfan Sheriffd649c122010-06-09 15:39:36 -07001902 /**
1903 * Reads the network specific TCP buffer sizes from SystemProperties
1904 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1905 * wide use
1906 */
1907 public void updateNetworkSettings(NetworkStateTracker nt) {
1908 String key = nt.getTcpBufferSizesPropName();
1909 String bufferSizes = SystemProperties.get(key);
1910
1911 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001912 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001913
1914 // Setting to default values so we won't be stuck to previous values
1915 key = "net.tcp.buffersize.default";
1916 bufferSizes = SystemProperties.get(key);
1917 }
1918
1919 // Set values in kernel
1920 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001921 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001922 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001923 + "] which comes from [" + key + "]");
1924 }
1925 setBufferSize(bufferSizes);
1926 }
1927 }
1928
1929 /**
1930 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1931 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1932 *
1933 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1934 * writeMin, writeInitial, writeMax"
1935 */
1936 private void setBufferSize(String bufferSizes) {
1937 try {
1938 String[] values = bufferSizes.split(",");
1939
1940 if (values.length == 6) {
1941 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001942 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1943 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1944 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1945 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1946 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1947 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001948 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001949 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001950 }
1951 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001952 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001953 }
1954 }
1955
Robert Greenwalt42acef32009-08-12 16:08:25 -07001956 /**
1957 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1958 * on the highest priority active net which this process requested.
1959 * If there aren't any, clear it out
1960 */
1961 private void reassessPidDns(int myPid, boolean doBump)
1962 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001963 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001964 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001965 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001966 continue;
1967 }
1968 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001969 if (nt.getNetworkInfo().isConnected() &&
1970 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001971 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001972 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001973 List pids = mNetRequestersPids[i];
1974 for (int j=0; j<pids.size(); j++) {
1975 Integer pid = (Integer)pids.get(j);
1976 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001977 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07001978 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001979 if (doBump) {
1980 bumpDns();
1981 }
1982 return;
1983 }
1984 }
1985 }
1986 }
1987 // nothing found - delete
1988 for (int i = 1; ; i++) {
1989 String prop = "net.dns" + i + "." + myPid;
1990 if (SystemProperties.get(prop).length() == 0) {
1991 if (doBump) {
1992 bumpDns();
1993 }
1994 return;
1995 }
1996 SystemProperties.set(prop, "");
1997 }
1998 }
1999
Robert Greenwalt10398722010-12-17 15:20:36 -08002000 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002001 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002002 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002003 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002004 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002005 String dnsString = dns.getHostAddress();
2006 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2007 changed = true;
2008 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2009 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002010 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002011 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002012 }
2013
2014 private void bumpDns() {
2015 /*
2016 * Bump the property that tells the name resolver library to reread
2017 * the DNS server list from the properties.
2018 */
2019 String propVal = SystemProperties.get("net.dnschange");
2020 int n = 0;
2021 if (propVal.length() != 0) {
2022 try {
2023 n = Integer.parseInt(propVal);
2024 } catch (NumberFormatException e) {}
2025 }
2026 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002027 /*
2028 * Tell the VMs to toss their DNS caches
2029 */
2030 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2031 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002032 /*
2033 * Connectivity events can happen before boot has completed ...
2034 */
2035 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002036 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002037 }
2038
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002039 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002040 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002041 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002042 boolean changed = false;
2043 int last = 0;
2044 if (dnses.size() == 0 && mDefaultDns != null) {
2045 ++last;
2046 String value = mDefaultDns.getHostAddress();
2047 if (!value.equals(SystemProperties.get("net.dns1"))) {
2048 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002049 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002050 }
2051 changed = true;
2052 SystemProperties.set("net.dns1", value);
2053 }
2054 } else {
2055 for (InetAddress dns : dnses) {
2056 ++last;
2057 String key = "net.dns" + last;
2058 String value = dns.getHostAddress();
2059 if (!changed && value.equals(SystemProperties.get(key))) {
2060 continue;
2061 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002062 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002063 log("adding dns " + value + " for " + network);
2064 }
2065 changed = true;
2066 SystemProperties.set(key, value);
2067 }
2068 }
2069 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2070 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002071 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002072 changed = true;
2073 SystemProperties.set(key, "");
2074 }
2075 mNumDnsEntries = last;
2076
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002077 if (changed) {
2078 try {
2079 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2080 mNetd.setDefaultInterfaceForDns(iface);
2081 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002082 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002083 }
2084 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002085 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2086 SystemProperties.set("net.dns.search", domains);
2087 changed = true;
2088 }
2089 return changed;
2090 }
2091
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002092 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002093 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002094 NetworkStateTracker nt = mNetTrackers[netType];
2095 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002096 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002097 if (p == null) return;
2098 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002099 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002100 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002101 String network = nt.getNetworkInfo().getTypeName();
2102 synchronized (mDnsLock) {
2103 if (!mDnsOverridden) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002104 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002105 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002106 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002107 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002108 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002109 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002110 NetworkUtils.makeStrings(dnses));
2111 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002112 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002113 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002114 // set per-pid dns for attached secondary nets
2115 List pids = mNetRequestersPids[netType];
2116 for (int y=0; y< pids.size(); y++) {
2117 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002118 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
2120 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002121 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002123 }
2124
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002125 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002126 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2127 NETWORK_RESTORE_DELAY_PROP_NAME);
2128 if(restoreDefaultNetworkDelayStr != null &&
2129 restoreDefaultNetworkDelayStr.length() != 0) {
2130 try {
2131 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2132 } catch (NumberFormatException e) {
2133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002135 // if the system property isn't set, use the value for the apn type
2136 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2137
2138 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2139 (mNetConfigs[networkType] != null)) {
2140 ret = mNetConfigs[networkType].restoreTime;
2141 }
2142 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
2144
2145 @Override
2146 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002147 if (mContext.checkCallingOrSelfPermission(
2148 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002150 pw.println("Permission Denial: can't dump ConnectivityService " +
2151 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2152 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 return;
2154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 pw.println();
2156 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002157 if (nst != null) {
2158 if (nst.getNetworkInfo().isConnected()) {
2159 pw.println("Active network: " + nst.getNetworkInfo().
2160 getTypeName());
2161 }
2162 pw.println(nst.getNetworkInfo());
2163 pw.println(nst);
2164 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002167
2168 pw.println("Network Requester Pids:");
2169 for (int net : mPriorityList) {
2170 String pidString = net + ": ";
2171 for (Object pid : mNetRequestersPids[net]) {
2172 pidString = pidString + pid.toString() + ", ";
2173 }
2174 pw.println(pidString);
2175 }
2176 pw.println();
2177
2178 pw.println("FeatureUsers:");
2179 for (Object requester : mFeatureUsers) {
2180 pw.println(requester.toString());
2181 }
2182 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002183
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002184 synchronized (this) {
2185 pw.println("NetworkTranstionWakeLock is currently " +
2186 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2187 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2188 }
2189 pw.println();
2190
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002191 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002192
2193 if (mInetLog != null) {
2194 pw.println();
2195 pw.println("Inet condition reports:");
2196 for(int i = 0; i < mInetLog.size(); i++) {
2197 pw.println(mInetLog.get(i));
2198 }
2199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201
Robert Greenwalt42acef32009-08-12 16:08:25 -07002202 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002204 public MyHandler(Looper looper) {
2205 super(looper);
2206 }
2207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 @Override
2209 public void handleMessage(Message msg) {
2210 NetworkInfo info;
2211 switch (msg.what) {
2212 case NetworkStateTracker.EVENT_STATE_CHANGED:
2213 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002214 int type = info.getType();
2215 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002216
Wink Savillec9acde92011-09-21 11:05:43 -07002217 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2218 (state == NetworkInfo.State.DISCONNECTED)) {
2219 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002220 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002221 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223
2224 // Connectivity state changed:
2225 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002226 // [12-9] Network subtype (for mobile network, as defined
2227 // by TelephonyManager)
2228 // [8-3] Detailed state ordinal (as defined by
2229 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 // [2-0] Network type (as defined by ConnectivityManager)
2231 int eventLogParam = (info.getType() & 0x7) |
2232 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2233 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002234 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002235 eventLogParam);
2236
2237 if (info.getDetailedState() ==
2238 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002240 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002242 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002244 // the logic here is, handle SUSPENDED the same as
2245 // DISCONNECTED. The only difference being we are
2246 // broadcasting an intent with NetworkInfo that's
2247 // suspended. This allows the applications an
2248 // opportunity to handle DISCONNECTED and SUSPENDED
2249 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002251 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 handleConnect(info);
2253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002256 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002257 // TODO: Temporary allowing network configuration
2258 // change not resetting sockets.
2259 // @see bug/4455071
2260 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002262 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002263 String causedBy = null;
2264 synchronized (ConnectivityService.this) {
2265 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2266 mNetTransitionWakeLock.isHeld()) {
2267 mNetTransitionWakeLock.release();
2268 causedBy = mNetTransitionWakeLockCausedBy;
2269 }
2270 }
2271 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002272 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002273 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002274 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002275 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002276 FeatureUser u = (FeatureUser)msg.obj;
2277 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002278 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002279 case EVENT_INET_CONDITION_CHANGE:
2280 {
2281 int netType = msg.arg1;
2282 int condition = msg.arg2;
2283 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002284 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002285 }
2286 case EVENT_INET_CONDITION_HOLD_END:
2287 {
2288 int netType = msg.arg1;
2289 int sequence = msg.arg2;
2290 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002291 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002292 }
2293 case EVENT_SET_NETWORK_PREFERENCE:
2294 {
2295 int preference = msg.arg1;
2296 handleSetNetworkPreference(preference);
2297 break;
2298 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002299 case EVENT_SET_MOBILE_DATA:
2300 {
2301 boolean enabled = (msg.arg1 == ENABLED);
2302 handleSetMobileData(enabled);
2303 break;
2304 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002305 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2306 {
2307 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002308 break;
2309 }
2310 case EVENT_SET_DEPENDENCY_MET:
2311 {
2312 boolean met = (msg.arg1 == ENABLED);
2313 handleSetDependencyMet(msg.arg2, met);
2314 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002315 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002316 case EVENT_RESTORE_DNS:
2317 {
2318 if (mActiveDefaultNetwork != -1) {
2319 handleDnsConfigurationChange(mActiveDefaultNetwork);
2320 }
2321 break;
2322 }
Wink Saville628b0852011-08-04 15:01:58 -07002323 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2324 {
2325 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002326 sendStickyBroadcast(intent);
2327 break;
2328 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002329 case EVENT_SET_POLICY_DATA_ENABLE: {
2330 final int networkType = msg.arg1;
2331 final boolean enabled = msg.arg2 == ENABLED;
2332 handleSetPolicyDataEnable(networkType, enabled);
2333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
2335 }
2336 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002337
2338 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002339 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002340 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002341
2342 if (isTetheringSupported()) {
2343 return mTethering.tether(iface);
2344 } else {
2345 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2346 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002347 }
2348
2349 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002350 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002351 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002352
2353 if (isTetheringSupported()) {
2354 return mTethering.untether(iface);
2355 } else {
2356 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2357 }
2358 }
2359
2360 // javadoc from interface
2361 public int getLastTetherError(String iface) {
2362 enforceTetherAccessPermission();
2363
2364 if (isTetheringSupported()) {
2365 return mTethering.getLastTetherError(iface);
2366 } else {
2367 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2368 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002369 }
2370
2371 // TODO - proper iface API for selection by property, inspection, etc
2372 public String[] getTetherableUsbRegexs() {
2373 enforceTetherAccessPermission();
2374 if (isTetheringSupported()) {
2375 return mTethering.getTetherableUsbRegexs();
2376 } else {
2377 return new String[0];
2378 }
2379 }
2380
2381 public String[] getTetherableWifiRegexs() {
2382 enforceTetherAccessPermission();
2383 if (isTetheringSupported()) {
2384 return mTethering.getTetherableWifiRegexs();
2385 } else {
2386 return new String[0];
2387 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002388 }
2389
Danica Chang6fdd0c62010-08-11 14:54:43 -07002390 public String[] getTetherableBluetoothRegexs() {
2391 enforceTetherAccessPermission();
2392 if (isTetheringSupported()) {
2393 return mTethering.getTetherableBluetoothRegexs();
2394 } else {
2395 return new String[0];
2396 }
2397 }
2398
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002399 public int setUsbTethering(boolean enable) {
2400 enforceTetherAccessPermission();
2401 if (isTetheringSupported()) {
2402 return mTethering.setUsbTethering(enable);
2403 } else {
2404 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2405 }
2406 }
2407
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002408 // TODO - move iface listing, queries, etc to new module
2409 // javadoc from interface
2410 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002411 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002412 return mTethering.getTetherableIfaces();
2413 }
2414
2415 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002416 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002417 return mTethering.getTetheredIfaces();
2418 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002419
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002420 @Override
2421 public String[] getTetheredIfacePairs() {
2422 enforceTetherAccessPermission();
2423 return mTethering.getTetheredIfacePairs();
2424 }
2425
Robert Greenwalt5a735062010-03-02 17:25:02 -08002426 public String[] getTetheringErroredIfaces() {
2427 enforceTetherAccessPermission();
2428 return mTethering.getErroredIfaces();
2429 }
2430
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002431 // if ro.tether.denied = true we default to no tethering
2432 // gservices could set the secure setting to 1 though to enable it on a build where it
2433 // had previously been turned off.
2434 public boolean isTetheringSupported() {
2435 enforceTetherAccessPermission();
2436 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002437 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2438 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2439 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002440 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002441
2442 // An API NetworkStateTrackers can call when they lose their network.
2443 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2444 // whichever happens first. The timer is started by the first caller and not
2445 // restarted by subsequent callers.
2446 public void requestNetworkTransitionWakelock(String forWhom) {
2447 enforceConnectivityInternalPermission();
2448 synchronized (this) {
2449 if (mNetTransitionWakeLock.isHeld()) return;
2450 mNetTransitionWakeLockSerialNumber++;
2451 mNetTransitionWakeLock.acquire();
2452 mNetTransitionWakeLockCausedBy = forWhom;
2453 }
2454 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002455 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002456 mNetTransitionWakeLockSerialNumber, 0),
2457 mNetTransitionWakeLockTimeout);
2458 return;
2459 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002460
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002461 // 100 percent is full good, 0 is full bad.
2462 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002463 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002464 mContext.enforceCallingOrSelfPermission(
2465 android.Manifest.permission.STATUS_BAR,
2466 "ConnectivityService");
2467
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002468 if (DBG) {
2469 int pid = getCallingPid();
2470 int uid = getCallingUid();
2471 String s = pid + "(" + uid + ") reports inet is " +
2472 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2473 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2474 mInetLog.add(s);
2475 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2476 mInetLog.remove(0);
2477 }
2478 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002479 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002480 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2481 }
2482
2483 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002484 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002485 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002486 return;
2487 }
2488 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002489 if (DBG) log("handleInetConditionChange: net=" + netType +
2490 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002491 return;
2492 }
Wink Savillec9acde92011-09-21 11:05:43 -07002493 if (VDBG) {
2494 log("handleInetConditionChange: net=" +
2495 netType + ", condition=" + condition +
2496 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2497 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002498 mDefaultInetCondition = condition;
2499 int delay;
2500 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002501 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002502 // setup a new hold to debounce this
2503 if (mDefaultInetCondition > 50) {
2504 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2505 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2506 } else {
2507 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2508 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2509 }
2510 mInetConditionChangeInFlight = true;
2511 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2512 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2513 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002514 // we've set the new condition, when this hold ends that will get picked up
2515 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002516 }
2517 }
2518
2519 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002520 if (DBG) {
2521 log("handleInetConditionHoldEnd: net=" + netType +
2522 ", condition=" + mDefaultInetCondition +
2523 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002524 }
2525 mInetConditionChangeInFlight = false;
2526
2527 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002528 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002529 return;
2530 }
2531 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002532 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002533 return;
2534 }
Wink Saville628b0852011-08-04 15:01:58 -07002535 // TODO: Figure out why this optimization sometimes causes a
2536 // change in mDefaultInetCondition to be missed and the
2537 // UI to not be updated.
2538 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2539 // if (DBG) log("no change in condition - aborting");
2540 // return;
2541 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002542 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2543 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002544 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002545 return;
2546 }
2547 mDefaultInetConditionPublished = mDefaultInetCondition;
2548 sendInetConditionBroadcast(networkInfo);
2549 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002550 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002551
2552 public synchronized ProxyProperties getProxy() {
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002553 return mDefaultProxy;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002554 }
2555
2556 public void setGlobalProxy(ProxyProperties proxyProperties) {
2557 enforceChangePermission();
2558 synchronized (mGlobalProxyLock) {
2559 if (proxyProperties == mGlobalProxy) return;
2560 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2561 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2562
2563 String host = "";
2564 int port = 0;
2565 String exclList = "";
2566 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2567 mGlobalProxy = new ProxyProperties(proxyProperties);
2568 host = mGlobalProxy.getHost();
2569 port = mGlobalProxy.getPort();
2570 exclList = mGlobalProxy.getExclusionList();
2571 } else {
2572 mGlobalProxy = null;
2573 }
2574 ContentResolver res = mContext.getContentResolver();
2575 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2576 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002577 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002578 exclList);
2579 }
2580
2581 if (mGlobalProxy == null) {
2582 proxyProperties = mDefaultProxy;
2583 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002584 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002585 }
2586
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002587 private void loadGlobalProxy() {
2588 ContentResolver res = mContext.getContentResolver();
2589 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2590 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2591 String exclList = Settings.Secure.getString(res,
2592 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2593 if (!TextUtils.isEmpty(host)) {
2594 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2595 synchronized (mGlobalProxyLock) {
2596 mGlobalProxy = proxyProperties;
2597 }
2598 }
2599 }
2600
Robert Greenwalt434203a2010-10-11 16:00:27 -07002601 public ProxyProperties getGlobalProxy() {
2602 synchronized (mGlobalProxyLock) {
2603 return mGlobalProxy;
2604 }
2605 }
2606
2607 private void handleApplyDefaultProxy(int type) {
2608 // check if new default - push it out to all VM if so
2609 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2610 synchronized (this) {
2611 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2612 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002613 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002614 mDefaultProxy = proxy;
2615 } else {
2616 mDefaultProxy = null;
2617 }
2618 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002619 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002620 sendProxyBroadcast(proxy);
2621 }
2622
2623 private void handleDeprecatedGlobalHttpProxy() {
2624 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2625 Settings.Secure.HTTP_PROXY);
2626 if (!TextUtils.isEmpty(proxy)) {
2627 String data[] = proxy.split(":");
2628 String proxyHost = data[0];
2629 int proxyPort = 8080;
2630 if (data.length > 1) {
2631 try {
2632 proxyPort = Integer.parseInt(data[1]);
2633 } catch (NumberFormatException e) {
2634 return;
2635 }
2636 }
2637 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2638 setGlobalProxy(p);
2639 }
2640 }
2641
2642 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002643 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002644 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002645 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002646 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2647 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002648 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002649 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002650 }
2651
2652 private static class SettingsObserver extends ContentObserver {
2653 private int mWhat;
2654 private Handler mHandler;
2655 SettingsObserver(Handler handler, int what) {
2656 super(handler);
2657 mHandler = handler;
2658 mWhat = what;
2659 }
2660
2661 void observe(Context context) {
2662 ContentResolver resolver = context.getContentResolver();
2663 resolver.registerContentObserver(Settings.Secure.getUriFor(
2664 Settings.Secure.HTTP_PROXY), false, this);
2665 }
2666
2667 @Override
2668 public void onChange(boolean selfChange) {
2669 mHandler.obtainMessage(mWhat).sendToTarget();
2670 }
2671 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002672
2673 private void log(String s) {
2674 Slog.d(TAG, s);
2675 }
2676
2677 private void loge(String s) {
2678 Slog.e(TAG, s);
2679 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002680
repo syncaea743a2011-07-29 23:55:49 -07002681 int convertFeatureToNetworkType(int networkType, String feature) {
2682 int usedNetworkType = networkType;
2683
2684 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2685 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2686 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2687 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2688 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2689 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2690 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2691 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2692 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2693 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2694 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2695 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2696 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2697 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2698 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2699 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2700 } else {
2701 Slog.e(TAG, "Can't match any mobile netTracker!");
2702 }
2703 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2704 if (TextUtils.equals(feature, "p2p")) {
2705 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2706 } else {
2707 Slog.e(TAG, "Can't match any wifi netTracker!");
2708 }
2709 } else {
2710 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002711 }
repo syncaea743a2011-07-29 23:55:49 -07002712 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002713 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002714
2715 private static <T> T checkNotNull(T value, String message) {
2716 if (value == null) {
2717 throw new NullPointerException(message);
2718 }
2719 return value;
2720 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002721
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002722 /**
2723 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002724 * VpnBuilder and not available in ConnectivityManager. Permissions
2725 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002726 * @hide
2727 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002728 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002729 public boolean protectVpn(ParcelFileDescriptor socket) {
2730 try {
2731 int type = mActiveDefaultNetwork;
2732 if (ConnectivityManager.isNetworkTypeValid(type)) {
2733 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2734 return true;
2735 }
2736 } catch (Exception e) {
2737 // ignore
2738 } finally {
2739 try {
2740 socket.close();
2741 } catch (Exception e) {
2742 // ignore
2743 }
2744 }
2745 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002746 }
2747
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002748 /**
2749 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002750 * and not available in ConnectivityManager. Permissions are checked
2751 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002752 * @hide
2753 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002754 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002755 public boolean prepareVpn(String oldPackage, String newPackage) {
2756 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002757 }
2758
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002759 /**
2760 * Configure a TUN interface and return its file descriptor. Parameters
2761 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002762 * and not available in ConnectivityManager. Permissions are checked in
2763 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002764 * @hide
2765 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002766 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002767 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002768 return mVpn.establish(config);
2769 }
2770
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002771 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002772 * Start legacy VPN and return an intent to VpnDialogs. This method is
2773 * used by VpnSettings and not available in ConnectivityManager.
2774 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002775 * @hide
2776 */
2777 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002778 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2779 mVpn.startLegacyVpn(config, racoon, mtpd);
2780 }
2781
2782 /**
2783 * Return the information of the ongoing legacy VPN. This method is used
2784 * by VpnSettings and not available in ConnectivityManager. Permissions
2785 * are checked in Vpn class.
2786 * @hide
2787 */
2788 @Override
2789 public LegacyVpnInfo getLegacyVpnInfo() {
2790 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002791 }
2792
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002793 /**
2794 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2795 * through NetworkStateTracker since it works differently. For example, it
2796 * needs to override DNS servers but never takes the default routes. It
2797 * relies on another data network, and it could keep existing connections
2798 * alive after reconnecting, switching between networks, or even resuming
2799 * from deep sleep. Calls from applications should be done synchronously
2800 * to avoid race conditions. As these are all hidden APIs, refactoring can
2801 * be done whenever a better abstraction is developed.
2802 */
2803 public class VpnCallback {
2804
2805 private VpnCallback() {
2806 }
2807
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002808 public void override(List<String> dnsServers, List<String> searchDomains) {
2809 if (dnsServers == null) {
2810 restore();
2811 return;
2812 }
2813
2814 // Convert DNS servers into addresses.
2815 List<InetAddress> addresses = new ArrayList<InetAddress>();
2816 for (String address : dnsServers) {
2817 // Double check the addresses and remove invalid ones.
2818 try {
2819 addresses.add(InetAddress.parseNumericAddress(address));
2820 } catch (Exception e) {
2821 // ignore
2822 }
2823 }
2824 if (addresses.isEmpty()) {
2825 restore();
2826 return;
2827 }
2828
2829 // Concatenate search domains into a string.
2830 StringBuilder buffer = new StringBuilder();
2831 if (searchDomains != null) {
2832 for (String domain : searchDomains) {
2833 buffer.append(domain).append(' ');
2834 }
2835 }
2836 String domains = buffer.toString().trim();
2837
2838 // Apply DNS changes.
2839 boolean changed = false;
2840 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002841 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002842 mDnsOverridden = true;
2843 }
2844 if (changed) {
2845 bumpDns();
2846 }
2847
2848 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002849 }
2850
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002851 public void restore() {
2852 synchronized (mDnsLock) {
2853 if (!mDnsOverridden) {
2854 return;
2855 }
2856 mDnsOverridden = false;
2857 }
2858 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002859 }
2860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861}