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.MANAGE_NETWORK_POLICY;
20 import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
21 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
23 import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24 import static android.net.ConnectivityManager.TYPE_DUMMY;
25 import static android.net.ConnectivityManager.TYPE_ETHERNET;
26 import static android.net.ConnectivityManager.TYPE_MOBILE;
27 import static android.net.ConnectivityManager.TYPE_WIFI;
28 import static android.net.ConnectivityManager.TYPE_WIMAX;
29 import static android.net.ConnectivityManager.getNetworkTypeName;
30 import static android.net.ConnectivityManager.isNetworkTypeValid;
31 import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
32 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
34 import android.bluetooth.BluetoothTetheringDataTracker;
35 import android.content.BroadcastReceiver;
36 import android.content.ContentResolver;
37 import android.content.Context;
38 import android.content.ContextWrapper;
39 import android.content.Intent;
40 import android.content.IntentFilter;
41 import android.content.pm.PackageManager;
42 import android.content.res.Resources;
43 import android.database.ContentObserver;
44 import android.net.CaptivePortalTracker;
45 import android.net.ConnectivityManager;
46 import android.net.DummyDataStateTracker;
47 import android.net.EthernetDataTracker;
48 import android.net.IConnectivityManager;
49 import android.net.INetworkManagementEventObserver;
50 import android.net.INetworkPolicyListener;
51 import android.net.INetworkPolicyManager;
52 import android.net.INetworkStatsService;
53 import android.net.LinkAddress;
54 import android.net.LinkProperties;
55 import android.net.LinkProperties.CompareResult;
56 import android.net.MobileDataStateTracker;
57 import android.net.NetworkConfig;
58 import android.net.NetworkInfo;
59 import android.net.NetworkInfo.DetailedState;
60 import android.net.NetworkQuotaInfo;
61 import android.net.NetworkState;
62 import android.net.NetworkStateTracker;
63 import android.net.NetworkUtils;
64 import android.net.Proxy;
65 import android.net.ProxyProperties;
66 import android.net.RouteInfo;
67 import android.net.wifi.WifiStateTracker;
68 import android.net.wimax.WimaxManagerConstants;
69 import android.os.Binder;
70 import android.os.FileUtils;
71 import android.os.Handler;
72 import android.os.HandlerThread;
73 import android.os.IBinder;
74 import android.os.INetworkManagementService;
75 import android.os.Looper;
76 import android.os.Message;
77 import android.os.Messenger;
78 import android.os.ParcelFileDescriptor;
79 import android.os.PowerManager;
80 import android.os.Process;
81 import android.os.RemoteException;
82 import android.os.ServiceManager;
83 import android.os.SystemClock;
84 import android.os.SystemProperties;
85 import android.os.UserHandle;
86 import android.provider.Settings;
87 import android.security.Credentials;
88 import android.security.KeyStore;
89 import android.text.TextUtils;
90 import android.util.Slog;
91 import android.util.SparseIntArray;
93 import com.android.internal.net.LegacyVpnInfo;
94 import com.android.internal.net.VpnConfig;
95 import com.android.internal.net.VpnProfile;
96 import com.android.internal.telephony.Phone;
97 import com.android.internal.telephony.PhoneConstants;
98 import com.android.internal.util.IndentingPrintWriter;
99 import com.android.server.am.BatteryStatsService;
100 import com.android.server.connectivity.Nat464Xlat;
101 import com.android.server.connectivity.Tethering;
102 import com.android.server.connectivity.Vpn;
103 import com.android.server.net.BaseNetworkObserver;
104 import com.android.server.net.LockdownVpnTracker;
105 import com.google.android.collect.Lists;
106 import com.google.android.collect.Sets;
108 import dalvik.system.DexClassLoader;
110 import java.io.FileDescriptor;
111 import java.io.IOException;
112 import java.io.PrintWriter;
113 import java.lang.reflect.Constructor;
114 import java.net.Inet4Address;
115 import java.net.Inet6Address;
116 import java.net.InetAddress;
117 import java.net.UnknownHostException;
118 import java.util.ArrayList;
119 import java.util.Arrays;
120 import java.util.Collection;
121 import java.util.GregorianCalendar;
122 import java.util.HashSet;
123 import java.util.List;
128 public class ConnectivityService extends IConnectivityManager.Stub {
129 private static final String TAG = "ConnectivityService";
131 private static final boolean DBG = true;
132 private static final boolean VDBG = false;
134 private static final boolean LOGD_RULES = false;
136 // TODO: create better separation between radio types and network types
138 // how long to wait before switching back to a radio's default network
139 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
140 // system property that can override the above value
141 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
142 "android.telephony.apn-restore";
144 // used in recursive route setting to add gateways for the host for which
145 // a host route was requested.
146 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
148 private Tethering mTethering;
149 private boolean mTetheringConfigValid = false;
151 private KeyStore mKeyStore;
154 private VpnCallback mVpnCallback = new VpnCallback();
156 private boolean mLockdownEnabled;
157 private LockdownVpnTracker mLockdownTracker;
159 private Nat464Xlat mClat;
161 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
162 private Object mRulesLock = new Object();
163 /** Currently active network rules by UID. */
164 private SparseIntArray mUidRules = new SparseIntArray();
165 /** Set of ifaces that are costly. */
166 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
169 * Sometimes we want to refer to the individual network state
170 * trackers separately, and sometimes we just want to treat them
173 private NetworkStateTracker mNetTrackers[];
175 /* Handles captive portal check on a network */
176 private CaptivePortalTracker mCaptivePortalTracker;
179 * The link properties that define the current links
181 private LinkProperties mCurrentLinkProperties[];
184 * A per Net list of the PID's that requested access to the net
185 * used both as a refcount and for per-PID DNS selection
187 private List<Integer> mNetRequestersPids[];
189 // priority order of the nettrackers
190 // (excluding dynamically set mNetworkPreference)
191 // TODO - move mNetworkTypePreference into this
192 private int[] mPriorityList;
194 private Context mContext;
195 private int mNetworkPreference;
196 private int mActiveDefaultNetwork = -1;
197 // 0 is full bad, 100 is full good
198 private int mDefaultInetCondition = 0;
199 private int mDefaultInetConditionPublished = 0;
200 private boolean mInetConditionChangeInFlight = false;
201 private int mDefaultConnectionSequence = 0;
203 private Object mDnsLock = new Object();
204 private int mNumDnsEntries;
205 private boolean mDnsOverridden = false;
207 private boolean mTestMode;
208 private static ConnectivityService sServiceInstance;
210 private INetworkManagementService mNetd;
211 private INetworkPolicyManager mPolicyManager;
213 private static final int ENABLED = 1;
214 private static final int DISABLED = 0;
216 private static final boolean ADD = true;
217 private static final boolean REMOVE = false;
219 private static final boolean TO_DEFAULT_TABLE = true;
220 private static final boolean TO_SECONDARY_TABLE = false;
223 * used internally as a delayed event to make us switch back to the
226 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
229 * used internally to change our mobile data enabled flag
231 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
234 * used internally to change our network preference setting
235 * arg1 = networkType to prefer
237 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
240 * used internally to synchronize inet condition reports
242 * arg2 = condition (0 bad, 100 good)
244 private static final int EVENT_INET_CONDITION_CHANGE = 4;
247 * used internally to mark the end of inet condition hold periods
250 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
253 * used internally to set enable/disable cellular data
254 * arg1 = ENBALED or DISABLED
256 private static final int EVENT_SET_MOBILE_DATA = 7;
259 * used internally to clear a wakelock when transitioning
260 * from one net to another
262 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
265 * used internally to reload global proxy settings
267 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
270 * used internally to set external dependency met/unmet
271 * arg1 = ENABLED (met) or DISABLED (unmet)
274 private static final int EVENT_SET_DEPENDENCY_MET = 10;
277 * used internally to restore DNS properties back to the
280 private static final int EVENT_RESTORE_DNS = 11;
283 * used internally to send a sticky broadcast delayed.
285 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
289 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
291 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
293 private static final int EVENT_VPN_STATE_CHANGED = 14;
295 /** Handler used for internal events. */
296 private InternalHandler mHandler;
297 /** Handler used for incoming {@link NetworkStateTracker} events. */
298 private NetworkStateTrackerHandler mTrackerHandler;
300 // list of DeathRecipients used to make sure features are turned off when
302 private List<FeatureUser> mFeatureUsers;
304 private boolean mSystemReady;
305 private Intent mInitialBroadcast;
307 private PowerManager.WakeLock mNetTransitionWakeLock;
308 private String mNetTransitionWakeLockCausedBy = "";
309 private int mNetTransitionWakeLockSerialNumber;
310 private int mNetTransitionWakeLockTimeout;
312 private InetAddress mDefaultDns;
314 // this collection is used to refcount the added routes - if there are none left
315 // it's time to remove the route from the route table
316 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
318 // used in DBG mode to track inet condition reports
319 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
320 private ArrayList mInetLog;
322 // track the current default http proxy - tell the world if we get a new one (real change)
323 private ProxyProperties mDefaultProxy = null;
324 private Object mProxyLock = new Object();
325 private boolean mDefaultProxyDisabled = false;
327 // track the global proxy.
328 private ProxyProperties mGlobalProxy = null;
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 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
416 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
418 // Load device network attributes from resources
419 String[] raStrings = context.getResources().getStringArray(
420 com.android.internal.R.array.radioAttributes);
421 for (String raString : raStrings) {
422 RadioAttributes r = new RadioAttributes(raString);
423 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
424 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
427 if (mRadioAttributes[r.mType] != null) {
428 loge("Error in radioAttributes - ignoring attempt to redefine type " +
432 mRadioAttributes[r.mType] = r;
435 // TODO: What is the "correct" way to do determine if this is a wifi only device?
436 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
437 log("wifiOnly=" + wifiOnly);
438 String[] naStrings = context.getResources().getStringArray(
439 com.android.internal.R.array.networkAttributes);
440 for (String naString : naStrings) {
442 NetworkConfig n = new NetworkConfig(naString);
443 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
444 loge("Error in networkAttributes - ignoring attempt to define type " +
448 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
449 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
453 if (mNetConfigs[n.type] != null) {
454 loge("Error in networkAttributes - ignoring attempt to redefine type " +
458 if (mRadioAttributes[n.radio] == null) {
459 loge("Error in networkAttributes - ignoring attempt to use undefined " +
460 "radio " + n.radio + " in network type " + n.type);
463 mNetConfigs[n.type] = n;
465 } catch(Exception e) {
466 // ignore it - leave the entry null
470 mProtectedNetworks = new ArrayList<Integer>();
471 int[] protectedNetworks = context.getResources().getIntArray(
472 com.android.internal.R.array.config_protectedNetworks);
473 for (int p : protectedNetworks) {
474 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
475 mProtectedNetworks.add(p);
477 if (DBG) loge("Ignoring protectedNetwork " + p);
481 // high priority first
482 mPriorityList = new int[mNetworksDefined];
484 int insertionPoint = mNetworksDefined-1;
485 int currentLowest = 0;
487 while (insertionPoint > -1) {
488 for (NetworkConfig na : mNetConfigs) {
489 if (na == null) continue;
490 if (na.priority < currentLowest) continue;
491 if (na.priority > currentLowest) {
492 if (na.priority < nextLowest || nextLowest == 0) {
493 nextLowest = na.priority;
497 mPriorityList[insertionPoint--] = na.type;
499 currentLowest = nextLowest;
504 // Update mNetworkPreference according to user mannually first then overlay config.xml
505 mNetworkPreference = getPersistedNetworkPreference();
506 if (mNetworkPreference == -1) {
507 for (int n : mPriorityList) {
508 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
509 mNetworkPreference = n;
513 if (mNetworkPreference == -1) {
514 throw new IllegalStateException(
515 "You should set at least one default Network in config.xml!");
520 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
521 for (int i : mPriorityList) {
522 mNetRequestersPids[i] = new ArrayList<Integer>();
525 mFeatureUsers = new ArrayList<FeatureUser>();
527 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
528 && SystemProperties.get("ro.build.type").equals("eng");
530 // Create and start trackers for hard-coded networks
531 for (int targetNetworkType : mPriorityList) {
532 final NetworkConfig config = mNetConfigs[targetNetworkType];
533 final NetworkStateTracker tracker;
535 tracker = netFactory.createTracker(targetNetworkType, config);
536 mNetTrackers[targetNetworkType] = tracker;
537 } catch (IllegalArgumentException e) {
538 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
543 tracker.startMonitoring(context, mTrackerHandler);
544 if (config.isDefault()) {
549 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
550 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
551 mTethering.getTetherableWifiRegexs().length != 0 ||
552 mTethering.getTetherableBluetoothRegexs().length != 0) &&
553 mTethering.getUpstreamIfaceTypes().length != 0);
555 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
556 mVpn.startMonitoring(mContext, mTrackerHandler);
558 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
561 mNetd.registerObserver(mTethering);
562 mNetd.registerObserver(mDataActivityObserver);
563 mNetd.registerObserver(mClat);
564 } catch (RemoteException e) {
565 loge("Error registering observer :" + e);
569 mInetLog = new ArrayList();
572 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
573 mSettingsObserver.observe(mContext);
575 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
580 * Factory that creates {@link NetworkStateTracker} instances using given
581 * {@link NetworkConfig}.
583 public interface NetworkFactory {
584 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
587 private static class DefaultNetworkFactory implements NetworkFactory {
588 private final Context mContext;
589 private final Handler mTrackerHandler;
591 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
593 mTrackerHandler = trackerHandler;
597 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
598 switch (config.radio) {
600 return new WifiStateTracker(targetNetworkType, config.name);
602 return new MobileDataStateTracker(targetNetworkType, config.name);
604 return new DummyDataStateTracker(targetNetworkType, config.name);
606 return BluetoothTetheringDataTracker.getInstance();
608 return makeWimaxStateTracker(mContext, mTrackerHandler);
610 return EthernetDataTracker.getInstance();
612 throw new IllegalArgumentException(
613 "Trying to create a NetworkStateTracker for an unknown radio type: "
620 * Loads external WiMAX library and registers as system service, returning a
621 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
622 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
624 private static NetworkStateTracker makeWimaxStateTracker(
625 Context context, Handler trackerHandler) {
627 DexClassLoader wimaxClassLoader;
628 Class wimaxStateTrackerClass = null;
629 Class wimaxServiceClass = null;
630 Class wimaxManagerClass;
631 String wimaxJarLocation;
632 String wimaxLibLocation;
633 String wimaxManagerClassName;
634 String wimaxServiceClassName;
635 String wimaxStateTrackerClassName;
637 NetworkStateTracker wimaxStateTracker = null;
639 boolean isWimaxEnabled = context.getResources().getBoolean(
640 com.android.internal.R.bool.config_wimaxEnabled);
642 if (isWimaxEnabled) {
644 wimaxJarLocation = context.getResources().getString(
645 com.android.internal.R.string.config_wimaxServiceJarLocation);
646 wimaxLibLocation = context.getResources().getString(
647 com.android.internal.R.string.config_wimaxNativeLibLocation);
648 wimaxManagerClassName = context.getResources().getString(
649 com.android.internal.R.string.config_wimaxManagerClassname);
650 wimaxServiceClassName = context.getResources().getString(
651 com.android.internal.R.string.config_wimaxServiceClassname);
652 wimaxStateTrackerClassName = context.getResources().getString(
653 com.android.internal.R.string.config_wimaxStateTrackerClassname);
655 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
656 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
657 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
658 wimaxLibLocation, ClassLoader.getSystemClassLoader());
661 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
662 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
663 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
664 } catch (ClassNotFoundException ex) {
665 loge("Exception finding Wimax classes: " + ex.toString());
668 } catch(Resources.NotFoundException ex) {
669 loge("Wimax Resources does not exist!!! ");
674 if (DBG) log("Starting Wimax Service... ");
676 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
677 (new Class[] {Context.class, Handler.class});
678 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
679 context, trackerHandler);
681 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
682 (new Class[] {Context.class, wimaxStateTrackerClass});
683 wmxSrvConst.setAccessible(true);
684 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
685 wmxSrvConst.setAccessible(false);
687 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
689 } catch(Exception ex) {
690 loge("Exception creating Wimax classes: " + ex.toString());
694 loge("Wimax is not enabled or not added to the network attributes!!! ");
698 return wimaxStateTracker;
702 * Sets the preferred network.
703 * @param preference the new preference
705 public void setNetworkPreference(int preference) {
706 enforceChangePermission();
708 mHandler.sendMessage(
709 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
712 public int getNetworkPreference() {
713 enforceAccessPermission();
716 preference = mNetworkPreference;
721 private void handleSetNetworkPreference(int preference) {
722 if (ConnectivityManager.isNetworkTypeValid(preference) &&
723 mNetConfigs[preference] != null &&
724 mNetConfigs[preference].isDefault()) {
725 if (mNetworkPreference != preference) {
726 final ContentResolver cr = mContext.getContentResolver();
727 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
729 mNetworkPreference = preference;
736 private int getConnectivityChangeDelay() {
737 final ContentResolver cr = mContext.getContentResolver();
739 /** Check system properties for the default value then use secure settings value, if any. */
740 int defaultDelay = SystemProperties.getInt(
741 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
742 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
743 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
747 private int getPersistedNetworkPreference() {
748 final ContentResolver cr = mContext.getContentResolver();
750 final int networkPrefSetting = Settings.Global
751 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
753 return networkPrefSetting;
757 * Make the state of network connectivity conform to the preference settings
758 * In this method, we only tear down a non-preferred network. Establishing
759 * a connection to the preferred network is taken care of when we handle
760 * the disconnect event from the non-preferred network
761 * (see {@link #handleDisconnect(NetworkInfo)}).
763 private void enforcePreference() {
764 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
767 if (!mNetTrackers[mNetworkPreference].isAvailable())
770 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
771 if (t != mNetworkPreference && mNetTrackers[t] != null &&
772 mNetTrackers[t].getNetworkInfo().isConnected()) {
774 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
775 " in enforcePreference");
777 teardown(mNetTrackers[t]);
782 private boolean teardown(NetworkStateTracker netTracker) {
783 if (netTracker.teardown()) {
784 netTracker.setTeardownRequested(true);
792 * Check if UID should be blocked from using the network represented by the
793 * given {@link NetworkStateTracker}.
795 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
796 final String iface = tracker.getLinkProperties().getInterfaceName();
798 final boolean networkCostly;
800 synchronized (mRulesLock) {
801 networkCostly = mMeteredIfaces.contains(iface);
802 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
805 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
809 // no restrictive rules; network is visible
814 * Return a filtered {@link NetworkInfo}, potentially marked
815 * {@link DetailedState#BLOCKED} based on
816 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
818 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
819 NetworkInfo info = tracker.getNetworkInfo();
820 if (isNetworkBlocked(tracker, uid)) {
821 // network is blocked; clone and override state
822 info = new NetworkInfo(info);
823 info.setDetailedState(DetailedState.BLOCKED, null, null);
825 if (mLockdownTracker != null) {
826 info = mLockdownTracker.augmentNetworkInfo(info);
832 * Return NetworkInfo for the active (i.e., connected) network interface.
833 * It is assumed that at most one network is active at a time. If more
834 * than one is active, it is indeterminate which will be returned.
835 * @return the info for the active network, or {@code null} if none is
839 public NetworkInfo getActiveNetworkInfo() {
840 enforceAccessPermission();
841 final int uid = Binder.getCallingUid();
842 return getNetworkInfo(mActiveDefaultNetwork, uid);
845 public NetworkInfo getActiveNetworkInfoUnfiltered() {
846 enforceAccessPermission();
847 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
848 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
849 if (tracker != null) {
850 return tracker.getNetworkInfo();
857 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
858 enforceConnectivityInternalPermission();
859 return getNetworkInfo(mActiveDefaultNetwork, uid);
863 public NetworkInfo getNetworkInfo(int networkType) {
864 enforceAccessPermission();
865 final int uid = Binder.getCallingUid();
866 return getNetworkInfo(networkType, uid);
869 private NetworkInfo getNetworkInfo(int networkType, int uid) {
870 NetworkInfo info = null;
871 if (isNetworkTypeValid(networkType)) {
872 final NetworkStateTracker tracker = mNetTrackers[networkType];
873 if (tracker != null) {
874 info = getFilteredNetworkInfo(tracker, uid);
881 public NetworkInfo[] getAllNetworkInfo() {
882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 final ArrayList<NetworkInfo> result = Lists.newArrayList();
885 synchronized (mRulesLock) {
886 for (NetworkStateTracker tracker : mNetTrackers) {
887 if (tracker != null) {
888 result.add(getFilteredNetworkInfo(tracker, uid));
892 return result.toArray(new NetworkInfo[result.size()]);
896 public boolean isNetworkSupported(int networkType) {
897 enforceAccessPermission();
898 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
902 * Return LinkProperties for the active (i.e., connected) default
903 * network interface. It is assumed that at most one default network
904 * is active at a time. If more than one is active, it is indeterminate
905 * which will be returned.
906 * @return the ip properties for the active network, or {@code null} if
910 public LinkProperties getActiveLinkProperties() {
911 return getLinkProperties(mActiveDefaultNetwork);
915 public LinkProperties getLinkProperties(int networkType) {
916 enforceAccessPermission();
917 if (isNetworkTypeValid(networkType)) {
918 final NetworkStateTracker tracker = mNetTrackers[networkType];
919 if (tracker != null) {
920 return tracker.getLinkProperties();
927 public NetworkState[] getAllNetworkState() {
928 enforceAccessPermission();
929 final int uid = Binder.getCallingUid();
930 final ArrayList<NetworkState> result = Lists.newArrayList();
931 synchronized (mRulesLock) {
932 for (NetworkStateTracker tracker : mNetTrackers) {
933 if (tracker != null) {
934 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
935 result.add(new NetworkState(
936 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
940 return result.toArray(new NetworkState[result.size()]);
943 private NetworkState getNetworkStateUnchecked(int networkType) {
944 if (isNetworkTypeValid(networkType)) {
945 final NetworkStateTracker tracker = mNetTrackers[networkType];
946 if (tracker != null) {
947 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
948 tracker.getLinkCapabilities());
955 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
956 enforceAccessPermission();
958 final long token = Binder.clearCallingIdentity();
960 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
963 return mPolicyManager.getNetworkQuotaInfo(state);
964 } catch (RemoteException e) {
969 Binder.restoreCallingIdentity(token);
974 public boolean isActiveNetworkMetered() {
975 enforceAccessPermission();
976 final long token = Binder.clearCallingIdentity();
978 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
980 Binder.restoreCallingIdentity(token);
984 private boolean isNetworkMeteredUnchecked(int networkType) {
985 final NetworkState state = getNetworkStateUnchecked(networkType);
988 return mPolicyManager.isNetworkMetered(state);
989 } catch (RemoteException e) {
995 public boolean setRadios(boolean turnOn) {
996 boolean result = true;
997 enforceChangePermission();
998 for (NetworkStateTracker t : mNetTrackers) {
999 if (t != null) result = t.setRadio(turnOn) && result;
1004 public boolean setRadio(int netType, boolean turnOn) {
1005 enforceChangePermission();
1006 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1009 NetworkStateTracker tracker = mNetTrackers[netType];
1010 return tracker != null && tracker.setRadio(turnOn);
1013 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1015 public void interfaceClassDataActivityChanged(String label, boolean active) {
1016 int deviceType = Integer.parseInt(label);
1017 sendDataActivityBroadcast(deviceType, active);
1022 * Used to notice when the calling process dies so we can self-expire
1024 * Also used to know if the process has cleaned up after itself when
1025 * our auto-expire timer goes off. The timer has a link to an object.
1028 private class FeatureUser implements IBinder.DeathRecipient {
1036 FeatureUser(int type, String feature, IBinder binder) {
1038 mNetworkType = type;
1041 mPid = getCallingPid();
1042 mUid = getCallingUid();
1043 mCreateTime = System.currentTimeMillis();
1046 mBinder.linkToDeath(this, 0);
1047 } catch (RemoteException e) {
1052 void unlinkDeathRecipient() {
1053 mBinder.unlinkToDeath(this, 0);
1056 public void binderDied() {
1057 log("ConnectivityService FeatureUser binderDied(" +
1058 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1059 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1060 stopUsingNetworkFeature(this, false);
1063 public void expire() {
1065 log("ConnectivityService FeatureUser expire(" +
1066 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1067 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1069 stopUsingNetworkFeature(this, false);
1072 public boolean isSameUser(FeatureUser u) {
1073 if (u == null) return false;
1075 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1078 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1079 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1080 TextUtils.equals(mFeature, feature)) {
1086 public String toString() {
1087 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1088 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1092 // javadoc from interface
1093 public int startUsingNetworkFeature(int networkType, String feature,
1097 startTime = SystemClock.elapsedRealtime();
1100 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1101 + Binder.getCallingUid());
1103 enforceChangePermission();
1105 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1106 mNetConfigs[networkType] == null) {
1107 return PhoneConstants.APN_REQUEST_FAILED;
1110 FeatureUser f = new FeatureUser(networkType, feature, binder);
1112 // TODO - move this into individual networktrackers
1113 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1115 if (mLockdownEnabled) {
1116 // Since carrier APNs usually aren't available from VPN
1117 // endpoint, mark them as unavailable.
1118 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1121 if (mProtectedNetworks.contains(usedNetworkType)) {
1122 enforceConnectivityInternalPermission();
1125 // if UID is restricted, don't allow them to bring up metered APNs
1126 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1128 synchronized (mRulesLock) {
1129 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1131 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1132 return PhoneConstants.APN_REQUEST_FAILED;
1135 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1136 if (network != null) {
1137 Integer currentPid = new Integer(getCallingPid());
1138 if (usedNetworkType != networkType) {
1139 NetworkInfo ni = network.getNetworkInfo();
1141 if (ni.isAvailable() == false) {
1142 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1143 if (DBG) log("special network not available ni=" + ni.getTypeName());
1144 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1146 // else make the attempt anyway - probably giving REQUEST_STARTED below
1148 log("special network not available, but try anyway ni=" +
1154 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1156 synchronized(this) {
1157 boolean addToList = true;
1158 if (restoreTimer < 0) {
1159 // In case there is no timer is specified for the feature,
1160 // make sure we don't add duplicate entry with the same request.
1161 for (FeatureUser u : mFeatureUsers) {
1162 if (u.isSameUser(f)) {
1163 // Duplicate user is found. Do not add.
1170 if (addToList) mFeatureUsers.add(f);
1171 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1172 // this gets used for per-pid dns when connected
1173 mNetRequestersPids[usedNetworkType].add(currentPid);
1177 if (restoreTimer >= 0) {
1178 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1179 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1182 if ((ni.isConnectedOrConnecting() == true) &&
1183 !network.isTeardownRequested()) {
1184 if (ni.isConnected() == true) {
1185 final long token = Binder.clearCallingIdentity();
1187 // add the pid-specific dns
1188 handleDnsConfigurationChange(usedNetworkType);
1189 if (VDBG) log("special network already active");
1191 Binder.restoreCallingIdentity(token);
1193 return PhoneConstants.APN_ALREADY_ACTIVE;
1195 if (VDBG) log("special network already connecting");
1196 return PhoneConstants.APN_REQUEST_STARTED;
1199 // check if the radio in play can make another contact
1200 // assume if cannot for now
1203 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1206 if (network.reconnect()) {
1207 return PhoneConstants.APN_REQUEST_STARTED;
1209 return PhoneConstants.APN_REQUEST_FAILED;
1212 // need to remember this unsupported request so we respond appropriately on stop
1213 synchronized(this) {
1214 mFeatureUsers.add(f);
1215 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1216 // this gets used for per-pid dns when connected
1217 mNetRequestersPids[usedNetworkType].add(currentPid);
1223 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1226 final long execTime = SystemClock.elapsedRealtime() - startTime;
1227 if (execTime > 250) {
1228 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1230 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1236 // javadoc from interface
1237 public int stopUsingNetworkFeature(int networkType, String feature) {
1238 enforceChangePermission();
1240 int pid = getCallingPid();
1241 int uid = getCallingUid();
1243 FeatureUser u = null;
1244 boolean found = false;
1246 synchronized(this) {
1247 for (FeatureUser x : mFeatureUsers) {
1248 if (x.isSameUser(pid, uid, networkType, feature)) {
1255 if (found && u != null) {
1256 // stop regardless of how many other time this proc had called start
1257 return stopUsingNetworkFeature(u, true);
1260 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
1265 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1266 int networkType = u.mNetworkType;
1267 String feature = u.mFeature;
1271 NetworkStateTracker tracker = null;
1272 boolean callTeardown = false; // used to carry our decision outside of sync block
1275 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1278 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1280 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1281 ", net is invalid");
1286 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1288 synchronized(this) {
1289 // check if this process still has an outstanding start request
1290 if (!mFeatureUsers.contains(u)) {
1292 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1297 u.unlinkDeathRecipient();
1298 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1299 // If we care about duplicate requests, check for that here.
1301 // This is done to support the extension of a request - the app
1302 // can request we start the network feature again and renew the
1303 // auto-shutoff delay. Normal "stop" calls from the app though
1304 // do not pay attention to duplicate requests - in effect the
1305 // API does not refcount and a single stop will counter multiple starts.
1306 if (ignoreDups == false) {
1307 for (FeatureUser x : mFeatureUsers) {
1308 if (x.isSameUser(u)) {
1309 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1315 // TODO - move to individual network trackers
1316 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1318 tracker = mNetTrackers[usedNetworkType];
1319 if (tracker == null) {
1321 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1322 " no known tracker for used net type " + usedNetworkType);
1326 if (usedNetworkType != networkType) {
1327 Integer currentPid = new Integer(pid);
1328 mNetRequestersPids[usedNetworkType].remove(currentPid);
1330 final long token = Binder.clearCallingIdentity();
1332 reassessPidDns(pid, true);
1334 Binder.restoreCallingIdentity(token);
1337 if (mNetRequestersPids[usedNetworkType].size() != 0) {
1339 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1340 " others still using it");
1344 callTeardown = true;
1347 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1348 " not a known feature - dropping");
1355 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1365 * @deprecated use requestRouteToHostAddress instead
1367 * Ensure that a network route exists to deliver traffic to the specified
1368 * host via the specified network interface.
1369 * @param networkType the type of the network over which traffic to the
1370 * specified host is to be routed
1371 * @param hostAddress the IP address of the host to which the route is
1373 * @return {@code true} on success, {@code false} on failure
1375 public boolean requestRouteToHost(int networkType, int hostAddress) {
1376 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1378 if (inetAddress == null) {
1382 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1386 * Ensure that a network route exists to deliver traffic to the specified
1387 * host via the specified network interface.
1388 * @param networkType the type of the network over which traffic to the
1389 * specified host is to be routed
1390 * @param hostAddress the IP address of the host to which the route is
1392 * @return {@code true} on success, {@code false} on failure
1394 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1395 enforceChangePermission();
1396 if (mProtectedNetworks.contains(networkType)) {
1397 enforceConnectivityInternalPermission();
1400 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1401 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1404 NetworkStateTracker tracker = mNetTrackers[networkType];
1405 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
1407 if (tracker == null || (netState != DetailedState.CONNECTED &&
1408 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1409 tracker.isTeardownRequested()) {
1411 log("requestRouteToHostAddress on down network " +
1412 "(" + networkType + ") - dropped");
1416 final long token = Binder.clearCallingIdentity();
1418 InetAddress addr = InetAddress.getByAddress(hostAddress);
1419 LinkProperties lp = tracker.getLinkProperties();
1420 return addRouteToAddress(lp, addr);
1421 } catch (UnknownHostException e) {
1422 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1424 Binder.restoreCallingIdentity(token);
1429 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1430 return modifyRoute(p, r, 0, ADD, toDefaultTable);
1433 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1434 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
1437 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1438 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
1441 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1442 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
1445 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1446 boolean toDefaultTable) {
1447 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1448 if (bestRoute == null) {
1449 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1451 String iface = bestRoute.getInterface();
1452 if (bestRoute.getGateway().equals(addr)) {
1453 // if there is no better route, add the implied hostroute for our gateway
1454 bestRoute = RouteInfo.makeHostRoute(addr, iface);
1456 // if we will connect to this through another route, add a direct route
1458 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1461 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
1464 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1465 boolean toDefaultTable) {
1466 if ((lp == null) || (r == null)) {
1467 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1471 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1472 loge("Error modifying route - too much recursion");
1476 String ifaceName = r.getInterface();
1477 if(ifaceName == null) {
1478 loge("Error modifying route - no interface name");
1481 if (r.hasGateway()) {
1482 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1483 if (bestRoute != null) {
1484 if (bestRoute.getGateway().equals(r.getGateway())) {
1485 // if there is no better route, add the implied hostroute for our gateway
1486 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1488 // if we will connect to our gateway through another route, add a direct
1489 // route to it's gateway
1490 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1491 bestRoute.getGateway(),
1494 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
1498 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1500 if (toDefaultTable) {
1501 mAddedRoutes.add(r); // only track default table - only one apps can effect
1502 mNetd.addRoute(ifaceName, r);
1504 mNetd.addSecondaryRoute(ifaceName, r);
1506 } catch (Exception e) {
1507 // never crash - catch them all
1508 if (DBG) loge("Exception trying to add a route: " + e);
1512 // if we remove this one and there are no more like it, then refcount==0 and
1513 // we can remove it from the table
1514 if (toDefaultTable) {
1515 mAddedRoutes.remove(r);
1516 if (mAddedRoutes.contains(r) == false) {
1517 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1519 mNetd.removeRoute(ifaceName, r);
1520 } catch (Exception e) {
1521 // never crash - catch them all
1522 if (VDBG) loge("Exception trying to remove a route: " + e);
1526 if (VDBG) log("not removing " + r + " as it's still in use");
1529 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1531 mNetd.removeSecondaryRoute(ifaceName, r);
1532 } catch (Exception e) {
1533 // never crash - catch them all
1534 if (VDBG) loge("Exception trying to remove a route: " + e);
1543 * @see ConnectivityManager#getMobileDataEnabled()
1545 public boolean getMobileDataEnabled() {
1546 // TODO: This detail should probably be in DataConnectionTracker's
1547 // which is where we store the value and maybe make this
1549 enforceAccessPermission();
1550 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1551 Settings.Global.MOBILE_DATA, 1) == 1;
1552 if (VDBG) log("getMobileDataEnabled returning " + retVal);
1556 public void setDataDependency(int networkType, boolean met) {
1557 enforceConnectivityInternalPermission();
1559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1560 (met ? ENABLED : DISABLED), networkType));
1563 private void handleSetDependencyMet(int networkType, boolean met) {
1564 if (mNetTrackers[networkType] != null) {
1566 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1568 mNetTrackers[networkType].setDependencyMet(met);
1572 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1574 public void onUidRulesChanged(int uid, int uidRules) {
1575 // caller is NPMS, since we only register with them
1577 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1580 synchronized (mRulesLock) {
1581 // skip update when we've already applied rules
1582 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1583 if (oldRules == uidRules) return;
1585 mUidRules.put(uid, uidRules);
1588 // TODO: notify UID when it has requested targeted updates
1592 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1593 // caller is NPMS, since we only register with them
1595 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1598 synchronized (mRulesLock) {
1599 mMeteredIfaces.clear();
1600 for (String iface : meteredIfaces) {
1601 mMeteredIfaces.add(iface);
1607 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1608 // caller is NPMS, since we only register with them
1610 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1613 // kick off connectivity change broadcast for active network, since
1614 // global background policy change is radical.
1615 final int networkType = mActiveDefaultNetwork;
1616 if (isNetworkTypeValid(networkType)) {
1617 final NetworkStateTracker tracker = mNetTrackers[networkType];
1618 if (tracker != null) {
1619 final NetworkInfo info = tracker.getNetworkInfo();
1620 if (info != null && info.isConnected()) {
1621 sendConnectedBroadcast(info);
1629 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1631 public void setMobileDataEnabled(boolean enabled) {
1632 enforceChangePermission();
1633 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1635 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1636 (enabled ? ENABLED : DISABLED), 0));
1639 private void handleSetMobileData(boolean enabled) {
1640 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1642 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1644 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1646 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1648 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1650 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1655 public void setPolicyDataEnable(int networkType, boolean enabled) {
1656 // only someone like NPMS should only be calling us
1657 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1659 mHandler.sendMessage(mHandler.obtainMessage(
1660 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1663 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1664 if (isNetworkTypeValid(networkType)) {
1665 final NetworkStateTracker tracker = mNetTrackers[networkType];
1666 if (tracker != null) {
1667 tracker.setPolicyDataEnable(enabled);
1672 private void enforceAccessPermission() {
1673 mContext.enforceCallingOrSelfPermission(
1674 android.Manifest.permission.ACCESS_NETWORK_STATE,
1675 "ConnectivityService");
1678 private void enforceChangePermission() {
1679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.CHANGE_NETWORK_STATE,
1681 "ConnectivityService");
1684 // TODO Make this a special check when it goes public
1685 private void enforceTetherChangePermission() {
1686 mContext.enforceCallingOrSelfPermission(
1687 android.Manifest.permission.CHANGE_NETWORK_STATE,
1688 "ConnectivityService");
1691 private void enforceTetherAccessPermission() {
1692 mContext.enforceCallingOrSelfPermission(
1693 android.Manifest.permission.ACCESS_NETWORK_STATE,
1694 "ConnectivityService");
1697 private void enforceConnectivityInternalPermission() {
1698 mContext.enforceCallingOrSelfPermission(
1699 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1700 "ConnectivityService");
1704 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1705 * network, we ignore it. If it is for the active network, we send out a
1706 * broadcast. But first, we check whether it might be possible to connect
1707 * to a different network.
1708 * @param info the {@code NetworkInfo} for the network
1710 private void handleDisconnect(NetworkInfo info) {
1712 int prevNetType = info.getType();
1714 mNetTrackers[prevNetType].setTeardownRequested(false);
1716 // Remove idletimer previously setup in {@code handleConnect}
1717 removeDataActivityTracking(prevNetType);
1720 * If the disconnected network is not the active one, then don't report
1721 * this as a loss of connectivity. What probably happened is that we're
1722 * getting the disconnect for a network that we explicitly disabled
1723 * in accordance with network preference policies.
1725 if (!mNetConfigs[prevNetType].isDefault()) {
1726 List<Integer> pids = mNetRequestersPids[prevNetType];
1727 for (Integer pid : pids) {
1728 // will remove them because the net's no longer connected
1729 // need to do this now as only now do we know the pids and
1730 // can properly null things that are no longer referenced.
1731 reassessPidDns(pid.intValue(), false);
1735 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1736 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1737 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1738 if (info.isFailover()) {
1739 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1740 info.setFailover(false);
1742 if (info.getReason() != null) {
1743 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1745 if (info.getExtraInfo() != null) {
1746 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1747 info.getExtraInfo());
1750 if (mNetConfigs[prevNetType].isDefault()) {
1751 tryFailover(prevNetType);
1752 if (mActiveDefaultNetwork != -1) {
1753 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1754 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1756 mDefaultInetConditionPublished = 0; // we're not connected anymore
1757 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1760 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1762 // Reset interface if no other connections are using the same interface
1763 boolean doReset = true;
1764 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1765 if (linkProperties != null) {
1766 String oldIface = linkProperties.getInterfaceName();
1767 if (TextUtils.isEmpty(oldIface) == false) {
1768 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1769 if (networkStateTracker == null) continue;
1770 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1771 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1772 LinkProperties l = networkStateTracker.getLinkProperties();
1773 if (l == null) continue;
1774 if (oldIface.equals(l.getInterfaceName())) {
1783 // do this before we broadcast the change
1784 handleConnectivityChange(prevNetType, doReset);
1786 final Intent immediateIntent = new Intent(intent);
1787 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1788 sendStickyBroadcast(immediateIntent);
1789 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1791 * If the failover network is already connected, then immediately send
1792 * out a followup broadcast indicating successful failover
1794 if (mActiveDefaultNetwork != -1) {
1795 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1796 getConnectivityChangeDelay());
1800 private void tryFailover(int prevNetType) {
1802 * If this is a default network, check if other defaults are available.
1803 * Try to reconnect on all available and let them hash it out when
1804 * more than one connects.
1806 if (mNetConfigs[prevNetType].isDefault()) {
1807 if (mActiveDefaultNetwork == prevNetType) {
1808 mActiveDefaultNetwork = -1;
1811 // don't signal a reconnect for anything lower or equal priority than our
1812 // current connected default
1813 // TODO - don't filter by priority now - nice optimization but risky
1814 // int currentPriority = -1;
1815 // if (mActiveDefaultNetwork != -1) {
1816 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1818 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1819 if (checkType == prevNetType) continue;
1820 if (mNetConfigs[checkType] == null) continue;
1821 if (!mNetConfigs[checkType].isDefault()) continue;
1822 if (mNetTrackers[checkType] == null) continue;
1824 // Enabling the isAvailable() optimization caused mobile to not get
1825 // selected if it was in the middle of error handling. Specifically
1826 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1827 // would not be available and we wouldn't get connected to anything.
1828 // So removing the isAvailable() optimization below for now. TODO: This
1829 // optimization should work and we need to investigate why it doesn't work.
1830 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1831 // complete before it is really complete.
1832 // if (!mNetTrackers[checkType].isAvailable()) continue;
1834 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1836 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1837 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1838 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1839 checkInfo.setFailover(true);
1840 checkTracker.reconnect();
1842 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1847 public void sendConnectedBroadcast(NetworkInfo info) {
1848 enforceConnectivityInternalPermission();
1849 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1850 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1853 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1854 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1855 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1858 private void sendInetConditionBroadcast(NetworkInfo info) {
1859 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1862 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1863 if (mLockdownTracker != null) {
1864 info = mLockdownTracker.augmentNetworkInfo(info);
1867 Intent intent = new Intent(bcastType);
1868 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1869 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1870 if (info.isFailover()) {
1871 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1872 info.setFailover(false);
1874 if (info.getReason() != null) {
1875 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1877 if (info.getExtraInfo() != null) {
1878 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1879 info.getExtraInfo());
1881 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1885 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1886 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1889 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1890 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1893 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1894 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1895 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1896 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1897 final long ident = Binder.clearCallingIdentity();
1899 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1900 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1902 Binder.restoreCallingIdentity(ident);
1907 * Called when an attempt to fail over to another network has failed.
1908 * @param info the {@link NetworkInfo} for the failed network
1910 private void handleConnectionFailure(NetworkInfo info) {
1911 mNetTrackers[info.getType()].setTeardownRequested(false);
1913 String reason = info.getReason();
1914 String extraInfo = info.getExtraInfo();
1917 if (reason == null) {
1920 reasonText = " (" + reason + ").";
1922 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1924 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1925 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1927 if (getActiveNetworkInfo() == null) {
1928 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1930 if (reason != null) {
1931 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1933 if (extraInfo != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1936 if (info.isFailover()) {
1937 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1938 info.setFailover(false);
1941 if (mNetConfigs[info.getType()].isDefault()) {
1942 tryFailover(info.getType());
1943 if (mActiveDefaultNetwork != -1) {
1944 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1945 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1947 mDefaultInetConditionPublished = 0;
1948 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1952 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1954 final Intent immediateIntent = new Intent(intent);
1955 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1956 sendStickyBroadcast(immediateIntent);
1957 sendStickyBroadcast(intent);
1959 * If the failover network is already connected, then immediately send
1960 * out a followup broadcast indicating successful failover
1962 if (mActiveDefaultNetwork != -1) {
1963 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1967 private void sendStickyBroadcast(Intent intent) {
1968 synchronized(this) {
1969 if (!mSystemReady) {
1970 mInitialBroadcast = new Intent(intent);
1972 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1974 log("sendStickyBroadcast: action=" + intent.getAction());
1977 final long ident = Binder.clearCallingIdentity();
1979 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1981 Binder.restoreCallingIdentity(ident);
1986 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1988 sendStickyBroadcast(intent);
1991 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1992 + intent.getAction());
1994 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1995 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1999 void systemReady() {
2000 synchronized(this) {
2001 mSystemReady = true;
2002 if (mInitialBroadcast != null) {
2003 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2004 mInitialBroadcast = null;
2007 // load the global proxy at startup
2008 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2010 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2011 // for user to unlock device.
2012 if (!updateLockdownVpn()) {
2013 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2014 mContext.registerReceiver(mUserPresentReceiver, filter);
2018 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2020 public void onReceive(Context context, Intent intent) {
2021 // Try creating lockdown tracker, since user present usually means
2022 // unlocked keystore.
2023 if (updateLockdownVpn()) {
2024 mContext.unregisterReceiver(this);
2029 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2030 if ((type != mNetworkPreference &&
2031 mNetConfigs[mActiveDefaultNetwork].priority >
2032 mNetConfigs[type].priority) ||
2033 mNetworkPreference == mActiveDefaultNetwork) return false;
2037 private void handleConnect(NetworkInfo info) {
2038 final int newNetType = info.getType();
2040 setupDataActivityTracking(newNetType);
2042 // snapshot isFailover, because sendConnectedBroadcast() resets it
2043 boolean isFailover = info.isFailover();
2044 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2045 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2047 // if this is a default net and other default is running
2048 // kill the one not preferred
2049 if (mNetConfigs[newNetType].isDefault()) {
2050 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2051 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2052 // tear down the other
2053 NetworkStateTracker otherNet =
2054 mNetTrackers[mActiveDefaultNetwork];
2056 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2059 if (!teardown(otherNet)) {
2060 loge("Network declined teardown request");
2065 // don't accept this one
2067 log("Not broadcasting CONNECT_ACTION " +
2068 "to torn down network " + info.getTypeName());
2074 synchronized (ConnectivityService.this) {
2075 // have a new default network, release the transition wakelock in a second
2076 // if it's held. The second pause is to allow apps to reconnect over the
2078 if (mNetTransitionWakeLock.isHeld()) {
2079 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2080 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2081 mNetTransitionWakeLockSerialNumber, 0),
2085 mActiveDefaultNetwork = newNetType;
2086 // this will cause us to come up initially as unconnected and switching
2087 // to connected after our normal pause unless somebody reports us as reall
2089 mDefaultInetConditionPublished = 0;
2090 mDefaultConnectionSequence++;
2091 mInetConditionChangeInFlight = false;
2092 // Don't do this - if we never sign in stay, grey
2093 //reportNetworkCondition(mActiveDefaultNetwork, 100);
2095 thisNet.setTeardownRequested(false);
2096 updateNetworkSettings(thisNet);
2097 handleConnectivityChange(newNetType, false);
2098 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2100 // notify battery stats service about this network
2101 if (thisIface != null) {
2103 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2104 } catch (RemoteException e) {
2105 // ignored; service lives in system_server
2110 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2111 if (DBG) log("Captive portal check " + info);
2112 int type = info.getType();
2113 final NetworkStateTracker thisNet = mNetTrackers[type];
2114 if (mNetConfigs[type].isDefault()) {
2115 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2116 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2117 if (DBG) log("Captive check on " + info.getTypeName());
2118 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
2121 if (DBG) log("Tear down low priority net " + info.getTypeName());
2128 thisNet.captivePortalCheckComplete();
2132 public void captivePortalCheckComplete(NetworkInfo info) {
2133 enforceConnectivityInternalPermission();
2134 mNetTrackers[info.getType()].captivePortalCheckComplete();
2138 * Setup data activity tracking for the given network interface.
2140 * Every {@code setupDataActivityTracking} should be paired with a
2141 * {@link removeDataActivityTracking} for cleanup.
2143 private void setupDataActivityTracking(int type) {
2144 final NetworkStateTracker thisNet = mNetTrackers[type];
2145 final String iface = thisNet.getLinkProperties().getInterfaceName();
2149 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2150 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2151 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2153 // Canonicalize mobile network type
2154 type = ConnectivityManager.TYPE_MOBILE;
2155 } else if (ConnectivityManager.TYPE_WIFI == type) {
2156 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2157 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2160 // do not track any other networks
2164 if (timeout > 0 && iface != null) {
2166 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2167 } catch (RemoteException e) {
2173 * Remove data activity tracking when network disconnects.
2175 private void removeDataActivityTracking(int type) {
2176 final NetworkStateTracker net = mNetTrackers[type];
2177 final String iface = net.getLinkProperties().getInterfaceName();
2179 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2180 ConnectivityManager.TYPE_WIFI == type)) {
2182 // the call fails silently if no idletimer setup for this interface
2183 mNetd.removeIdleTimer(iface);
2184 } catch (RemoteException e) {
2190 * After a change in the connectivity state of a network. We're mainly
2191 * concerned with making sure that the list of DNS servers is set up
2192 * according to which networks are connected, and ensuring that the
2193 * right routing table entries exist.
2195 private void handleConnectivityChange(int netType, boolean doReset) {
2196 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2199 * If a non-default network is enabled, add the host routes that
2200 * will allow it's DNS servers to be accessed.
2202 handleDnsConfigurationChange(netType);
2204 LinkProperties curLp = mCurrentLinkProperties[netType];
2205 LinkProperties newLp = null;
2207 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2208 newLp = mNetTrackers[netType].getLinkProperties();
2210 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2211 " doReset=" + doReset + " resetMask=" + resetMask +
2212 "\n curLp=" + curLp +
2213 "\n newLp=" + newLp);
2216 if (curLp != null) {
2217 if (curLp.isIdenticalInterfaceName(newLp)) {
2218 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2219 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2220 for (LinkAddress linkAddr : car.removed) {
2221 if (linkAddr.getAddress() instanceof Inet4Address) {
2222 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2224 if (linkAddr.getAddress() instanceof Inet6Address) {
2225 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2229 log("handleConnectivityChange: addresses changed" +
2230 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2235 log("handleConnectivityChange: address are the same reset per doReset" +
2236 " linkProperty[" + netType + "]:" +
2237 " resetMask=" + resetMask);
2241 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2243 log("handleConnectivityChange: interface not not equivalent reset both" +
2244 " linkProperty[" + netType + "]:" +
2245 " resetMask=" + resetMask);
2249 if (mNetConfigs[netType].isDefault()) {
2250 handleApplyDefaultProxy(newLp.getHttpProxy());
2254 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2255 " doReset=" + doReset + " resetMask=" + resetMask +
2256 "\n curLp=" + curLp +
2260 mCurrentLinkProperties[netType] = newLp;
2261 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2263 if (resetMask != 0 || resetDns) {
2264 if (curLp != null) {
2265 for (String iface : curLp.getAllInterfaceNames()) {
2266 if (TextUtils.isEmpty(iface) == false) {
2267 if (resetMask != 0) {
2268 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2269 NetworkUtils.resetConnections(iface, resetMask);
2271 // Tell VPN the interface is down. It is a temporary
2272 // but effective fix to make VPN aware of the change.
2273 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2274 mVpn.interfaceStatusChanged(iface, false);
2279 if (VDBG) log("resetting DNS cache for " + iface);
2281 mNetd.flushInterfaceDnsCache(iface);
2282 } catch (Exception e) {
2283 // never crash - catch them all
2284 if (DBG) loge("Exception resetting dns cache: " + e);
2288 loge("Can't reset connection for type "+netType);
2294 // Update 464xlat state.
2295 NetworkStateTracker tracker = mNetTrackers[netType];
2296 if (mClat.requiresClat(netType, tracker)) {
2297 // If the connection was previously using clat, but is not using it now, stop the clat
2298 // daemon. Normally, this happens automatically when the connection disconnects, but if
2299 // the disconnect is not reported, or if the connection's LinkProperties changed for
2300 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2301 // still be running. If it's not running, then stopping it is a no-op.
2302 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2305 // If the link requires clat to be running, then start the daemon now.
2306 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2307 mClat.startClat(tracker);
2313 // TODO: Temporary notifying upstread change to Tethering.
2315 /** Notify TetheringService if interface name has been changed. */
2316 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2317 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2318 if (isTetheringSupported()) {
2319 mTethering.handleTetherIfaceChange();
2325 * Add and remove routes using the old properties (null if not previously connected),
2326 * new properties (null if becoming disconnected). May even be double null, which
2328 * Uses isLinkDefault to determine if default routes should be set or conversely if
2329 * host routes should be set to the dns servers
2330 * returns a boolean indicating the routes changed
2332 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2333 boolean isLinkDefault) {
2334 Collection<RouteInfo> routesToAdd = null;
2335 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2336 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2337 if (curLp != null) {
2338 // check for the delta between the current set and the new
2339 routeDiff = curLp.compareRoutes(newLp);
2340 dnsDiff = curLp.compareDnses(newLp);
2341 } else if (newLp != null) {
2342 routeDiff.added = newLp.getAllRoutes();
2343 dnsDiff.added = newLp.getDnses();
2346 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2348 for (RouteInfo r : routeDiff.removed) {
2349 if (isLinkDefault || ! r.isDefaultRoute()) {
2350 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2352 if (isLinkDefault == false) {
2353 // remove from a secondary route table
2354 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2358 if (!isLinkDefault) {
2359 // handle DNS routes
2360 if (routesChanged) {
2361 // routes changed - remove all old dns entries and add new
2362 if (curLp != null) {
2363 for (InetAddress oldDns : curLp.getDnses()) {
2364 removeRouteToAddress(curLp, oldDns);
2367 if (newLp != null) {
2368 for (InetAddress newDns : newLp.getDnses()) {
2369 addRouteToAddress(newLp, newDns);
2373 // no change in routes, check for change in dns themselves
2374 for (InetAddress oldDns : dnsDiff.removed) {
2375 removeRouteToAddress(curLp, oldDns);
2377 for (InetAddress newDns : dnsDiff.added) {
2378 addRouteToAddress(newLp, newDns);
2383 for (RouteInfo r : routeDiff.added) {
2384 if (isLinkDefault || ! r.isDefaultRoute()) {
2385 addRoute(newLp, r, TO_DEFAULT_TABLE);
2387 // add to a secondary route table
2388 addRoute(newLp, r, TO_SECONDARY_TABLE);
2390 // many radios add a default route even when we don't want one.
2391 // remove the default route unless somebody else has asked for it
2392 String ifaceName = newLp.getInterfaceName();
2393 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2394 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2396 mNetd.removeRoute(ifaceName, r);
2397 } catch (Exception e) {
2398 // never crash - catch them all
2399 if (DBG) loge("Exception trying to remove a route: " + e);
2405 return routesChanged;
2410 * Reads the network specific TCP buffer sizes from SystemProperties
2411 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2414 private void updateNetworkSettings(NetworkStateTracker nt) {
2415 String key = nt.getTcpBufferSizesPropName();
2416 String bufferSizes = key == null ? null : SystemProperties.get(key);
2418 if (TextUtils.isEmpty(bufferSizes)) {
2419 if (VDBG) log(key + " not found in system properties. Using defaults");
2421 // Setting to default values so we won't be stuck to previous values
2422 key = "net.tcp.buffersize.default";
2423 bufferSizes = SystemProperties.get(key);
2426 // Set values in kernel
2427 if (bufferSizes.length() != 0) {
2429 log("Setting TCP values: [" + bufferSizes
2430 + "] which comes from [" + key + "]");
2432 setBufferSize(bufferSizes);
2437 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2438 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2440 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2441 * writeMin, writeInitial, writeMax"
2443 private void setBufferSize(String bufferSizes) {
2445 String[] values = bufferSizes.split(",");
2447 if (values.length == 6) {
2448 final String prefix = "/sys/kernel/ipv4/tcp_";
2449 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2450 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2451 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2452 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2453 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2454 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2456 loge("Invalid buffersize string: " + bufferSizes);
2458 } catch (IOException e) {
2459 loge("Can't set tcp buffer sizes:" + e);
2464 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2465 * on the highest priority active net which this process requested.
2466 * If there aren't any, clear it out
2468 private void reassessPidDns(int pid, boolean doBump)
2470 if (VDBG) log("reassessPidDns for pid " + pid);
2471 Integer myPid = new Integer(pid);
2472 for(int i : mPriorityList) {
2473 if (mNetConfigs[i].isDefault()) {
2476 NetworkStateTracker nt = mNetTrackers[i];
2477 if (nt.getNetworkInfo().isConnected() &&
2478 !nt.isTeardownRequested()) {
2479 LinkProperties p = nt.getLinkProperties();
2480 if (p == null) continue;
2481 if (mNetRequestersPids[i].contains(myPid)) {
2483 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2484 } catch (Exception e) {
2485 Slog.e(TAG, "exception reasseses pid dns: " + e);
2491 // nothing found - delete
2493 mNetd.clearDnsInterfaceForPid(pid);
2494 } catch (Exception e) {
2495 Slog.e(TAG, "exception clear interface from pid: " + e);
2499 private void flushVmDnsCache() {
2501 * Tell the VMs to toss their DNS caches
2503 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2504 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2506 * Connectivity events can happen before boot has completed ...
2508 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2509 final long ident = Binder.clearCallingIdentity();
2511 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2513 Binder.restoreCallingIdentity(ident);
2517 // Caller must grab mDnsLock.
2518 private void updateDnsLocked(String network, String iface,
2519 Collection<InetAddress> dnses, String domains) {
2521 if (dnses.size() == 0 && mDefaultDns != null) {
2522 dnses = new ArrayList();
2523 dnses.add(mDefaultDns);
2525 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2530 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2531 mNetd.setDefaultInterfaceForDns(iface);
2532 for (InetAddress dns : dnses) {
2534 String key = "net.dns" + last;
2535 String value = dns.getHostAddress();
2536 SystemProperties.set(key, value);
2538 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2539 String key = "net.dns" + i;
2540 SystemProperties.set(key, "");
2542 mNumDnsEntries = last;
2543 } catch (Exception e) {
2544 if (DBG) loge("exception setting default dns interface: " + e);
2548 private void handleDnsConfigurationChange(int netType) {
2549 // add default net's dns entries
2550 NetworkStateTracker nt = mNetTrackers[netType];
2551 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2552 LinkProperties p = nt.getLinkProperties();
2553 if (p == null) return;
2554 Collection<InetAddress> dnses = p.getDnses();
2555 if (mNetConfigs[netType].isDefault()) {
2556 String network = nt.getNetworkInfo().getTypeName();
2557 synchronized (mDnsLock) {
2558 if (!mDnsOverridden) {
2559 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
2564 mNetd.setDnsServersForInterface(p.getInterfaceName(),
2565 NetworkUtils.makeStrings(dnses), p.getDomains());
2566 } catch (Exception e) {
2567 if (DBG) loge("exception setting dns servers: " + e);
2569 // set per-pid dns for attached secondary nets
2570 List<Integer> pids = mNetRequestersPids[netType];
2571 for (Integer pid : pids) {
2573 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2574 } catch (Exception e) {
2575 Slog.e(TAG, "exception setting interface for pid: " + e);
2583 private int getRestoreDefaultNetworkDelay(int networkType) {
2584 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2585 NETWORK_RESTORE_DELAY_PROP_NAME);
2586 if(restoreDefaultNetworkDelayStr != null &&
2587 restoreDefaultNetworkDelayStr.length() != 0) {
2589 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2590 } catch (NumberFormatException e) {
2593 // if the system property isn't set, use the value for the apn type
2594 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2596 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2597 (mNetConfigs[networkType] != null)) {
2598 ret = mNetConfigs[networkType].restoreTime;
2604 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2605 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2606 if (mContext.checkCallingOrSelfPermission(
2607 android.Manifest.permission.DUMP)
2608 != PackageManager.PERMISSION_GRANTED) {
2609 pw.println("Permission Denial: can't dump ConnectivityService " +
2610 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2611 Binder.getCallingUid());
2615 // TODO: add locking to get atomic snapshot
2617 for (int i = 0; i < mNetTrackers.length; i++) {
2618 final NetworkStateTracker nst = mNetTrackers[i];
2620 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2621 pw.increaseIndent();
2622 if (nst.getNetworkInfo().isConnected()) {
2623 pw.println("Active network: " + nst.getNetworkInfo().
2626 pw.println(nst.getNetworkInfo());
2627 pw.println(nst.getLinkProperties());
2630 pw.decreaseIndent();
2634 pw.println("Network Requester Pids:");
2635 pw.increaseIndent();
2636 for (int net : mPriorityList) {
2637 String pidString = net + ": ";
2638 for (Integer pid : mNetRequestersPids[net]) {
2639 pidString = pidString + pid.toString() + ", ";
2641 pw.println(pidString);
2644 pw.decreaseIndent();
2646 pw.println("FeatureUsers:");
2647 pw.increaseIndent();
2648 for (Object requester : mFeatureUsers) {
2649 pw.println(requester.toString());
2652 pw.decreaseIndent();
2654 synchronized (this) {
2655 pw.println("NetworkTranstionWakeLock is currently " +
2656 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2657 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2661 mTethering.dump(fd, pw, args);
2663 if (mInetLog != null) {
2665 pw.println("Inet condition reports:");
2666 pw.increaseIndent();
2667 for(int i = 0; i < mInetLog.size(); i++) {
2668 pw.println(mInetLog.get(i));
2670 pw.decreaseIndent();
2674 // must be stateless - things change under us.
2675 private class NetworkStateTrackerHandler extends Handler {
2676 public NetworkStateTrackerHandler(Looper looper) {
2681 public void handleMessage(Message msg) {
2684 case NetworkStateTracker.EVENT_STATE_CHANGED:
2685 info = (NetworkInfo) msg.obj;
2686 int type = info.getType();
2687 NetworkInfo.State state = info.getState();
2689 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2690 (state == NetworkInfo.State.DISCONNECTED)) {
2691 log("ConnectivityChange for " +
2692 info.getTypeName() + ": " +
2693 state + "/" + info.getDetailedState());
2696 EventLogTags.writeConnectivityStateChanged(
2697 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2699 if (info.getDetailedState() ==
2700 NetworkInfo.DetailedState.FAILED) {
2701 handleConnectionFailure(info);
2702 } else if (info.getDetailedState() ==
2703 DetailedState.CAPTIVE_PORTAL_CHECK) {
2704 handleCaptivePortalTrackerCheck(info);
2705 } else if (state == NetworkInfo.State.DISCONNECTED) {
2706 handleDisconnect(info);
2707 } else if (state == NetworkInfo.State.SUSPENDED) {
2708 // TODO: need to think this over.
2709 // the logic here is, handle SUSPENDED the same as
2710 // DISCONNECTED. The only difference being we are
2711 // broadcasting an intent with NetworkInfo that's
2712 // suspended. This allows the applications an
2713 // opportunity to handle DISCONNECTED and SUSPENDED
2714 // differently, or not.
2715 handleDisconnect(info);
2716 } else if (state == NetworkInfo.State.CONNECTED) {
2717 handleConnect(info);
2719 if (mLockdownTracker != null) {
2720 mLockdownTracker.onNetworkInfoChanged(info);
2723 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2724 info = (NetworkInfo) msg.obj;
2725 // TODO: Temporary allowing network configuration
2726 // change not resetting sockets.
2728 handleConnectivityChange(info.getType(), false);
2730 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2731 info = (NetworkInfo) msg.obj;
2732 type = info.getType();
2733 updateNetworkSettings(mNetTrackers[type]);
2739 private class InternalHandler extends Handler {
2740 public InternalHandler(Looper looper) {
2745 public void handleMessage(Message msg) {
2748 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2749 String causedBy = null;
2750 synchronized (ConnectivityService.this) {
2751 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2752 mNetTransitionWakeLock.isHeld()) {
2753 mNetTransitionWakeLock.release();
2754 causedBy = mNetTransitionWakeLockCausedBy;
2757 if (causedBy != null) {
2758 log("NetTransition Wakelock for " + causedBy + " released by timeout");
2761 case EVENT_RESTORE_DEFAULT_NETWORK:
2762 FeatureUser u = (FeatureUser)msg.obj;
2765 case EVENT_INET_CONDITION_CHANGE:
2767 int netType = msg.arg1;
2768 int condition = msg.arg2;
2769 handleInetConditionChange(netType, condition);
2772 case EVENT_INET_CONDITION_HOLD_END:
2774 int netType = msg.arg1;
2775 int sequence = msg.arg2;
2776 handleInetConditionHoldEnd(netType, sequence);
2779 case EVENT_SET_NETWORK_PREFERENCE:
2781 int preference = msg.arg1;
2782 handleSetNetworkPreference(preference);
2785 case EVENT_SET_MOBILE_DATA:
2787 boolean enabled = (msg.arg1 == ENABLED);
2788 handleSetMobileData(enabled);
2791 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2793 handleDeprecatedGlobalHttpProxy();
2796 case EVENT_SET_DEPENDENCY_MET:
2798 boolean met = (msg.arg1 == ENABLED);
2799 handleSetDependencyMet(msg.arg2, met);
2802 case EVENT_RESTORE_DNS:
2804 if (mActiveDefaultNetwork != -1) {
2805 handleDnsConfigurationChange(mActiveDefaultNetwork);
2809 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2811 Intent intent = (Intent)msg.obj;
2812 sendStickyBroadcast(intent);
2815 case EVENT_SET_POLICY_DATA_ENABLE: {
2816 final int networkType = msg.arg1;
2817 final boolean enabled = msg.arg2 == ENABLED;
2818 handleSetPolicyDataEnable(networkType, enabled);
2821 case EVENT_VPN_STATE_CHANGED: {
2822 if (mLockdownTracker != null) {
2823 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2831 // javadoc from interface
2832 public int tether(String iface) {
2833 enforceTetherChangePermission();
2835 if (isTetheringSupported()) {
2836 return mTethering.tether(iface);
2838 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2842 // javadoc from interface
2843 public int untether(String iface) {
2844 enforceTetherChangePermission();
2846 if (isTetheringSupported()) {
2847 return mTethering.untether(iface);
2849 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2853 // javadoc from interface
2854 public int getLastTetherError(String iface) {
2855 enforceTetherAccessPermission();
2857 if (isTetheringSupported()) {
2858 return mTethering.getLastTetherError(iface);
2860 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2864 // TODO - proper iface API for selection by property, inspection, etc
2865 public String[] getTetherableUsbRegexs() {
2866 enforceTetherAccessPermission();
2867 if (isTetheringSupported()) {
2868 return mTethering.getTetherableUsbRegexs();
2870 return new String[0];
2874 public String[] getTetherableWifiRegexs() {
2875 enforceTetherAccessPermission();
2876 if (isTetheringSupported()) {
2877 return mTethering.getTetherableWifiRegexs();
2879 return new String[0];
2883 public String[] getTetherableBluetoothRegexs() {
2884 enforceTetherAccessPermission();
2885 if (isTetheringSupported()) {
2886 return mTethering.getTetherableBluetoothRegexs();
2888 return new String[0];
2892 public int setUsbTethering(boolean enable) {
2893 enforceTetherChangePermission();
2894 if (isTetheringSupported()) {
2895 return mTethering.setUsbTethering(enable);
2897 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2901 // TODO - move iface listing, queries, etc to new module
2902 // javadoc from interface
2903 public String[] getTetherableIfaces() {
2904 enforceTetherAccessPermission();
2905 return mTethering.getTetherableIfaces();
2908 public String[] getTetheredIfaces() {
2909 enforceTetherAccessPermission();
2910 return mTethering.getTetheredIfaces();
2914 public String[] getTetheredIfacePairs() {
2915 enforceTetherAccessPermission();
2916 return mTethering.getTetheredIfacePairs();
2919 public String[] getTetheringErroredIfaces() {
2920 enforceTetherAccessPermission();
2921 return mTethering.getErroredIfaces();
2924 // if ro.tether.denied = true we default to no tethering
2925 // gservices could set the secure setting to 1 though to enable it on a build where it
2926 // had previously been turned off.
2927 public boolean isTetheringSupported() {
2928 enforceTetherAccessPermission();
2929 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2930 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2931 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
2932 return tetherEnabledInSettings && mTetheringConfigValid;
2935 // An API NetworkStateTrackers can call when they lose their network.
2936 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2937 // whichever happens first. The timer is started by the first caller and not
2938 // restarted by subsequent callers.
2939 public void requestNetworkTransitionWakelock(String forWhom) {
2940 enforceConnectivityInternalPermission();
2941 synchronized (this) {
2942 if (mNetTransitionWakeLock.isHeld()) return;
2943 mNetTransitionWakeLockSerialNumber++;
2944 mNetTransitionWakeLock.acquire();
2945 mNetTransitionWakeLockCausedBy = forWhom;
2947 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2948 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2949 mNetTransitionWakeLockSerialNumber, 0),
2950 mNetTransitionWakeLockTimeout);
2954 // 100 percent is full good, 0 is full bad.
2955 public void reportInetCondition(int networkType, int percentage) {
2956 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2957 mContext.enforceCallingOrSelfPermission(
2958 android.Manifest.permission.STATUS_BAR,
2959 "ConnectivityService");
2962 int pid = getCallingPid();
2963 int uid = getCallingUid();
2964 String s = pid + "(" + uid + ") reports inet is " +
2965 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2966 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2968 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2972 mHandler.sendMessage(mHandler.obtainMessage(
2973 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2976 private void handleInetConditionChange(int netType, int condition) {
2977 if (mActiveDefaultNetwork == -1) {
2978 if (DBG) log("handleInetConditionChange: no active default network - ignore");
2981 if (mActiveDefaultNetwork != netType) {
2982 if (DBG) log("handleInetConditionChange: net=" + netType +
2983 " != default=" + mActiveDefaultNetwork + " - ignore");
2987 log("handleInetConditionChange: net=" +
2988 netType + ", condition=" + condition +
2989 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2991 mDefaultInetCondition = condition;
2993 if (mInetConditionChangeInFlight == false) {
2994 if (VDBG) log("handleInetConditionChange: starting a change hold");
2995 // setup a new hold to debounce this
2996 if (mDefaultInetCondition > 50) {
2997 delay = Settings.Global.getInt(mContext.getContentResolver(),
2998 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3000 delay = Settings.Global.getInt(mContext.getContentResolver(),
3001 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3003 mInetConditionChangeInFlight = true;
3004 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3005 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3007 // we've set the new condition, when this hold ends that will get picked up
3008 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3012 private void handleInetConditionHoldEnd(int netType, int sequence) {
3014 log("handleInetConditionHoldEnd: net=" + netType +
3015 ", condition=" + mDefaultInetCondition +
3016 ", published condition=" + mDefaultInetConditionPublished);
3018 mInetConditionChangeInFlight = false;
3020 if (mActiveDefaultNetwork == -1) {
3021 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3024 if (mDefaultConnectionSequence != sequence) {
3025 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3028 // TODO: Figure out why this optimization sometimes causes a
3029 // change in mDefaultInetCondition to be missed and the
3030 // UI to not be updated.
3031 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3032 // if (DBG) log("no change in condition - aborting");
3035 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3036 if (networkInfo.isConnected() == false) {
3037 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3040 mDefaultInetConditionPublished = mDefaultInetCondition;
3041 sendInetConditionBroadcast(networkInfo);
3045 public ProxyProperties getProxy() {
3046 // this information is already available as a world read/writable jvm property
3047 // so this API change wouldn't have a benifit. It also breaks the passing
3048 // of proxy info to all the JVMs.
3049 // enforceAccessPermission();
3050 synchronized (mProxyLock) {
3051 if (mGlobalProxy != null) return mGlobalProxy;
3052 return (mDefaultProxyDisabled ? null : mDefaultProxy);
3056 public void setGlobalProxy(ProxyProperties proxyProperties) {
3057 enforceConnectivityInternalPermission();
3058 synchronized (mProxyLock) {
3059 if (proxyProperties == mGlobalProxy) return;
3060 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3061 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3065 String exclList = "";
3066 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3067 mGlobalProxy = new ProxyProperties(proxyProperties);
3068 host = mGlobalProxy.getHost();
3069 port = mGlobalProxy.getPort();
3070 exclList = mGlobalProxy.getExclusionList();
3072 mGlobalProxy = null;
3074 ContentResolver res = mContext.getContentResolver();
3075 final long token = Binder.clearCallingIdentity();
3077 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3078 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3079 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3082 Binder.restoreCallingIdentity(token);
3086 if (mGlobalProxy == null) {
3087 proxyProperties = mDefaultProxy;
3089 sendProxyBroadcast(proxyProperties);
3092 private void loadGlobalProxy() {
3093 ContentResolver res = mContext.getContentResolver();
3094 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3095 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3096 String exclList = Settings.Global.getString(res,
3097 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3098 if (!TextUtils.isEmpty(host)) {
3099 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3100 synchronized (mProxyLock) {
3101 mGlobalProxy = proxyProperties;
3106 public ProxyProperties getGlobalProxy() {
3107 // this information is already available as a world read/writable jvm property
3108 // so this API change wouldn't have a benifit. It also breaks the passing
3109 // of proxy info to all the JVMs.
3110 // enforceAccessPermission();
3111 synchronized (mProxyLock) {
3112 return mGlobalProxy;
3116 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3117 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3120 synchronized (mProxyLock) {
3121 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3122 if (mDefaultProxy == proxy) return; // catches repeated nulls
3123 mDefaultProxy = proxy;
3125 if (mGlobalProxy != null) return;
3126 if (!mDefaultProxyDisabled) {
3127 sendProxyBroadcast(proxy);
3132 private void handleDeprecatedGlobalHttpProxy() {
3133 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3134 Settings.Global.HTTP_PROXY);
3135 if (!TextUtils.isEmpty(proxy)) {
3136 String data[] = proxy.split(":");
3137 String proxyHost = data[0];
3138 int proxyPort = 8080;
3139 if (data.length > 1) {
3141 proxyPort = Integer.parseInt(data[1]);
3142 } catch (NumberFormatException e) {
3146 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3151 private void sendProxyBroadcast(ProxyProperties proxy) {
3152 if (proxy == null) proxy = new ProxyProperties("", 0, "");
3153 if (DBG) log("sending Proxy Broadcast for " + proxy);
3154 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3155 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3156 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3157 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3158 final long ident = Binder.clearCallingIdentity();
3160 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3162 Binder.restoreCallingIdentity(ident);
3166 private static class SettingsObserver extends ContentObserver {
3168 private Handler mHandler;
3169 SettingsObserver(Handler handler, int what) {
3175 void observe(Context context) {
3176 ContentResolver resolver = context.getContentResolver();
3177 resolver.registerContentObserver(Settings.Global.getUriFor(
3178 Settings.Global.HTTP_PROXY), false, this);
3182 public void onChange(boolean selfChange) {
3183 mHandler.obtainMessage(mWhat).sendToTarget();
3187 private static void log(String s) {
3191 private static void loge(String s) {
3195 int convertFeatureToNetworkType(int networkType, String feature) {
3196 int usedNetworkType = networkType;
3198 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3199 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3200 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3201 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3202 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3203 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3204 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3205 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3206 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3207 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3208 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3209 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3210 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3211 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3212 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3213 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3215 Slog.e(TAG, "Can't match any mobile netTracker!");
3217 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3218 if (TextUtils.equals(feature, "p2p")) {
3219 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3221 Slog.e(TAG, "Can't match any wifi netTracker!");
3224 Slog.e(TAG, "Unexpected network type");
3226 return usedNetworkType;
3229 private static <T> T checkNotNull(T value, String message) {
3230 if (value == null) {
3231 throw new NullPointerException(message);
3237 * Protect a socket from VPN routing rules. This method is used by
3238 * VpnBuilder and not available in ConnectivityManager. Permissions
3239 * are checked in Vpn class.
3243 public boolean protectVpn(ParcelFileDescriptor socket) {
3244 throwIfLockdownEnabled();
3246 int type = mActiveDefaultNetwork;
3247 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3248 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3251 } catch (Exception e) {
3256 } catch (Exception e) {
3264 * Prepare for a VPN application. This method is used by VpnDialogs
3265 * and not available in ConnectivityManager. Permissions are checked
3270 public boolean prepareVpn(String oldPackage, String newPackage) {
3271 throwIfLockdownEnabled();
3272 return mVpn.prepare(oldPackage, newPackage);
3276 * Configure a TUN interface and return its file descriptor. Parameters
3277 * are encoded and opaque to this class. This method is used by VpnBuilder
3278 * and not available in ConnectivityManager. Permissions are checked in
3283 public ParcelFileDescriptor establishVpn(VpnConfig config) {
3284 throwIfLockdownEnabled();
3285 return mVpn.establish(config);
3289 * Start legacy VPN, controlling native daemons as needed. Creates a
3290 * secondary thread to perform connection work, returning quickly.
3293 public void startLegacyVpn(VpnProfile profile) {
3294 throwIfLockdownEnabled();
3295 final LinkProperties egress = getActiveLinkProperties();
3296 if (egress == null) {
3297 throw new IllegalStateException("Missing active network connection");
3299 mVpn.startLegacyVpn(profile, mKeyStore, egress);
3303 * Return the information of the ongoing legacy VPN. This method is used
3304 * by VpnSettings and not available in ConnectivityManager. Permissions
3305 * are checked in Vpn class.
3309 public LegacyVpnInfo getLegacyVpnInfo() {
3310 throwIfLockdownEnabled();
3311 return mVpn.getLegacyVpnInfo();
3315 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3316 * through NetworkStateTracker since it works differently. For example, it
3317 * needs to override DNS servers but never takes the default routes. It
3318 * relies on another data network, and it could keep existing connections
3319 * alive after reconnecting, switching between networks, or even resuming
3320 * from deep sleep. Calls from applications should be done synchronously
3321 * to avoid race conditions. As these are all hidden APIs, refactoring can
3322 * be done whenever a better abstraction is developed.
3324 public class VpnCallback {
3325 private VpnCallback() {
3328 public void onStateChanged(NetworkInfo info) {
3329 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3332 public void override(List<String> dnsServers, List<String> searchDomains) {
3333 if (dnsServers == null) {
3338 // Convert DNS servers into addresses.
3339 List<InetAddress> addresses = new ArrayList<InetAddress>();
3340 for (String address : dnsServers) {
3341 // Double check the addresses and remove invalid ones.
3343 addresses.add(InetAddress.parseNumericAddress(address));
3344 } catch (Exception e) {
3348 if (addresses.isEmpty()) {
3353 // Concatenate search domains into a string.
3354 StringBuilder buffer = new StringBuilder();
3355 if (searchDomains != null) {
3356 for (String domain : searchDomains) {
3357 buffer.append(domain).append(' ');
3360 String domains = buffer.toString().trim();
3362 // Apply DNS changes.
3363 synchronized (mDnsLock) {
3364 updateDnsLocked("VPN", "VPN", addresses, domains);
3365 mDnsOverridden = true;
3368 // Temporarily disable the default proxy (not global).
3369 synchronized (mProxyLock) {
3370 mDefaultProxyDisabled = true;
3371 if (mGlobalProxy == null && mDefaultProxy != null) {
3372 sendProxyBroadcast(null);
3376 // TODO: support proxy per network.
3379 public void restore() {
3380 synchronized (mDnsLock) {
3381 if (mDnsOverridden) {
3382 mDnsOverridden = false;
3383 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3386 synchronized (mProxyLock) {
3387 mDefaultProxyDisabled = false;
3388 if (mGlobalProxy == null && mDefaultProxy != null) {
3389 sendProxyBroadcast(mDefaultProxy);
3396 public boolean updateLockdownVpn() {
3397 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3398 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3402 // Tear down existing lockdown if profile was removed
3403 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3404 if (mLockdownEnabled) {
3405 if (!mKeyStore.isUnlocked()) {
3406 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3410 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3411 final VpnProfile profile = VpnProfile.decode(
3412 profileName, mKeyStore.get(Credentials.VPN + profileName));
3413 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3415 setLockdownTracker(null);
3422 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3423 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3425 private void setLockdownTracker(LockdownVpnTracker tracker) {
3426 // Shutdown any existing tracker
3427 final LockdownVpnTracker existing = mLockdownTracker;
3428 mLockdownTracker = null;
3429 if (existing != null) {
3430 existing.shutdown();
3434 if (tracker != null) {
3435 mNetd.setFirewallEnabled(true);
3436 mNetd.setFirewallInterfaceRule("lo", true);
3437 mLockdownTracker = tracker;
3438 mLockdownTracker.init();
3440 mNetd.setFirewallEnabled(false);
3442 } catch (RemoteException e) {
3443 // ignored; NMS lives inside system_server
3447 private void throwIfLockdownEnabled() {
3448 if (mLockdownEnabled) {
3449 throw new IllegalStateException("Unavailable in lockdown mode");
3453 public void supplyMessenger(int networkType, Messenger messenger) {
3454 enforceConnectivityInternalPermission();
3456 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3457 mNetTrackers[networkType].supplyMessenger(messenger);
3461 public int findConnectionTypeForIface(String iface) {
3462 enforceConnectivityInternalPermission();
3464 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3465 for (NetworkStateTracker tracker : mNetTrackers) {
3466 if (tracker != null) {
3467 LinkProperties lp = tracker.getLinkProperties();
3468 if (lp != null && iface.equals(lp.getInterfaceName())) {
3469 return tracker.getNetworkInfo().getType();
3473 return ConnectivityManager.TYPE_NONE;