2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
19 import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
20 import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
21 import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
22 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
23 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
24 import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25 import static android.net.ConnectivityManager.TYPE_DUMMY;
26 import static android.net.ConnectivityManager.TYPE_ETHERNET;
27 import static android.net.ConnectivityManager.TYPE_MOBILE;
28 import static android.net.ConnectivityManager.TYPE_WIFI;
29 import static android.net.ConnectivityManager.TYPE_WIMAX;
30 import static android.net.ConnectivityManager.getNetworkTypeName;
31 import static android.net.ConnectivityManager.isNetworkTypeValid;
32 import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
33 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
35 import android.app.Activity;
36 import android.bluetooth.BluetoothTetheringDataTracker;
37 import android.content.BroadcastReceiver;
38 import android.content.ContentResolver;
39 import android.content.Context;
40 import android.content.ContextWrapper;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.content.pm.PackageManager;
44 import android.content.res.Resources;
45 import android.database.ContentObserver;
46 import android.net.CaptivePortalTracker;
47 import android.net.ConnectivityManager;
48 import android.net.DummyDataStateTracker;
49 import android.net.EthernetDataTracker;
50 import android.net.IConnectivityManager;
51 import android.net.INetworkManagementEventObserver;
52 import android.net.INetworkPolicyListener;
53 import android.net.INetworkPolicyManager;
54 import android.net.INetworkStatsService;
55 import android.net.LinkAddress;
56 import android.net.LinkProperties;
57 import android.net.LinkProperties.CompareResult;
58 import android.net.MobileDataStateTracker;
59 import android.net.NetworkConfig;
60 import android.net.NetworkInfo;
61 import android.net.NetworkInfo.DetailedState;
62 import android.net.NetworkQuotaInfo;
63 import android.net.NetworkState;
64 import android.net.NetworkStateTracker;
65 import android.net.NetworkUtils;
66 import android.net.Proxy;
67 import android.net.ProxyProperties;
68 import android.net.RouteInfo;
69 import android.net.wifi.WifiStateTracker;
70 import android.net.wimax.WimaxManagerConstants;
71 import android.os.Binder;
72 import android.os.FileUtils;
73 import android.os.Handler;
74 import android.os.HandlerThread;
75 import android.os.IBinder;
76 import android.os.INetworkManagementService;
77 import android.os.Looper;
78 import android.os.Message;
79 import android.os.ParcelFileDescriptor;
80 import android.os.PowerManager;
81 import android.os.Process;
82 import android.os.RemoteException;
83 import android.os.ServiceManager;
84 import android.os.SystemClock;
85 import android.os.SystemProperties;
86 import android.os.UserHandle;
87 import android.provider.Settings;
88 import android.security.Credentials;
89 import android.security.KeyStore;
90 import android.text.TextUtils;
91 import android.util.EventLog;
92 import android.util.Slog;
93 import android.util.SparseIntArray;
95 import com.android.internal.net.LegacyVpnInfo;
96 import com.android.internal.net.VpnConfig;
97 import com.android.internal.net.VpnProfile;
98 import com.android.internal.telephony.Phone;
99 import com.android.internal.telephony.PhoneConstants;
100 import com.android.internal.util.IndentingPrintWriter;
101 import com.android.server.am.BatteryStatsService;
102 import com.android.server.connectivity.Tethering;
103 import com.android.server.connectivity.Vpn;
104 import com.android.server.net.BaseNetworkObserver;
105 import com.android.server.net.LockdownVpnTracker;
106 import com.google.android.collect.Lists;
107 import com.google.android.collect.Sets;
109 import dalvik.system.DexClassLoader;
111 import java.io.FileDescriptor;
112 import java.io.IOException;
113 import java.io.PrintWriter;
114 import java.lang.reflect.Constructor;
115 import java.net.Inet4Address;
116 import java.net.Inet6Address;
117 import java.net.InetAddress;
118 import java.net.UnknownHostException;
119 import java.util.ArrayList;
120 import java.util.Arrays;
121 import java.util.Collection;
122 import java.util.GregorianCalendar;
123 import java.util.HashSet;
124 import java.util.List;
129 public class ConnectivityService extends IConnectivityManager.Stub {
130 private static final String TAG = "ConnectivityService";
132 private static final boolean DBG = true;
133 private static final boolean VDBG = false;
135 private static final boolean LOGD_RULES = false;
137 // TODO: create better separation between radio types and network types
139 // how long to wait before switching back to a radio's default network
140 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
141 // system property that can override the above value
142 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
143 "android.telephony.apn-restore";
145 // used in recursive route setting to add gateways for the host for which
146 // a host route was requested.
147 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
149 private Tethering mTethering;
150 private boolean mTetheringConfigValid = false;
152 private KeyStore mKeyStore;
155 private VpnCallback mVpnCallback = new VpnCallback();
157 private boolean mLockdownEnabled;
158 private LockdownVpnTracker mLockdownTracker;
160 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
161 private Object mRulesLock = new Object();
162 /** Currently active network rules by UID. */
163 private SparseIntArray mUidRules = new SparseIntArray();
164 /** Set of ifaces that are costly. */
165 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
168 * Sometimes we want to refer to the individual network state
169 * trackers separately, and sometimes we just want to treat them
172 private NetworkStateTracker mNetTrackers[];
174 /* Handles captive portal check on a network */
175 private CaptivePortalTracker mCaptivePortalTracker;
178 * The link properties that define the current links
180 private LinkProperties mCurrentLinkProperties[];
183 * A per Net list of the PID's that requested access to the net
184 * used both as a refcount and for per-PID DNS selection
186 private List mNetRequestersPids[];
188 // priority order of the nettrackers
189 // (excluding dynamically set mNetworkPreference)
190 // TODO - move mNetworkTypePreference into this
191 private int[] mPriorityList;
193 private Context mContext;
194 private int mNetworkPreference;
195 private int mActiveDefaultNetwork = -1;
196 // 0 is full bad, 100 is full good
197 private int mDefaultInetCondition = 0;
198 private int mDefaultInetConditionPublished = 0;
199 private boolean mInetConditionChangeInFlight = false;
200 private int mDefaultConnectionSequence = 0;
202 private Object mDnsLock = new Object();
203 private int mNumDnsEntries;
204 private boolean mDnsOverridden = false;
206 private boolean mTestMode;
207 private static ConnectivityService sServiceInstance;
209 private INetworkManagementService mNetd;
210 private INetworkPolicyManager mPolicyManager;
212 private static final int ENABLED = 1;
213 private static final int DISABLED = 0;
215 private static final boolean ADD = true;
216 private static final boolean REMOVE = false;
218 private static final boolean TO_DEFAULT_TABLE = true;
219 private static final boolean TO_SECONDARY_TABLE = false;
222 * used internally as a delayed event to make us switch back to the
225 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
228 * used internally to change our mobile data enabled flag
230 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
233 * used internally to change our network preference setting
234 * arg1 = networkType to prefer
236 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
239 * used internally to synchronize inet condition reports
241 * arg2 = condition (0 bad, 100 good)
243 private static final int EVENT_INET_CONDITION_CHANGE = 4;
246 * used internally to mark the end of inet condition hold periods
249 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
252 * used internally to set enable/disable cellular data
253 * arg1 = ENBALED or DISABLED
255 private static final int EVENT_SET_MOBILE_DATA = 7;
258 * used internally to clear a wakelock when transitioning
259 * from one net to another
261 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
264 * used internally to reload global proxy settings
266 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
269 * used internally to set external dependency met/unmet
270 * arg1 = ENABLED (met) or DISABLED (unmet)
273 private static final int EVENT_SET_DEPENDENCY_MET = 10;
276 * used internally to restore DNS properties back to the
279 private static final int EVENT_RESTORE_DNS = 11;
282 * used internally to send a sticky broadcast delayed.
284 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
288 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
290 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
292 private static final int EVENT_VPN_STATE_CHANGED = 14;
294 /** Handler used for internal events. */
295 private InternalHandler mHandler;
296 /** Handler used for incoming {@link NetworkStateTracker} events. */
297 private NetworkStateTrackerHandler mTrackerHandler;
299 // list of DeathRecipients used to make sure features are turned off when
301 private List<FeatureUser> mFeatureUsers;
303 private boolean mSystemReady;
304 private Intent mInitialBroadcast;
306 private PowerManager.WakeLock mNetTransitionWakeLock;
307 private String mNetTransitionWakeLockCausedBy = "";
308 private int mNetTransitionWakeLockSerialNumber;
309 private int mNetTransitionWakeLockTimeout;
311 private InetAddress mDefaultDns;
313 // this collection is used to refcount the added routes - if there are none left
314 // it's time to remove the route from the route table
315 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
317 // used in DBG mode to track inet condition reports
318 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
319 private ArrayList mInetLog;
321 // track the current default http proxy - tell the world if we get a new one (real change)
322 private ProxyProperties mDefaultProxy = null;
323 private Object mDefaultProxyLock = new Object();
324 private boolean mDefaultProxyDisabled = false;
326 // track the global proxy.
327 private ProxyProperties mGlobalProxy = null;
328 private final Object mGlobalProxyLock = new Object();
330 private SettingsObserver mSettingsObserver;
332 NetworkConfig[] mNetConfigs;
333 int mNetworksDefined;
335 private static class RadioAttributes {
336 public int mSimultaneity;
338 public RadioAttributes(String init) {
339 String fragments[] = init.split(",");
340 mType = Integer.parseInt(fragments[0]);
341 mSimultaneity = Integer.parseInt(fragments[1]);
344 RadioAttributes[] mRadioAttributes;
346 // the set of network types that can only be enabled by system/sig apps
347 List mProtectedNetworks;
349 public ConnectivityService(Context context, INetworkManagementService netd,
350 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
351 // Currently, omitting a NetworkFactory will create one internally
352 // TODO: create here when we have cleaner WiMAX support
353 this(context, netd, statsService, policyManager, null);
356 public ConnectivityService(Context context, INetworkManagementService netManager,
357 INetworkStatsService statsService, INetworkPolicyManager policyManager,
358 NetworkFactory netFactory) {
359 if (DBG) log("ConnectivityService starting up");
361 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
362 handlerThread.start();
363 mHandler = new InternalHandler(handlerThread.getLooper());
364 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
366 if (netFactory == null) {
367 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
370 // setup our unique device name
371 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
372 String id = Settings.Secure.getString(context.getContentResolver(),
373 Settings.Secure.ANDROID_ID);
374 if (id != null && id.length() > 0) {
375 String name = new String("android-").concat(id);
376 SystemProperties.set("net.hostname", name);
380 // read our default dns server ip
381 String dns = Settings.Global.getString(context.getContentResolver(),
382 Settings.Global.DEFAULT_DNS_SERVER);
383 if (dns == null || dns.length() == 0) {
384 dns = context.getResources().getString(
385 com.android.internal.R.string.config_default_dns_server);
388 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
389 } catch (IllegalArgumentException e) {
390 loge("Error setting defaultDns using " + dns);
393 mContext = checkNotNull(context, "missing Context");
394 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
395 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
396 mKeyStore = KeyStore.getInstance();
399 mPolicyManager.registerListener(mPolicyListener);
400 } catch (RemoteException e) {
401 // ouch, no rules updates means some processes may never get network
402 loge("unable to register INetworkPolicyListener" + e.toString());
405 final PowerManager powerManager = (PowerManager) context.getSystemService(
406 Context.POWER_SERVICE);
407 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
408 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
409 com.android.internal.R.integer.config_networkTransitionTimeout);
411 mNetTrackers = new NetworkStateTracker[
412 ConnectivityManager.MAX_NETWORK_TYPE+1];
413 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
415 mNetworkPreference = getPersistedNetworkPreference();
417 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
418 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
420 // Load device network attributes from resources
421 String[] raStrings = context.getResources().getStringArray(
422 com.android.internal.R.array.radioAttributes);
423 for (String raString : raStrings) {
424 RadioAttributes r = new RadioAttributes(raString);
425 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
426 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
429 if (mRadioAttributes[r.mType] != null) {
430 loge("Error in radioAttributes - ignoring attempt to redefine type " +
434 mRadioAttributes[r.mType] = r;
437 String[] naStrings = context.getResources().getStringArray(
438 com.android.internal.R.array.networkAttributes);
439 for (String naString : naStrings) {
441 NetworkConfig n = new NetworkConfig(naString);
442 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
443 loge("Error in networkAttributes - ignoring attempt to define type " +
447 if (mNetConfigs[n.type] != null) {
448 loge("Error in networkAttributes - ignoring attempt to redefine type " +
452 if (mRadioAttributes[n.radio] == null) {
453 loge("Error in networkAttributes - ignoring attempt to use undefined " +
454 "radio " + n.radio + " in network type " + n.type);
457 mNetConfigs[n.type] = n;
459 } catch(Exception e) {
460 // ignore it - leave the entry null
464 mProtectedNetworks = new ArrayList<Integer>();
465 int[] protectedNetworks = context.getResources().getIntArray(
466 com.android.internal.R.array.config_protectedNetworks);
467 for (int p : protectedNetworks) {
468 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
469 mProtectedNetworks.add(p);
471 if (DBG) loge("Ignoring protectedNetwork " + p);
475 // high priority first
476 mPriorityList = new int[mNetworksDefined];
478 int insertionPoint = mNetworksDefined-1;
479 int currentLowest = 0;
481 while (insertionPoint > -1) {
482 for (NetworkConfig na : mNetConfigs) {
483 if (na == null) continue;
484 if (na.priority < currentLowest) continue;
485 if (na.priority > currentLowest) {
486 if (na.priority < nextLowest || nextLowest == 0) {
487 nextLowest = na.priority;
491 mPriorityList[insertionPoint--] = na.type;
493 currentLowest = nextLowest;
498 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
499 for (int i : mPriorityList) {
500 mNetRequestersPids[i] = new ArrayList();
503 mFeatureUsers = new ArrayList<FeatureUser>();
507 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
508 && SystemProperties.get("ro.build.type").equals("eng");
510 // Create and start trackers for hard-coded networks
511 for (int targetNetworkType : mPriorityList) {
512 final NetworkConfig config = mNetConfigs[targetNetworkType];
513 final NetworkStateTracker tracker;
515 tracker = netFactory.createTracker(targetNetworkType, config);
516 mNetTrackers[targetNetworkType] = tracker;
517 } catch (IllegalArgumentException e) {
518 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
523 tracker.startMonitoring(context, mTrackerHandler);
524 if (config.isDefault()) {
529 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
530 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
531 mTethering.getTetherableWifiRegexs().length != 0 ||
532 mTethering.getTetherableBluetoothRegexs().length != 0) &&
533 mTethering.getUpstreamIfaceTypes().length != 0);
535 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
536 mVpn.startMonitoring(mContext, mTrackerHandler);
539 mNetd.registerObserver(mTethering);
540 mNetd.registerObserver(mDataActivityObserver);
541 } catch (RemoteException e) {
542 loge("Error registering observer :" + e);
546 mInetLog = new ArrayList();
549 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
550 mSettingsObserver.observe(mContext);
552 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
557 * Factory that creates {@link NetworkStateTracker} instances using given
558 * {@link NetworkConfig}.
560 public interface NetworkFactory {
561 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
564 private static class DefaultNetworkFactory implements NetworkFactory {
565 private final Context mContext;
566 private final Handler mTrackerHandler;
568 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
570 mTrackerHandler = trackerHandler;
574 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
575 switch (config.radio) {
577 return new WifiStateTracker(targetNetworkType, config.name);
579 return new MobileDataStateTracker(targetNetworkType, config.name);
581 return new DummyDataStateTracker(targetNetworkType, config.name);
583 return BluetoothTetheringDataTracker.getInstance();
585 return makeWimaxStateTracker(mContext, mTrackerHandler);
587 return EthernetDataTracker.getInstance();
589 throw new IllegalArgumentException(
590 "Trying to create a NetworkStateTracker for an unknown radio type: "
597 * Loads external WiMAX library and registers as system service, returning a
598 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
599 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
601 private static NetworkStateTracker makeWimaxStateTracker(
602 Context context, Handler trackerHandler) {
604 DexClassLoader wimaxClassLoader;
605 Class wimaxStateTrackerClass = null;
606 Class wimaxServiceClass = null;
607 Class wimaxManagerClass;
608 String wimaxJarLocation;
609 String wimaxLibLocation;
610 String wimaxManagerClassName;
611 String wimaxServiceClassName;
612 String wimaxStateTrackerClassName;
614 NetworkStateTracker wimaxStateTracker = null;
616 boolean isWimaxEnabled = context.getResources().getBoolean(
617 com.android.internal.R.bool.config_wimaxEnabled);
619 if (isWimaxEnabled) {
621 wimaxJarLocation = context.getResources().getString(
622 com.android.internal.R.string.config_wimaxServiceJarLocation);
623 wimaxLibLocation = context.getResources().getString(
624 com.android.internal.R.string.config_wimaxNativeLibLocation);
625 wimaxManagerClassName = context.getResources().getString(
626 com.android.internal.R.string.config_wimaxManagerClassname);
627 wimaxServiceClassName = context.getResources().getString(
628 com.android.internal.R.string.config_wimaxServiceClassname);
629 wimaxStateTrackerClassName = context.getResources().getString(
630 com.android.internal.R.string.config_wimaxStateTrackerClassname);
632 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
633 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
634 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
635 wimaxLibLocation, ClassLoader.getSystemClassLoader());
638 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
639 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
640 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
641 } catch (ClassNotFoundException ex) {
642 loge("Exception finding Wimax classes: " + ex.toString());
645 } catch(Resources.NotFoundException ex) {
646 loge("Wimax Resources does not exist!!! ");
651 if (DBG) log("Starting Wimax Service... ");
653 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
654 (new Class[] {Context.class, Handler.class});
655 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
656 context, trackerHandler);
658 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
659 (new Class[] {Context.class, wimaxStateTrackerClass});
660 wmxSrvConst.setAccessible(true);
661 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
662 wmxSrvConst.setAccessible(false);
664 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
666 } catch(Exception ex) {
667 loge("Exception creating Wimax classes: " + ex.toString());
671 loge("Wimax is not enabled or not added to the network attributes!!! ");
675 return wimaxStateTracker;
679 * Sets the preferred network.
680 * @param preference the new preference
682 public void setNetworkPreference(int preference) {
683 enforceChangePermission();
685 mHandler.sendMessage(
686 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
689 public int getNetworkPreference() {
690 enforceAccessPermission();
693 preference = mNetworkPreference;
698 private void handleSetNetworkPreference(int preference) {
699 if (ConnectivityManager.isNetworkTypeValid(preference) &&
700 mNetConfigs[preference] != null &&
701 mNetConfigs[preference].isDefault()) {
702 if (mNetworkPreference != preference) {
703 final ContentResolver cr = mContext.getContentResolver();
704 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
706 mNetworkPreference = preference;
713 private int getConnectivityChangeDelay() {
714 final ContentResolver cr = mContext.getContentResolver();
716 /** Check system properties for the default value then use secure settings value, if any. */
717 int defaultDelay = SystemProperties.getInt(
718 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
719 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
720 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
724 private int getPersistedNetworkPreference() {
725 final ContentResolver cr = mContext.getContentResolver();
727 final int networkPrefSetting = Settings.Global
728 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
729 if (networkPrefSetting != -1) {
730 return networkPrefSetting;
733 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
737 * Make the state of network connectivity conform to the preference settings
738 * In this method, we only tear down a non-preferred network. Establishing
739 * a connection to the preferred network is taken care of when we handle
740 * the disconnect event from the non-preferred network
741 * (see {@link #handleDisconnect(NetworkInfo)}).
743 private void enforcePreference() {
744 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
747 if (!mNetTrackers[mNetworkPreference].isAvailable())
750 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
751 if (t != mNetworkPreference && mNetTrackers[t] != null &&
752 mNetTrackers[t].getNetworkInfo().isConnected()) {
754 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
755 " in enforcePreference");
757 teardown(mNetTrackers[t]);
762 private boolean teardown(NetworkStateTracker netTracker) {
763 if (netTracker.teardown()) {
764 netTracker.setTeardownRequested(true);
772 * Check if UID should be blocked from using the network represented by the
773 * given {@link NetworkStateTracker}.
775 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
776 final String iface = tracker.getLinkProperties().getInterfaceName();
778 final boolean networkCostly;
780 synchronized (mRulesLock) {
781 networkCostly = mMeteredIfaces.contains(iface);
782 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
785 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
789 // no restrictive rules; network is visible
794 * Return a filtered {@link NetworkInfo}, potentially marked
795 * {@link DetailedState#BLOCKED} based on
796 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
798 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
799 NetworkInfo info = tracker.getNetworkInfo();
800 if (isNetworkBlocked(tracker, uid)) {
801 // network is blocked; clone and override state
802 info = new NetworkInfo(info);
803 info.setDetailedState(DetailedState.BLOCKED, null, null);
805 if (mLockdownTracker != null) {
806 info = mLockdownTracker.augmentNetworkInfo(info);
812 * Return NetworkInfo for the active (i.e., connected) network interface.
813 * It is assumed that at most one network is active at a time. If more
814 * than one is active, it is indeterminate which will be returned.
815 * @return the info for the active network, or {@code null} if none is
819 public NetworkInfo getActiveNetworkInfo() {
820 enforceAccessPermission();
821 final int uid = Binder.getCallingUid();
822 return getNetworkInfo(mActiveDefaultNetwork, uid);
825 public NetworkInfo getActiveNetworkInfoUnfiltered() {
826 enforceAccessPermission();
827 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
828 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
829 if (tracker != null) {
830 return tracker.getNetworkInfo();
837 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
838 enforceConnectivityInternalPermission();
839 return getNetworkInfo(mActiveDefaultNetwork, uid);
843 public NetworkInfo getNetworkInfo(int networkType) {
844 enforceAccessPermission();
845 final int uid = Binder.getCallingUid();
846 return getNetworkInfo(networkType, uid);
849 private NetworkInfo getNetworkInfo(int networkType, int uid) {
850 NetworkInfo info = null;
851 if (isNetworkTypeValid(networkType)) {
852 final NetworkStateTracker tracker = mNetTrackers[networkType];
853 if (tracker != null) {
854 info = getFilteredNetworkInfo(tracker, uid);
861 public NetworkInfo[] getAllNetworkInfo() {
862 enforceAccessPermission();
863 final int uid = Binder.getCallingUid();
864 final ArrayList<NetworkInfo> result = Lists.newArrayList();
865 synchronized (mRulesLock) {
866 for (NetworkStateTracker tracker : mNetTrackers) {
867 if (tracker != null) {
868 result.add(getFilteredNetworkInfo(tracker, uid));
872 return result.toArray(new NetworkInfo[result.size()]);
876 public boolean isNetworkSupported(int networkType) {
877 enforceAccessPermission();
878 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
882 * Return LinkProperties for the active (i.e., connected) default
883 * network interface. It is assumed that at most one default network
884 * is active at a time. If more than one is active, it is indeterminate
885 * which will be returned.
886 * @return the ip properties for the active network, or {@code null} if
890 public LinkProperties getActiveLinkProperties() {
891 return getLinkProperties(mActiveDefaultNetwork);
895 public LinkProperties getLinkProperties(int networkType) {
896 enforceAccessPermission();
897 if (isNetworkTypeValid(networkType)) {
898 final NetworkStateTracker tracker = mNetTrackers[networkType];
899 if (tracker != null) {
900 return tracker.getLinkProperties();
907 public NetworkState[] getAllNetworkState() {
908 enforceAccessPermission();
909 final int uid = Binder.getCallingUid();
910 final ArrayList<NetworkState> result = Lists.newArrayList();
911 synchronized (mRulesLock) {
912 for (NetworkStateTracker tracker : mNetTrackers) {
913 if (tracker != null) {
914 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
915 result.add(new NetworkState(
916 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
920 return result.toArray(new NetworkState[result.size()]);
923 private NetworkState getNetworkStateUnchecked(int networkType) {
924 if (isNetworkTypeValid(networkType)) {
925 final NetworkStateTracker tracker = mNetTrackers[networkType];
926 if (tracker != null) {
927 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
928 tracker.getLinkCapabilities());
935 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
936 enforceAccessPermission();
938 final long token = Binder.clearCallingIdentity();
940 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
943 return mPolicyManager.getNetworkQuotaInfo(state);
944 } catch (RemoteException e) {
949 Binder.restoreCallingIdentity(token);
954 public boolean isActiveNetworkMetered() {
955 enforceAccessPermission();
956 final long token = Binder.clearCallingIdentity();
958 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
960 Binder.restoreCallingIdentity(token);
964 private boolean isNetworkMeteredUnchecked(int networkType) {
965 final NetworkState state = getNetworkStateUnchecked(networkType);
968 return mPolicyManager.isNetworkMetered(state);
969 } catch (RemoteException e) {
975 public boolean setRadios(boolean turnOn) {
976 boolean result = true;
977 enforceChangePermission();
978 for (NetworkStateTracker t : mNetTrackers) {
979 if (t != null) result = t.setRadio(turnOn) && result;
984 public boolean setRadio(int netType, boolean turnOn) {
985 enforceChangePermission();
986 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
989 NetworkStateTracker tracker = mNetTrackers[netType];
990 return tracker != null && tracker.setRadio(turnOn);
993 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
995 public void interfaceClassDataActivityChanged(String label, boolean active) {
996 int deviceType = Integer.parseInt(label);
997 sendDataActivityBroadcast(deviceType, active);
1002 * Used to notice when the calling process dies so we can self-expire
1004 * Also used to know if the process has cleaned up after itself when
1005 * our auto-expire timer goes off. The timer has a link to an object.
1008 private class FeatureUser implements IBinder.DeathRecipient {
1016 FeatureUser(int type, String feature, IBinder binder) {
1018 mNetworkType = type;
1021 mPid = getCallingPid();
1022 mUid = getCallingUid();
1023 mCreateTime = System.currentTimeMillis();
1026 mBinder.linkToDeath(this, 0);
1027 } catch (RemoteException e) {
1032 void unlinkDeathRecipient() {
1033 mBinder.unlinkToDeath(this, 0);
1036 public void binderDied() {
1037 log("ConnectivityService FeatureUser binderDied(" +
1038 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1039 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1040 stopUsingNetworkFeature(this, false);
1043 public void expire() {
1045 log("ConnectivityService FeatureUser expire(" +
1046 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1047 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1049 stopUsingNetworkFeature(this, false);
1052 public boolean isSameUser(FeatureUser u) {
1053 if (u == null) return false;
1055 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1058 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1059 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1060 TextUtils.equals(mFeature, feature)) {
1066 public String toString() {
1067 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1068 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1072 // javadoc from interface
1073 public int startUsingNetworkFeature(int networkType, String feature,
1077 startTime = SystemClock.elapsedRealtime();
1080 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1081 + Binder.getCallingUid());
1083 enforceChangePermission();
1085 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1086 mNetConfigs[networkType] == null) {
1087 return PhoneConstants.APN_REQUEST_FAILED;
1090 FeatureUser f = new FeatureUser(networkType, feature, binder);
1092 // TODO - move this into individual networktrackers
1093 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1095 if (mLockdownEnabled) {
1096 // Since carrier APNs usually aren't available from VPN
1097 // endpoint, mark them as unavailable.
1098 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1101 if (mProtectedNetworks.contains(usedNetworkType)) {
1102 enforceConnectivityInternalPermission();
1105 // if UID is restricted, don't allow them to bring up metered APNs
1106 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1108 synchronized (mRulesLock) {
1109 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1111 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1112 return PhoneConstants.APN_REQUEST_FAILED;
1115 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1116 if (network != null) {
1117 Integer currentPid = new Integer(getCallingPid());
1118 if (usedNetworkType != networkType) {
1119 NetworkInfo ni = network.getNetworkInfo();
1121 if (ni.isAvailable() == false) {
1122 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1123 if (DBG) log("special network not available ni=" + ni.getTypeName());
1124 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1126 // else make the attempt anyway - probably giving REQUEST_STARTED below
1128 log("special network not available, but try anyway ni=" +
1134 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1136 synchronized(this) {
1137 boolean addToList = true;
1138 if (restoreTimer < 0) {
1139 // In case there is no timer is specified for the feature,
1140 // make sure we don't add duplicate entry with the same request.
1141 for (FeatureUser u : mFeatureUsers) {
1142 if (u.isSameUser(f)) {
1143 // Duplicate user is found. Do not add.
1150 if (addToList) mFeatureUsers.add(f);
1151 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1152 // this gets used for per-pid dns when connected
1153 mNetRequestersPids[usedNetworkType].add(currentPid);
1157 if (restoreTimer >= 0) {
1158 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1159 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1162 if ((ni.isConnectedOrConnecting() == true) &&
1163 !network.isTeardownRequested()) {
1164 if (ni.isConnected() == true) {
1165 final long token = Binder.clearCallingIdentity();
1167 // add the pid-specific dns
1168 handleDnsConfigurationChange(usedNetworkType);
1169 if (VDBG) log("special network already active");
1171 Binder.restoreCallingIdentity(token);
1173 return PhoneConstants.APN_ALREADY_ACTIVE;
1175 if (VDBG) log("special network already connecting");
1176 return PhoneConstants.APN_REQUEST_STARTED;
1179 // check if the radio in play can make another contact
1180 // assume if cannot for now
1183 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1186 if (network.reconnect()) {
1187 return PhoneConstants.APN_REQUEST_STARTED;
1189 return PhoneConstants.APN_REQUEST_FAILED;
1192 // need to remember this unsupported request so we respond appropriately on stop
1193 synchronized(this) {
1194 mFeatureUsers.add(f);
1195 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1196 // this gets used for per-pid dns when connected
1197 mNetRequestersPids[usedNetworkType].add(currentPid);
1203 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1206 final long execTime = SystemClock.elapsedRealtime() - startTime;
1207 if (execTime > 250) {
1208 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1210 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1216 // javadoc from interface
1217 public int stopUsingNetworkFeature(int networkType, String feature) {
1218 enforceChangePermission();
1220 int pid = getCallingPid();
1221 int uid = getCallingUid();
1223 FeatureUser u = null;
1224 boolean found = false;
1226 synchronized(this) {
1227 for (FeatureUser x : mFeatureUsers) {
1228 if (x.isSameUser(pid, uid, networkType, feature)) {
1235 if (found && u != null) {
1236 // stop regardless of how many other time this proc had called start
1237 return stopUsingNetworkFeature(u, true);
1240 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
1245 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1246 int networkType = u.mNetworkType;
1247 String feature = u.mFeature;
1251 NetworkStateTracker tracker = null;
1252 boolean callTeardown = false; // used to carry our decision outside of sync block
1255 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1258 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1260 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1261 ", net is invalid");
1266 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1268 synchronized(this) {
1269 // check if this process still has an outstanding start request
1270 if (!mFeatureUsers.contains(u)) {
1272 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1277 u.unlinkDeathRecipient();
1278 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1279 // If we care about duplicate requests, check for that here.
1281 // This is done to support the extension of a request - the app
1282 // can request we start the network feature again and renew the
1283 // auto-shutoff delay. Normal "stop" calls from the app though
1284 // do not pay attention to duplicate requests - in effect the
1285 // API does not refcount and a single stop will counter multiple starts.
1286 if (ignoreDups == false) {
1287 for (FeatureUser x : mFeatureUsers) {
1288 if (x.isSameUser(u)) {
1289 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1295 // TODO - move to individual network trackers
1296 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1298 tracker = mNetTrackers[usedNetworkType];
1299 if (tracker == null) {
1301 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1302 " no known tracker for used net type " + usedNetworkType);
1306 if (usedNetworkType != networkType) {
1307 Integer currentPid = new Integer(pid);
1308 mNetRequestersPids[usedNetworkType].remove(currentPid);
1309 reassessPidDns(pid, true);
1310 if (mNetRequestersPids[usedNetworkType].size() != 0) {
1312 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1313 " others still using it");
1317 callTeardown = true;
1320 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1321 " not a known feature - dropping");
1328 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1338 * @deprecated use requestRouteToHostAddress instead
1340 * Ensure that a network route exists to deliver traffic to the specified
1341 * host via the specified network interface.
1342 * @param networkType the type of the network over which traffic to the
1343 * specified host is to be routed
1344 * @param hostAddress the IP address of the host to which the route is
1346 * @return {@code true} on success, {@code false} on failure
1348 public boolean requestRouteToHost(int networkType, int hostAddress) {
1349 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1351 if (inetAddress == null) {
1355 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1359 * Ensure that a network route exists to deliver traffic to the specified
1360 * host via the specified network interface.
1361 * @param networkType the type of the network over which traffic to the
1362 * specified host is to be routed
1363 * @param hostAddress the IP address of the host to which the route is
1365 * @return {@code true} on success, {@code false} on failure
1367 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1368 enforceChangePermission();
1369 if (mProtectedNetworks.contains(networkType)) {
1370 enforceConnectivityInternalPermission();
1373 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1374 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1377 NetworkStateTracker tracker = mNetTrackers[networkType];
1378 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
1380 if (tracker == null || (netState != DetailedState.CONNECTED &&
1381 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1382 tracker.isTeardownRequested()) {
1384 log("requestRouteToHostAddress on down network " +
1385 "(" + networkType + ") - dropped");
1389 final long token = Binder.clearCallingIdentity();
1391 InetAddress addr = InetAddress.getByAddress(hostAddress);
1392 LinkProperties lp = tracker.getLinkProperties();
1393 return addRouteToAddress(lp, addr);
1394 } catch (UnknownHostException e) {
1395 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1397 Binder.restoreCallingIdentity(token);
1402 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1403 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
1406 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1407 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
1410 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1411 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
1414 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1415 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
1418 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1419 boolean toDefaultTable) {
1420 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1421 if (bestRoute == null) {
1422 bestRoute = RouteInfo.makeHostRoute(addr);
1424 if (bestRoute.getGateway().equals(addr)) {
1425 // if there is no better route, add the implied hostroute for our gateway
1426 bestRoute = RouteInfo.makeHostRoute(addr);
1428 // if we will connect to this through another route, add a direct route
1430 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1433 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
1436 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1437 boolean doAdd, boolean toDefaultTable) {
1438 if ((ifaceName == null) || (lp == null) || (r == null)) {
1439 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1443 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1444 loge("Error modifying route - too much recursion");
1448 if (r.isHostRoute() == false) {
1449 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1450 if (bestRoute != null) {
1451 if (bestRoute.getGateway().equals(r.getGateway())) {
1452 // if there is no better route, add the implied hostroute for our gateway
1453 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
1455 // if we will connect to our gateway through another route, add a direct
1456 // route to it's gateway
1457 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
1459 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
1463 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1465 if (toDefaultTable) {
1466 mAddedRoutes.add(r); // only track default table - only one apps can effect
1467 mNetd.addRoute(ifaceName, r);
1469 mNetd.addSecondaryRoute(ifaceName, r);
1471 } catch (Exception e) {
1472 // never crash - catch them all
1473 if (DBG) loge("Exception trying to add a route: " + e);
1477 // if we remove this one and there are no more like it, then refcount==0 and
1478 // we can remove it from the table
1479 if (toDefaultTable) {
1480 mAddedRoutes.remove(r);
1481 if (mAddedRoutes.contains(r) == false) {
1482 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1484 mNetd.removeRoute(ifaceName, r);
1485 } catch (Exception e) {
1486 // never crash - catch them all
1487 if (VDBG) loge("Exception trying to remove a route: " + e);
1491 if (VDBG) log("not removing " + r + " as it's still in use");
1494 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1496 mNetd.removeSecondaryRoute(ifaceName, r);
1497 } catch (Exception e) {
1498 // never crash - catch them all
1499 if (VDBG) loge("Exception trying to remove a route: " + e);
1508 * @see ConnectivityManager#getMobileDataEnabled()
1510 public boolean getMobileDataEnabled() {
1511 // TODO: This detail should probably be in DataConnectionTracker's
1512 // which is where we store the value and maybe make this
1514 enforceAccessPermission();
1515 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1516 Settings.Global.MOBILE_DATA, 1) == 1;
1517 if (VDBG) log("getMobileDataEnabled returning " + retVal);
1521 public void setDataDependency(int networkType, boolean met) {
1522 enforceConnectivityInternalPermission();
1524 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1525 (met ? ENABLED : DISABLED), networkType));
1528 private void handleSetDependencyMet(int networkType, boolean met) {
1529 if (mNetTrackers[networkType] != null) {
1531 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1533 mNetTrackers[networkType].setDependencyMet(met);
1537 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1539 public void onUidRulesChanged(int uid, int uidRules) {
1540 // caller is NPMS, since we only register with them
1542 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1545 synchronized (mRulesLock) {
1546 // skip update when we've already applied rules
1547 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1548 if (oldRules == uidRules) return;
1550 mUidRules.put(uid, uidRules);
1553 // TODO: notify UID when it has requested targeted updates
1557 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1558 // caller is NPMS, since we only register with them
1560 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1563 synchronized (mRulesLock) {
1564 mMeteredIfaces.clear();
1565 for (String iface : meteredIfaces) {
1566 mMeteredIfaces.add(iface);
1572 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1573 // caller is NPMS, since we only register with them
1575 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1578 // kick off connectivity change broadcast for active network, since
1579 // global background policy change is radical.
1580 final int networkType = mActiveDefaultNetwork;
1581 if (isNetworkTypeValid(networkType)) {
1582 final NetworkStateTracker tracker = mNetTrackers[networkType];
1583 if (tracker != null) {
1584 final NetworkInfo info = tracker.getNetworkInfo();
1585 if (info != null && info.isConnected()) {
1586 sendConnectedBroadcast(info);
1594 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1596 public void setMobileDataEnabled(boolean enabled) {
1597 enforceChangePermission();
1598 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1600 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1601 (enabled ? ENABLED : DISABLED), 0));
1604 private void handleSetMobileData(boolean enabled) {
1605 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1607 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1609 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1611 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1613 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1615 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1620 public void setPolicyDataEnable(int networkType, boolean enabled) {
1621 // only someone like NPMS should only be calling us
1622 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1624 mHandler.sendMessage(mHandler.obtainMessage(
1625 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1628 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1629 if (isNetworkTypeValid(networkType)) {
1630 final NetworkStateTracker tracker = mNetTrackers[networkType];
1631 if (tracker != null) {
1632 tracker.setPolicyDataEnable(enabled);
1637 private void enforceAccessPermission() {
1638 mContext.enforceCallingOrSelfPermission(
1639 android.Manifest.permission.ACCESS_NETWORK_STATE,
1640 "ConnectivityService");
1643 private void enforceChangePermission() {
1644 mContext.enforceCallingOrSelfPermission(
1645 android.Manifest.permission.CHANGE_NETWORK_STATE,
1646 "ConnectivityService");
1649 // TODO Make this a special check when it goes public
1650 private void enforceTetherChangePermission() {
1651 mContext.enforceCallingOrSelfPermission(
1652 android.Manifest.permission.CHANGE_NETWORK_STATE,
1653 "ConnectivityService");
1656 private void enforceTetherAccessPermission() {
1657 mContext.enforceCallingOrSelfPermission(
1658 android.Manifest.permission.ACCESS_NETWORK_STATE,
1659 "ConnectivityService");
1662 private void enforceConnectivityInternalPermission() {
1663 mContext.enforceCallingOrSelfPermission(
1664 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1665 "ConnectivityService");
1669 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1670 * network, we ignore it. If it is for the active network, we send out a
1671 * broadcast. But first, we check whether it might be possible to connect
1672 * to a different network.
1673 * @param info the {@code NetworkInfo} for the network
1675 private void handleDisconnect(NetworkInfo info) {
1677 int prevNetType = info.getType();
1679 mNetTrackers[prevNetType].setTeardownRequested(false);
1681 // Remove idletimer previously setup in {@code handleConnect}
1682 removeDataActivityTracking(prevNetType);
1685 * If the disconnected network is not the active one, then don't report
1686 * this as a loss of connectivity. What probably happened is that we're
1687 * getting the disconnect for a network that we explicitly disabled
1688 * in accordance with network preference policies.
1690 if (!mNetConfigs[prevNetType].isDefault()) {
1691 List pids = mNetRequestersPids[prevNetType];
1692 for (int i = 0; i<pids.size(); i++) {
1693 Integer pid = (Integer)pids.get(i);
1694 // will remove them because the net's no longer connected
1695 // need to do this now as only now do we know the pids and
1696 // can properly null things that are no longer referenced.
1697 reassessPidDns(pid.intValue(), false);
1701 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1702 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1703 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1704 if (info.isFailover()) {
1705 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1706 info.setFailover(false);
1708 if (info.getReason() != null) {
1709 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1711 if (info.getExtraInfo() != null) {
1712 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1713 info.getExtraInfo());
1716 if (mNetConfigs[prevNetType].isDefault()) {
1717 tryFailover(prevNetType);
1718 if (mActiveDefaultNetwork != -1) {
1719 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1720 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1722 mDefaultInetConditionPublished = 0; // we're not connected anymore
1723 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1726 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1728 // Reset interface if no other connections are using the same interface
1729 boolean doReset = true;
1730 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1731 if (linkProperties != null) {
1732 String oldIface = linkProperties.getInterfaceName();
1733 if (TextUtils.isEmpty(oldIface) == false) {
1734 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1735 if (networkStateTracker == null) continue;
1736 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1737 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1738 LinkProperties l = networkStateTracker.getLinkProperties();
1739 if (l == null) continue;
1740 if (oldIface.equals(l.getInterfaceName())) {
1749 // do this before we broadcast the change
1750 handleConnectivityChange(prevNetType, doReset);
1752 final Intent immediateIntent = new Intent(intent);
1753 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1754 sendStickyBroadcast(immediateIntent);
1755 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1757 * If the failover network is already connected, then immediately send
1758 * out a followup broadcast indicating successful failover
1760 if (mActiveDefaultNetwork != -1) {
1761 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1762 getConnectivityChangeDelay());
1766 private void tryFailover(int prevNetType) {
1768 * If this is a default network, check if other defaults are available.
1769 * Try to reconnect on all available and let them hash it out when
1770 * more than one connects.
1772 if (mNetConfigs[prevNetType].isDefault()) {
1773 if (mActiveDefaultNetwork == prevNetType) {
1774 mActiveDefaultNetwork = -1;
1777 // don't signal a reconnect for anything lower or equal priority than our
1778 // current connected default
1779 // TODO - don't filter by priority now - nice optimization but risky
1780 // int currentPriority = -1;
1781 // if (mActiveDefaultNetwork != -1) {
1782 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1784 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1785 if (checkType == prevNetType) continue;
1786 if (mNetConfigs[checkType] == null) continue;
1787 if (!mNetConfigs[checkType].isDefault()) continue;
1788 if (mNetTrackers[checkType] == null) continue;
1790 // Enabling the isAvailable() optimization caused mobile to not get
1791 // selected if it was in the middle of error handling. Specifically
1792 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1793 // would not be available and we wouldn't get connected to anything.
1794 // So removing the isAvailable() optimization below for now. TODO: This
1795 // optimization should work and we need to investigate why it doesn't work.
1796 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1797 // complete before it is really complete.
1798 // if (!mNetTrackers[checkType].isAvailable()) continue;
1800 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1802 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1803 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1804 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1805 checkInfo.setFailover(true);
1806 checkTracker.reconnect();
1808 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1813 public void sendConnectedBroadcast(NetworkInfo info) {
1814 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1815 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1818 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1819 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1820 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1823 private void sendInetConditionBroadcast(NetworkInfo info) {
1824 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1827 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1828 if (mLockdownTracker != null) {
1829 info = mLockdownTracker.augmentNetworkInfo(info);
1832 Intent intent = new Intent(bcastType);
1833 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1834 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1835 if (info.isFailover()) {
1836 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1837 info.setFailover(false);
1839 if (info.getReason() != null) {
1840 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1842 if (info.getExtraInfo() != null) {
1843 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1844 info.getExtraInfo());
1846 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1850 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1851 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1854 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1855 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1858 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1859 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1860 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1861 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1862 final long ident = Binder.clearCallingIdentity();
1864 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1865 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1867 Binder.restoreCallingIdentity(ident);
1872 * Called when an attempt to fail over to another network has failed.
1873 * @param info the {@link NetworkInfo} for the failed network
1875 private void handleConnectionFailure(NetworkInfo info) {
1876 mNetTrackers[info.getType()].setTeardownRequested(false);
1878 String reason = info.getReason();
1879 String extraInfo = info.getExtraInfo();
1882 if (reason == null) {
1885 reasonText = " (" + reason + ").";
1887 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1889 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1890 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1891 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1892 if (getActiveNetworkInfo() == null) {
1893 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1895 if (reason != null) {
1896 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1898 if (extraInfo != null) {
1899 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1901 if (info.isFailover()) {
1902 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1903 info.setFailover(false);
1906 if (mNetConfigs[info.getType()].isDefault()) {
1907 tryFailover(info.getType());
1908 if (mActiveDefaultNetwork != -1) {
1909 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1910 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1912 mDefaultInetConditionPublished = 0;
1913 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1917 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1919 final Intent immediateIntent = new Intent(intent);
1920 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1921 sendStickyBroadcast(immediateIntent);
1922 sendStickyBroadcast(intent);
1924 * If the failover network is already connected, then immediately send
1925 * out a followup broadcast indicating successful failover
1927 if (mActiveDefaultNetwork != -1) {
1928 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1932 private void sendStickyBroadcast(Intent intent) {
1933 synchronized(this) {
1934 if (!mSystemReady) {
1935 mInitialBroadcast = new Intent(intent);
1937 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1939 log("sendStickyBroadcast: action=" + intent.getAction());
1942 final long ident = Binder.clearCallingIdentity();
1944 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1946 Binder.restoreCallingIdentity(ident);
1951 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1953 sendStickyBroadcast(intent);
1956 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1957 + intent.getAction());
1959 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1960 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1964 void systemReady() {
1965 synchronized(this) {
1966 mSystemReady = true;
1967 if (mInitialBroadcast != null) {
1968 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1969 mInitialBroadcast = null;
1972 // load the global proxy at startup
1973 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1975 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1976 // for user to unlock device.
1977 if (!updateLockdownVpn()) {
1978 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1979 mContext.registerReceiver(mUserPresentReceiver, filter);
1983 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1985 public void onReceive(Context context, Intent intent) {
1986 // Try creating lockdown tracker, since user present usually means
1987 // unlocked keystore.
1988 if (updateLockdownVpn()) {
1989 mContext.unregisterReceiver(this);
1994 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
1995 if ((type != mNetworkPreference &&
1996 mNetConfigs[mActiveDefaultNetwork].priority >
1997 mNetConfigs[type].priority) ||
1998 mNetworkPreference == mActiveDefaultNetwork) return false;
2002 private void handleConnect(NetworkInfo info) {
2003 final int newNetType = info.getType();
2005 setupDataActivityTracking(newNetType);
2007 // snapshot isFailover, because sendConnectedBroadcast() resets it
2008 boolean isFailover = info.isFailover();
2009 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2010 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2012 // if this is a default net and other default is running
2013 // kill the one not preferred
2014 if (mNetConfigs[newNetType].isDefault()) {
2015 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2016 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2017 // tear down the other
2018 NetworkStateTracker otherNet =
2019 mNetTrackers[mActiveDefaultNetwork];
2021 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2024 if (!teardown(otherNet)) {
2025 loge("Network declined teardown request");
2030 // don't accept this one
2032 log("Not broadcasting CONNECT_ACTION " +
2033 "to torn down network " + info.getTypeName());
2039 synchronized (ConnectivityService.this) {
2040 // have a new default network, release the transition wakelock in a second
2041 // if it's held. The second pause is to allow apps to reconnect over the
2043 if (mNetTransitionWakeLock.isHeld()) {
2044 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2045 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2046 mNetTransitionWakeLockSerialNumber, 0),
2050 mActiveDefaultNetwork = newNetType;
2051 // this will cause us to come up initially as unconnected and switching
2052 // to connected after our normal pause unless somebody reports us as reall
2054 mDefaultInetConditionPublished = 0;
2055 mDefaultConnectionSequence++;
2056 mInetConditionChangeInFlight = false;
2057 // Don't do this - if we never sign in stay, grey
2058 //reportNetworkCondition(mActiveDefaultNetwork, 100);
2060 thisNet.setTeardownRequested(false);
2061 updateNetworkSettings(thisNet);
2062 handleConnectivityChange(newNetType, false);
2063 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2065 // notify battery stats service about this network
2066 if (thisIface != null) {
2068 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2069 } catch (RemoteException e) {
2070 // ignored; service lives in system_server
2075 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2076 if (DBG) log("Captive portal check " + info);
2077 int type = info.getType();
2078 final NetworkStateTracker thisNet = mNetTrackers[type];
2079 if (mNetConfigs[type].isDefault()) {
2080 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2081 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2082 if (DBG) log("Captive check on " + info.getTypeName());
2083 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
2086 if (DBG) log("Tear down low priority net " + info.getTypeName());
2093 thisNet.captivePortalCheckComplete();
2097 public void captivePortalCheckComplete(NetworkInfo info) {
2098 mNetTrackers[info.getType()].captivePortalCheckComplete();
2102 * Setup data activity tracking for the given network interface.
2104 * Every {@code setupDataActivityTracking} should be paired with a
2105 * {@link removeDataActivityTracking} for cleanup.
2107 private void setupDataActivityTracking(int type) {
2108 final NetworkStateTracker thisNet = mNetTrackers[type];
2109 final String iface = thisNet.getLinkProperties().getInterfaceName();
2113 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2114 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2115 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2117 // Canonicalize mobile network type
2118 type = ConnectivityManager.TYPE_MOBILE;
2119 } else if (ConnectivityManager.TYPE_WIFI == type) {
2120 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2121 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2124 // do not track any other networks
2128 if (timeout > 0 && iface != null) {
2130 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2131 } catch (RemoteException e) {
2137 * Remove data activity tracking when network disconnects.
2139 private void removeDataActivityTracking(int type) {
2140 final NetworkStateTracker net = mNetTrackers[type];
2141 final String iface = net.getLinkProperties().getInterfaceName();
2143 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2144 ConnectivityManager.TYPE_WIFI == type)) {
2146 // the call fails silently if no idletimer setup for this interface
2147 mNetd.removeIdleTimer(iface);
2148 } catch (RemoteException e) {
2154 * After a change in the connectivity state of a network. We're mainly
2155 * concerned with making sure that the list of DNS servers is set up
2156 * according to which networks are connected, and ensuring that the
2157 * right routing table entries exist.
2159 private void handleConnectivityChange(int netType, boolean doReset) {
2160 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2163 * If a non-default network is enabled, add the host routes that
2164 * will allow it's DNS servers to be accessed.
2166 handleDnsConfigurationChange(netType);
2168 LinkProperties curLp = mCurrentLinkProperties[netType];
2169 LinkProperties newLp = null;
2171 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2172 newLp = mNetTrackers[netType].getLinkProperties();
2174 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2175 " doReset=" + doReset + " resetMask=" + resetMask +
2176 "\n curLp=" + curLp +
2177 "\n newLp=" + newLp);
2180 if (curLp != null) {
2181 if (curLp.isIdenticalInterfaceName(newLp)) {
2182 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2183 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2184 for (LinkAddress linkAddr : car.removed) {
2185 if (linkAddr.getAddress() instanceof Inet4Address) {
2186 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2188 if (linkAddr.getAddress() instanceof Inet6Address) {
2189 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2193 log("handleConnectivityChange: addresses changed" +
2194 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2199 log("handleConnectivityChange: address are the same reset per doReset" +
2200 " linkProperty[" + netType + "]:" +
2201 " resetMask=" + resetMask);
2205 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2207 log("handleConnectivityChange: interface not not equivalent reset both" +
2208 " linkProperty[" + netType + "]:" +
2209 " resetMask=" + resetMask);
2213 if (mNetConfigs[netType].isDefault()) {
2214 handleApplyDefaultProxy(newLp.getHttpProxy());
2218 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2219 " doReset=" + doReset + " resetMask=" + resetMask +
2220 "\n curLp=" + curLp +
2224 mCurrentLinkProperties[netType] = newLp;
2225 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2227 if (resetMask != 0 || resetDns) {
2228 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2229 if (linkProperties != null) {
2230 String iface = linkProperties.getInterfaceName();
2231 if (TextUtils.isEmpty(iface) == false) {
2232 if (resetMask != 0) {
2233 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2234 NetworkUtils.resetConnections(iface, resetMask);
2236 // Tell VPN the interface is down. It is a temporary
2237 // but effective fix to make VPN aware of the change.
2238 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2239 mVpn.interfaceStatusChanged(iface, false);
2243 if (VDBG) log("resetting DNS cache for " + iface);
2245 mNetd.flushInterfaceDnsCache(iface);
2246 } catch (Exception e) {
2247 // never crash - catch them all
2248 if (DBG) loge("Exception resetting dns cache: " + e);
2255 // TODO: Temporary notifying upstread change to Tethering.
2257 /** Notify TetheringService if interface name has been changed. */
2258 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2259 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2260 if (isTetheringSupported()) {
2261 mTethering.handleTetherIfaceChange();
2267 * Add and remove routes using the old properties (null if not previously connected),
2268 * new properties (null if becoming disconnected). May even be double null, which
2270 * Uses isLinkDefault to determine if default routes should be set or conversely if
2271 * host routes should be set to the dns servers
2272 * returns a boolean indicating the routes changed
2274 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2275 boolean isLinkDefault) {
2276 Collection<RouteInfo> routesToAdd = null;
2277 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2278 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2279 if (curLp != null) {
2280 // check for the delta between the current set and the new
2281 routeDiff = curLp.compareRoutes(newLp);
2282 dnsDiff = curLp.compareDnses(newLp);
2283 } else if (newLp != null) {
2284 routeDiff.added = newLp.getRoutes();
2285 dnsDiff.added = newLp.getDnses();
2288 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2290 for (RouteInfo r : routeDiff.removed) {
2291 if (isLinkDefault || ! r.isDefaultRoute()) {
2292 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2294 if (isLinkDefault == false) {
2295 // remove from a secondary route table
2296 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2300 for (RouteInfo r : routeDiff.added) {
2301 if (isLinkDefault || ! r.isDefaultRoute()) {
2302 addRoute(newLp, r, TO_DEFAULT_TABLE);
2304 // add to a secondary route table
2305 addRoute(newLp, r, TO_SECONDARY_TABLE);
2307 // many radios add a default route even when we don't want one.
2308 // remove the default route unless somebody else has asked for it
2309 String ifaceName = newLp.getInterfaceName();
2310 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2311 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2313 mNetd.removeRoute(ifaceName, r);
2314 } catch (Exception e) {
2315 // never crash - catch them all
2316 if (DBG) loge("Exception trying to remove a route: " + e);
2322 if (!isLinkDefault) {
2323 // handle DNS routes
2324 if (routesChanged) {
2325 // routes changed - remove all old dns entries and add new
2326 if (curLp != null) {
2327 for (InetAddress oldDns : curLp.getDnses()) {
2328 removeRouteToAddress(curLp, oldDns);
2331 if (newLp != null) {
2332 for (InetAddress newDns : newLp.getDnses()) {
2333 addRouteToAddress(newLp, newDns);
2337 // no change in routes, check for change in dns themselves
2338 for (InetAddress oldDns : dnsDiff.removed) {
2339 removeRouteToAddress(curLp, oldDns);
2341 for (InetAddress newDns : dnsDiff.added) {
2342 addRouteToAddress(newLp, newDns);
2346 return routesChanged;
2351 * Reads the network specific TCP buffer sizes from SystemProperties
2352 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2355 public void updateNetworkSettings(NetworkStateTracker nt) {
2356 String key = nt.getTcpBufferSizesPropName();
2357 String bufferSizes = key == null ? null : SystemProperties.get(key);
2359 if (TextUtils.isEmpty(bufferSizes)) {
2360 if (VDBG) log(key + " not found in system properties. Using defaults");
2362 // Setting to default values so we won't be stuck to previous values
2363 key = "net.tcp.buffersize.default";
2364 bufferSizes = SystemProperties.get(key);
2367 // Set values in kernel
2368 if (bufferSizes.length() != 0) {
2370 log("Setting TCP values: [" + bufferSizes
2371 + "] which comes from [" + key + "]");
2373 setBufferSize(bufferSizes);
2378 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2379 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2381 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2382 * writeMin, writeInitial, writeMax"
2384 private void setBufferSize(String bufferSizes) {
2386 String[] values = bufferSizes.split(",");
2388 if (values.length == 6) {
2389 final String prefix = "/sys/kernel/ipv4/tcp_";
2390 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2391 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2392 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2393 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2394 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2395 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2397 loge("Invalid buffersize string: " + bufferSizes);
2399 } catch (IOException e) {
2400 loge("Can't set tcp buffer sizes:" + e);
2405 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2406 * on the highest priority active net which this process requested.
2407 * If there aren't any, clear it out
2409 private void reassessPidDns(int myPid, boolean doBump)
2411 if (VDBG) log("reassessPidDns for pid " + myPid);
2412 for(int i : mPriorityList) {
2413 if (mNetConfigs[i].isDefault()) {
2416 NetworkStateTracker nt = mNetTrackers[i];
2417 if (nt.getNetworkInfo().isConnected() &&
2418 !nt.isTeardownRequested()) {
2419 LinkProperties p = nt.getLinkProperties();
2420 if (p == null) continue;
2421 List pids = mNetRequestersPids[i];
2422 for (int j=0; j<pids.size(); j++) {
2423 Integer pid = (Integer)pids.get(j);
2424 if (pid.intValue() == myPid) {
2425 Collection<InetAddress> dnses = p.getDnses();
2426 writePidDns(dnses, myPid);
2435 // nothing found - delete
2436 for (int i = 1; ; i++) {
2437 String prop = "net.dns" + i + "." + myPid;
2438 if (SystemProperties.get(prop).length() == 0) {
2444 SystemProperties.set(prop, "");
2448 // return true if results in a change
2449 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
2451 boolean changed = false;
2452 for (InetAddress dns : dnses) {
2453 String dnsString = dns.getHostAddress();
2454 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2456 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
2463 private void bumpDns() {
2465 * Bump the property that tells the name resolver library to reread
2466 * the DNS server list from the properties.
2468 String propVal = SystemProperties.get("net.dnschange");
2470 if (propVal.length() != 0) {
2472 n = Integer.parseInt(propVal);
2473 } catch (NumberFormatException e) {}
2475 SystemProperties.set("net.dnschange", "" + (n+1));
2477 * Tell the VMs to toss their DNS caches
2479 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2480 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2482 * Connectivity events can happen before boot has completed ...
2484 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2485 final long ident = Binder.clearCallingIdentity();
2487 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2489 Binder.restoreCallingIdentity(ident);
2493 // Caller must grab mDnsLock.
2494 private boolean updateDns(String network, String iface,
2495 Collection<InetAddress> dnses, String domains) {
2496 boolean changed = false;
2498 if (dnses.size() == 0 && mDefaultDns != null) {
2500 String value = mDefaultDns.getHostAddress();
2501 if (!value.equals(SystemProperties.get("net.dns1"))) {
2503 loge("no dns provided for " + network + " - using " + value);
2506 SystemProperties.set("net.dns1", value);
2509 for (InetAddress dns : dnses) {
2511 String key = "net.dns" + last;
2512 String value = dns.getHostAddress();
2513 if (!changed && value.equals(SystemProperties.get(key))) {
2517 log("adding dns " + value + " for " + network);
2520 SystemProperties.set(key, value);
2523 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2524 String key = "net.dns" + i;
2525 if (VDBG) log("erasing " + key);
2527 SystemProperties.set(key, "");
2529 mNumDnsEntries = last;
2533 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2534 mNetd.setDefaultInterfaceForDns(iface);
2535 } catch (Exception e) {
2536 if (DBG) loge("exception setting default dns interface: " + e);
2539 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2540 SystemProperties.set("net.dns.search", domains);
2546 private void handleDnsConfigurationChange(int netType) {
2547 // add default net's dns entries
2548 NetworkStateTracker nt = mNetTrackers[netType];
2549 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2550 LinkProperties p = nt.getLinkProperties();
2551 if (p == null) return;
2552 Collection<InetAddress> dnses = p.getDnses();
2553 boolean changed = false;
2554 if (mNetConfigs[netType].isDefault()) {
2555 String network = nt.getNetworkInfo().getTypeName();
2556 synchronized (mDnsLock) {
2557 if (!mDnsOverridden) {
2558 changed = updateDns(network, p.getInterfaceName(), dnses, "");
2563 mNetd.setDnsServersForInterface(p.getInterfaceName(),
2564 NetworkUtils.makeStrings(dnses));
2565 } catch (Exception e) {
2566 if (DBG) loge("exception setting dns servers: " + e);
2568 // set per-pid dns for attached secondary nets
2569 List pids = mNetRequestersPids[netType];
2570 for (int y=0; y< pids.size(); y++) {
2571 Integer pid = (Integer)pids.get(y);
2572 changed = writePidDns(dnses, pid.intValue());
2575 if (changed) bumpDns();
2579 private int getRestoreDefaultNetworkDelay(int networkType) {
2580 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2581 NETWORK_RESTORE_DELAY_PROP_NAME);
2582 if(restoreDefaultNetworkDelayStr != null &&
2583 restoreDefaultNetworkDelayStr.length() != 0) {
2585 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2586 } catch (NumberFormatException e) {
2589 // if the system property isn't set, use the value for the apn type
2590 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2592 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2593 (mNetConfigs[networkType] != null)) {
2594 ret = mNetConfigs[networkType].restoreTime;
2600 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2601 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2602 if (mContext.checkCallingOrSelfPermission(
2603 android.Manifest.permission.DUMP)
2604 != PackageManager.PERMISSION_GRANTED) {
2605 pw.println("Permission Denial: can't dump ConnectivityService " +
2606 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2607 Binder.getCallingUid());
2611 // TODO: add locking to get atomic snapshot
2613 for (int i = 0; i < mNetTrackers.length; i++) {
2614 final NetworkStateTracker nst = mNetTrackers[i];
2616 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2617 pw.increaseIndent();
2618 if (nst.getNetworkInfo().isConnected()) {
2619 pw.println("Active network: " + nst.getNetworkInfo().
2622 pw.println(nst.getNetworkInfo());
2623 pw.println(nst.getLinkProperties());
2626 pw.decreaseIndent();
2630 pw.println("Network Requester Pids:");
2631 pw.increaseIndent();
2632 for (int net : mPriorityList) {
2633 String pidString = net + ": ";
2634 for (Object pid : mNetRequestersPids[net]) {
2635 pidString = pidString + pid.toString() + ", ";
2637 pw.println(pidString);
2640 pw.decreaseIndent();
2642 pw.println("FeatureUsers:");
2643 pw.increaseIndent();
2644 for (Object requester : mFeatureUsers) {
2645 pw.println(requester.toString());
2648 pw.decreaseIndent();
2650 synchronized (this) {
2651 pw.println("NetworkTranstionWakeLock is currently " +
2652 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2653 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2657 mTethering.dump(fd, pw, args);
2659 if (mInetLog != null) {
2661 pw.println("Inet condition reports:");
2662 pw.increaseIndent();
2663 for(int i = 0; i < mInetLog.size(); i++) {
2664 pw.println(mInetLog.get(i));
2666 pw.decreaseIndent();
2670 // must be stateless - things change under us.
2671 private class NetworkStateTrackerHandler extends Handler {
2672 public NetworkStateTrackerHandler(Looper looper) {
2677 public void handleMessage(Message msg) {
2680 case NetworkStateTracker.EVENT_STATE_CHANGED:
2681 info = (NetworkInfo) msg.obj;
2682 int type = info.getType();
2683 NetworkInfo.State state = info.getState();
2685 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2686 (state == NetworkInfo.State.DISCONNECTED)) {
2687 log("ConnectivityChange for " +
2688 info.getTypeName() + ": " +
2689 state + "/" + info.getDetailedState());
2692 EventLogTags.writeConnectivityStateChanged(
2693 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2695 if (info.getDetailedState() ==
2696 NetworkInfo.DetailedState.FAILED) {
2697 handleConnectionFailure(info);
2698 } else if (info.getDetailedState() ==
2699 DetailedState.CAPTIVE_PORTAL_CHECK) {
2700 handleCaptivePortalTrackerCheck(info);
2701 } else if (state == NetworkInfo.State.DISCONNECTED) {
2702 handleDisconnect(info);
2703 } else if (state == NetworkInfo.State.SUSPENDED) {
2704 // TODO: need to think this over.
2705 // the logic here is, handle SUSPENDED the same as
2706 // DISCONNECTED. The only difference being we are
2707 // broadcasting an intent with NetworkInfo that's
2708 // suspended. This allows the applications an
2709 // opportunity to handle DISCONNECTED and SUSPENDED
2710 // differently, or not.
2711 handleDisconnect(info);
2712 } else if (state == NetworkInfo.State.CONNECTED) {
2713 handleConnect(info);
2715 if (mLockdownTracker != null) {
2716 mLockdownTracker.onNetworkInfoChanged(info);
2719 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2720 info = (NetworkInfo) msg.obj;
2721 // TODO: Temporary allowing network configuration
2722 // change not resetting sockets.
2724 handleConnectivityChange(info.getType(), false);
2726 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2727 info = (NetworkInfo) msg.obj;
2728 type = info.getType();
2729 updateNetworkSettings(mNetTrackers[type]);
2735 private class InternalHandler extends Handler {
2736 public InternalHandler(Looper looper) {
2741 public void handleMessage(Message msg) {
2744 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2745 String causedBy = null;
2746 synchronized (ConnectivityService.this) {
2747 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2748 mNetTransitionWakeLock.isHeld()) {
2749 mNetTransitionWakeLock.release();
2750 causedBy = mNetTransitionWakeLockCausedBy;
2753 if (causedBy != null) {
2754 log("NetTransition Wakelock for " + causedBy + " released by timeout");
2757 case EVENT_RESTORE_DEFAULT_NETWORK:
2758 FeatureUser u = (FeatureUser)msg.obj;
2761 case EVENT_INET_CONDITION_CHANGE:
2763 int netType = msg.arg1;
2764 int condition = msg.arg2;
2765 handleInetConditionChange(netType, condition);
2768 case EVENT_INET_CONDITION_HOLD_END:
2770 int netType = msg.arg1;
2771 int sequence = msg.arg2;
2772 handleInetConditionHoldEnd(netType, sequence);
2775 case EVENT_SET_NETWORK_PREFERENCE:
2777 int preference = msg.arg1;
2778 handleSetNetworkPreference(preference);
2781 case EVENT_SET_MOBILE_DATA:
2783 boolean enabled = (msg.arg1 == ENABLED);
2784 handleSetMobileData(enabled);
2787 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2789 handleDeprecatedGlobalHttpProxy();
2792 case EVENT_SET_DEPENDENCY_MET:
2794 boolean met = (msg.arg1 == ENABLED);
2795 handleSetDependencyMet(msg.arg2, met);
2798 case EVENT_RESTORE_DNS:
2800 if (mActiveDefaultNetwork != -1) {
2801 handleDnsConfigurationChange(mActiveDefaultNetwork);
2805 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2807 Intent intent = (Intent)msg.obj;
2808 sendStickyBroadcast(intent);
2811 case EVENT_SET_POLICY_DATA_ENABLE: {
2812 final int networkType = msg.arg1;
2813 final boolean enabled = msg.arg2 == ENABLED;
2814 handleSetPolicyDataEnable(networkType, enabled);
2817 case EVENT_VPN_STATE_CHANGED: {
2818 if (mLockdownTracker != null) {
2819 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2827 // javadoc from interface
2828 public int tether(String iface) {
2829 enforceTetherChangePermission();
2831 if (isTetheringSupported()) {
2832 return mTethering.tether(iface);
2834 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2838 // javadoc from interface
2839 public int untether(String iface) {
2840 enforceTetherChangePermission();
2842 if (isTetheringSupported()) {
2843 return mTethering.untether(iface);
2845 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2849 // javadoc from interface
2850 public int getLastTetherError(String iface) {
2851 enforceTetherAccessPermission();
2853 if (isTetheringSupported()) {
2854 return mTethering.getLastTetherError(iface);
2856 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2860 // TODO - proper iface API for selection by property, inspection, etc
2861 public String[] getTetherableUsbRegexs() {
2862 enforceTetherAccessPermission();
2863 if (isTetheringSupported()) {
2864 return mTethering.getTetherableUsbRegexs();
2866 return new String[0];
2870 public String[] getTetherableWifiRegexs() {
2871 enforceTetherAccessPermission();
2872 if (isTetheringSupported()) {
2873 return mTethering.getTetherableWifiRegexs();
2875 return new String[0];
2879 public String[] getTetherableBluetoothRegexs() {
2880 enforceTetherAccessPermission();
2881 if (isTetheringSupported()) {
2882 return mTethering.getTetherableBluetoothRegexs();
2884 return new String[0];
2888 public int setUsbTethering(boolean enable) {
2889 enforceTetherAccessPermission();
2890 if (isTetheringSupported()) {
2891 return mTethering.setUsbTethering(enable);
2893 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2897 // TODO - move iface listing, queries, etc to new module
2898 // javadoc from interface
2899 public String[] getTetherableIfaces() {
2900 enforceTetherAccessPermission();
2901 return mTethering.getTetherableIfaces();
2904 public String[] getTetheredIfaces() {
2905 enforceTetherAccessPermission();
2906 return mTethering.getTetheredIfaces();
2910 public String[] getTetheredIfacePairs() {
2911 enforceTetherAccessPermission();
2912 return mTethering.getTetheredIfacePairs();
2915 public String[] getTetheringErroredIfaces() {
2916 enforceTetherAccessPermission();
2917 return mTethering.getErroredIfaces();
2920 // if ro.tether.denied = true we default to no tethering
2921 // gservices could set the secure setting to 1 though to enable it on a build where it
2922 // had previously been turned off.
2923 public boolean isTetheringSupported() {
2924 enforceTetherAccessPermission();
2925 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2926 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2927 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
2928 return tetherEnabledInSettings && mTetheringConfigValid;
2931 // An API NetworkStateTrackers can call when they lose their network.
2932 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2933 // whichever happens first. The timer is started by the first caller and not
2934 // restarted by subsequent callers.
2935 public void requestNetworkTransitionWakelock(String forWhom) {
2936 enforceConnectivityInternalPermission();
2937 synchronized (this) {
2938 if (mNetTransitionWakeLock.isHeld()) return;
2939 mNetTransitionWakeLockSerialNumber++;
2940 mNetTransitionWakeLock.acquire();
2941 mNetTransitionWakeLockCausedBy = forWhom;
2943 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2944 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2945 mNetTransitionWakeLockSerialNumber, 0),
2946 mNetTransitionWakeLockTimeout);
2950 // 100 percent is full good, 0 is full bad.
2951 public void reportInetCondition(int networkType, int percentage) {
2952 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2953 mContext.enforceCallingOrSelfPermission(
2954 android.Manifest.permission.STATUS_BAR,
2955 "ConnectivityService");
2958 int pid = getCallingPid();
2959 int uid = getCallingUid();
2960 String s = pid + "(" + uid + ") reports inet is " +
2961 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2962 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2964 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2968 mHandler.sendMessage(mHandler.obtainMessage(
2969 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2972 private void handleInetConditionChange(int netType, int condition) {
2973 if (mActiveDefaultNetwork == -1) {
2974 if (DBG) log("handleInetConditionChange: no active default network - ignore");
2977 if (mActiveDefaultNetwork != netType) {
2978 if (DBG) log("handleInetConditionChange: net=" + netType +
2979 " != default=" + mActiveDefaultNetwork + " - ignore");
2983 log("handleInetConditionChange: net=" +
2984 netType + ", condition=" + condition +
2985 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2987 mDefaultInetCondition = condition;
2989 if (mInetConditionChangeInFlight == false) {
2990 if (VDBG) log("handleInetConditionChange: starting a change hold");
2991 // setup a new hold to debounce this
2992 if (mDefaultInetCondition > 50) {
2993 delay = Settings.Global.getInt(mContext.getContentResolver(),
2994 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2996 delay = Settings.Global.getInt(mContext.getContentResolver(),
2997 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2999 mInetConditionChangeInFlight = true;
3000 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3001 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3003 // we've set the new condition, when this hold ends that will get picked up
3004 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3008 private void handleInetConditionHoldEnd(int netType, int sequence) {
3010 log("handleInetConditionHoldEnd: net=" + netType +
3011 ", condition=" + mDefaultInetCondition +
3012 ", published condition=" + mDefaultInetConditionPublished);
3014 mInetConditionChangeInFlight = false;
3016 if (mActiveDefaultNetwork == -1) {
3017 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3020 if (mDefaultConnectionSequence != sequence) {
3021 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3024 // TODO: Figure out why this optimization sometimes causes a
3025 // change in mDefaultInetCondition to be missed and the
3026 // UI to not be updated.
3027 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3028 // if (DBG) log("no change in condition - aborting");
3031 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3032 if (networkInfo.isConnected() == false) {
3033 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3036 mDefaultInetConditionPublished = mDefaultInetCondition;
3037 sendInetConditionBroadcast(networkInfo);
3041 public ProxyProperties getProxy() {
3042 synchronized (mDefaultProxyLock) {
3043 return mDefaultProxyDisabled ? null : mDefaultProxy;
3047 public void setGlobalProxy(ProxyProperties proxyProperties) {
3048 enforceChangePermission();
3049 synchronized (mGlobalProxyLock) {
3050 if (proxyProperties == mGlobalProxy) return;
3051 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3052 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3056 String exclList = "";
3057 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3058 mGlobalProxy = new ProxyProperties(proxyProperties);
3059 host = mGlobalProxy.getHost();
3060 port = mGlobalProxy.getPort();
3061 exclList = mGlobalProxy.getExclusionList();
3063 mGlobalProxy = null;
3065 ContentResolver res = mContext.getContentResolver();
3066 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3067 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3068 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3072 if (mGlobalProxy == null) {
3073 proxyProperties = mDefaultProxy;
3075 //sendProxyBroadcast(proxyProperties);
3078 private void loadGlobalProxy() {
3079 ContentResolver res = mContext.getContentResolver();
3080 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3081 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3082 String exclList = Settings.Global.getString(res,
3083 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3084 if (!TextUtils.isEmpty(host)) {
3085 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3086 synchronized (mGlobalProxyLock) {
3087 mGlobalProxy = proxyProperties;
3092 public ProxyProperties getGlobalProxy() {
3093 synchronized (mGlobalProxyLock) {
3094 return mGlobalProxy;
3098 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3099 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3102 synchronized (mDefaultProxyLock) {
3103 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3104 if (mDefaultProxy == proxy) return;
3105 mDefaultProxy = proxy;
3107 if (!mDefaultProxyDisabled) {
3108 sendProxyBroadcast(proxy);
3113 private void handleDeprecatedGlobalHttpProxy() {
3114 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3115 Settings.Global.HTTP_PROXY);
3116 if (!TextUtils.isEmpty(proxy)) {
3117 String data[] = proxy.split(":");
3118 String proxyHost = data[0];
3119 int proxyPort = 8080;
3120 if (data.length > 1) {
3122 proxyPort = Integer.parseInt(data[1]);
3123 } catch (NumberFormatException e) {
3127 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3132 private void sendProxyBroadcast(ProxyProperties proxy) {
3133 if (proxy == null) proxy = new ProxyProperties("", 0, "");
3134 if (DBG) log("sending Proxy Broadcast for " + proxy);
3135 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3136 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3137 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3138 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3139 final long ident = Binder.clearCallingIdentity();
3141 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3143 Binder.restoreCallingIdentity(ident);
3147 private static class SettingsObserver extends ContentObserver {
3149 private Handler mHandler;
3150 SettingsObserver(Handler handler, int what) {
3156 void observe(Context context) {
3157 ContentResolver resolver = context.getContentResolver();
3158 resolver.registerContentObserver(Settings.Global.getUriFor(
3159 Settings.Global.HTTP_PROXY), false, this);
3163 public void onChange(boolean selfChange) {
3164 mHandler.obtainMessage(mWhat).sendToTarget();
3168 private static void log(String s) {
3172 private static void loge(String s) {
3176 int convertFeatureToNetworkType(int networkType, String feature) {
3177 int usedNetworkType = networkType;
3179 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3180 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3181 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3182 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3183 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3184 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3185 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3186 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3187 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3188 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3189 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3190 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3191 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3192 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3193 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3194 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3196 Slog.e(TAG, "Can't match any mobile netTracker!");
3198 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3199 if (TextUtils.equals(feature, "p2p")) {
3200 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3202 Slog.e(TAG, "Can't match any wifi netTracker!");
3205 Slog.e(TAG, "Unexpected network type");
3207 return usedNetworkType;
3210 private static <T> T checkNotNull(T value, String message) {
3211 if (value == null) {
3212 throw new NullPointerException(message);
3218 * Protect a socket from VPN routing rules. This method is used by
3219 * VpnBuilder and not available in ConnectivityManager. Permissions
3220 * are checked in Vpn class.
3224 public boolean protectVpn(ParcelFileDescriptor socket) {
3225 throwIfLockdownEnabled();
3227 int type = mActiveDefaultNetwork;
3228 if (ConnectivityManager.isNetworkTypeValid(type)) {
3229 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3232 } catch (Exception e) {
3237 } catch (Exception e) {
3245 * Prepare for a VPN application. This method is used by VpnDialogs
3246 * and not available in ConnectivityManager. Permissions are checked
3251 public boolean prepareVpn(String oldPackage, String newPackage) {
3252 throwIfLockdownEnabled();
3253 return mVpn.prepare(oldPackage, newPackage);
3257 * Configure a TUN interface and return its file descriptor. Parameters
3258 * are encoded and opaque to this class. This method is used by VpnBuilder
3259 * and not available in ConnectivityManager. Permissions are checked in
3264 public ParcelFileDescriptor establishVpn(VpnConfig config) {
3265 throwIfLockdownEnabled();
3266 return mVpn.establish(config);
3270 * Start legacy VPN, controlling native daemons as needed. Creates a
3271 * secondary thread to perform connection work, returning quickly.
3274 public void startLegacyVpn(VpnProfile profile) {
3275 throwIfLockdownEnabled();
3276 final LinkProperties egress = getActiveLinkProperties();
3277 if (egress == null) {
3278 throw new IllegalStateException("Missing active network connection");
3280 mVpn.startLegacyVpn(profile, mKeyStore, egress);
3284 * Return the information of the ongoing legacy VPN. This method is used
3285 * by VpnSettings and not available in ConnectivityManager. Permissions
3286 * are checked in Vpn class.
3290 public LegacyVpnInfo getLegacyVpnInfo() {
3291 throwIfLockdownEnabled();
3292 return mVpn.getLegacyVpnInfo();
3296 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3297 * through NetworkStateTracker since it works differently. For example, it
3298 * needs to override DNS servers but never takes the default routes. It
3299 * relies on another data network, and it could keep existing connections
3300 * alive after reconnecting, switching between networks, or even resuming
3301 * from deep sleep. Calls from applications should be done synchronously
3302 * to avoid race conditions. As these are all hidden APIs, refactoring can
3303 * be done whenever a better abstraction is developed.
3305 public class VpnCallback {
3306 private VpnCallback() {
3309 public void onStateChanged(NetworkInfo info) {
3310 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3313 public void override(List<String> dnsServers, List<String> searchDomains) {
3314 if (dnsServers == null) {
3319 // Convert DNS servers into addresses.
3320 List<InetAddress> addresses = new ArrayList<InetAddress>();
3321 for (String address : dnsServers) {
3322 // Double check the addresses and remove invalid ones.
3324 addresses.add(InetAddress.parseNumericAddress(address));
3325 } catch (Exception e) {
3329 if (addresses.isEmpty()) {
3334 // Concatenate search domains into a string.
3335 StringBuilder buffer = new StringBuilder();
3336 if (searchDomains != null) {
3337 for (String domain : searchDomains) {
3338 buffer.append(domain).append(' ');
3341 String domains = buffer.toString().trim();
3343 // Apply DNS changes.
3344 boolean changed = false;
3345 synchronized (mDnsLock) {
3346 changed = updateDns("VPN", "VPN", addresses, domains);
3347 mDnsOverridden = true;
3353 // Temporarily disable the default proxy.
3354 synchronized (mDefaultProxyLock) {
3355 mDefaultProxyDisabled = true;
3356 if (mDefaultProxy != null) {
3357 sendProxyBroadcast(null);
3361 // TODO: support proxy per network.
3364 public void restore() {
3365 synchronized (mDnsLock) {
3366 if (mDnsOverridden) {
3367 mDnsOverridden = false;
3368 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3371 synchronized (mDefaultProxyLock) {
3372 mDefaultProxyDisabled = false;
3373 if (mDefaultProxy != null) {
3374 sendProxyBroadcast(mDefaultProxy);
3381 public boolean updateLockdownVpn() {
3384 // Tear down existing lockdown if profile was removed
3385 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3386 if (mLockdownEnabled) {
3387 if (!mKeyStore.isUnlocked()) {
3388 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3392 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3393 final VpnProfile profile = VpnProfile.decode(
3394 profileName, mKeyStore.get(Credentials.VPN + profileName));
3395 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3397 setLockdownTracker(null);
3404 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3405 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3407 private void setLockdownTracker(LockdownVpnTracker tracker) {
3408 // Shutdown any existing tracker
3409 final LockdownVpnTracker existing = mLockdownTracker;
3410 mLockdownTracker = null;
3411 if (existing != null) {
3412 existing.shutdown();
3416 if (tracker != null) {
3417 mNetd.setFirewallEnabled(true);
3418 mLockdownTracker = tracker;
3419 mLockdownTracker.init();
3421 mNetd.setFirewallEnabled(false);
3423 } catch (RemoteException e) {
3424 // ignored; NMS lives inside system_server
3428 private void throwIfLockdownEnabled() {
3429 if (mLockdownEnabled) {
3430 throw new IllegalStateException("Unavailable in lockdown mode");
3434 private static void enforceSystemUid() {
3435 final int uid = Binder.getCallingUid();
3436 if (uid != Process.SYSTEM_UID) {
3437 throw new SecurityException("Only available to AID_SYSTEM");