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.app.Notification;
35 import android.app.NotificationManager;
36 import android.app.PendingIntent;
37 import android.bluetooth.BluetoothTetheringDataTracker;
38 import android.content.BroadcastReceiver;
39 import android.content.ContentResolver;
40 import android.content.Context;
41 import android.content.ContextWrapper;
42 import android.content.Intent;
43 import android.content.IntentFilter;
44 import android.content.pm.PackageManager;
45 import android.content.res.Configuration;
46 import android.content.res.Resources;
47 import android.database.ContentObserver;
48 import android.net.CaptivePortalTracker;
49 import android.net.ConnectivityManager;
50 import android.net.DummyDataStateTracker;
51 import android.net.EthernetDataTracker;
52 import android.net.IConnectivityManager;
53 import android.net.INetworkManagementEventObserver;
54 import android.net.INetworkPolicyListener;
55 import android.net.INetworkPolicyManager;
56 import android.net.INetworkStatsService;
57 import android.net.LinkAddress;
58 import android.net.LinkProperties;
59 import android.net.Uri;
60 import android.net.LinkProperties.CompareResult;
61 import android.net.MobileDataStateTracker;
62 import android.net.NetworkConfig;
63 import android.net.NetworkInfo;
64 import android.net.NetworkInfo.DetailedState;
65 import android.net.NetworkInfo.State;
66 import android.net.NetworkQuotaInfo;
67 import android.net.NetworkState;
68 import android.net.NetworkStateTracker;
69 import android.net.NetworkUtils;
70 import android.net.Proxy;
71 import android.net.ProxyProperties;
72 import android.net.RouteInfo;
73 import android.net.wifi.WifiStateTracker;
74 import android.net.wimax.WimaxManagerConstants;
75 import android.os.AsyncTask;
76 import android.os.Binder;
77 import android.os.FileUtils;
78 import android.os.Handler;
79 import android.os.HandlerThread;
80 import android.os.IBinder;
81 import android.os.INetworkManagementService;
82 import android.os.Looper;
83 import android.os.Message;
84 import android.os.Messenger;
85 import android.os.ParcelFileDescriptor;
86 import android.os.PowerManager;
87 import android.os.Process;
88 import android.os.RemoteException;
89 import android.os.ResultReceiver;
90 import android.os.ServiceManager;
91 import android.os.SystemClock;
92 import android.os.SystemProperties;
93 import android.os.UserHandle;
94 import android.provider.Settings;
95 import android.security.Credentials;
96 import android.security.KeyStore;
97 import android.telephony.TelephonyManager;
98 import android.text.TextUtils;
99 import android.util.Slog;
100 import android.util.SparseIntArray;
101 import android.util.Xml;
103 import com.android.internal.R;
104 import com.android.internal.net.LegacyVpnInfo;
105 import com.android.internal.net.VpnConfig;
106 import com.android.internal.net.VpnProfile;
107 import com.android.internal.telephony.DctConstants;
108 import com.android.internal.telephony.Phone;
109 import com.android.internal.telephony.PhoneConstants;
110 import com.android.internal.util.IndentingPrintWriter;
111 import com.android.internal.util.XmlUtils;
112 import com.android.server.am.BatteryStatsService;
113 import com.android.server.connectivity.Nat464Xlat;
114 import com.android.server.connectivity.Tethering;
115 import com.android.server.connectivity.Vpn;
116 import com.android.server.net.BaseNetworkObserver;
117 import com.android.server.net.LockdownVpnTracker;
118 import com.google.android.collect.Lists;
119 import com.google.android.collect.Sets;
121 import dalvik.system.DexClassLoader;
123 import org.xmlpull.v1.XmlPullParser;
124 import org.xmlpull.v1.XmlPullParserException;
127 import java.io.FileDescriptor;
128 import java.io.FileNotFoundException;
129 import java.io.FileReader;
130 import java.io.IOException;
131 import java.io.PrintWriter;
132 import java.lang.reflect.Constructor;
133 import java.net.HttpURLConnection;
134 import java.net.Inet4Address;
135 import java.net.Inet6Address;
136 import java.net.InetAddress;
138 import java.net.UnknownHostException;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Collection;
142 import java.util.GregorianCalendar;
143 import java.util.HashSet;
144 import java.util.List;
145 import java.util.Random;
146 import java.util.concurrent.atomic.AtomicInteger;
151 public class ConnectivityService extends IConnectivityManager.Stub {
152 private static final String TAG = "ConnectivityService";
154 private static final boolean DBG = true;
155 private static final boolean VDBG = false;
157 private static final boolean LOGD_RULES = false;
159 // TODO: create better separation between radio types and network types
161 // how long to wait before switching back to a radio's default network
162 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
163 // system property that can override the above value
164 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
165 "android.telephony.apn-restore";
167 // Default value if FAIL_FAST_TIME_MS is not set
168 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
169 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
170 private static final String FAIL_FAST_TIME_MS =
171 "persist.radio.fail_fast_time_ms";
173 // used in recursive route setting to add gateways for the host for which
174 // a host route was requested.
175 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
177 private Tethering mTethering;
179 private KeyStore mKeyStore;
182 private VpnCallback mVpnCallback = new VpnCallback();
184 private boolean mLockdownEnabled;
185 private LockdownVpnTracker mLockdownTracker;
187 private Nat464Xlat mClat;
189 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
190 private Object mRulesLock = new Object();
191 /** Currently active network rules by UID. */
192 private SparseIntArray mUidRules = new SparseIntArray();
193 /** Set of ifaces that are costly. */
194 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
197 * Sometimes we want to refer to the individual network state
198 * trackers separately, and sometimes we just want to treat them
201 private NetworkStateTracker mNetTrackers[];
203 /* Handles captive portal check on a network */
204 private CaptivePortalTracker mCaptivePortalTracker;
207 * The link properties that define the current links
209 private LinkProperties mCurrentLinkProperties[];
212 * A per Net list of the PID's that requested access to the net
213 * used both as a refcount and for per-PID DNS selection
215 private List<Integer> mNetRequestersPids[];
217 // priority order of the nettrackers
218 // (excluding dynamically set mNetworkPreference)
219 // TODO - move mNetworkTypePreference into this
220 private int[] mPriorityList;
222 private Context mContext;
223 private int mNetworkPreference;
224 private int mActiveDefaultNetwork = -1;
225 // 0 is full bad, 100 is full good
226 private int mDefaultInetCondition = 0;
227 private int mDefaultInetConditionPublished = 0;
228 private boolean mInetConditionChangeInFlight = false;
229 private int mDefaultConnectionSequence = 0;
231 private Object mDnsLock = new Object();
232 private int mNumDnsEntries;
233 private boolean mDnsOverridden = false;
235 private boolean mTestMode;
236 private static ConnectivityService sServiceInstance;
238 private INetworkManagementService mNetd;
239 private INetworkPolicyManager mPolicyManager;
241 private static final int ENABLED = 1;
242 private static final int DISABLED = 0;
244 private static final boolean ADD = true;
245 private static final boolean REMOVE = false;
247 private static final boolean TO_DEFAULT_TABLE = true;
248 private static final boolean TO_SECONDARY_TABLE = false;
251 * used internally as a delayed event to make us switch back to the
254 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
257 * used internally to change our mobile data enabled flag
259 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
262 * used internally to change our network preference setting
263 * arg1 = networkType to prefer
265 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
268 * used internally to synchronize inet condition reports
270 * arg2 = condition (0 bad, 100 good)
272 private static final int EVENT_INET_CONDITION_CHANGE = 4;
275 * used internally to mark the end of inet condition hold periods
278 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
281 * used internally to set enable/disable cellular data
282 * arg1 = ENBALED or DISABLED
284 private static final int EVENT_SET_MOBILE_DATA = 7;
287 * used internally to clear a wakelock when transitioning
288 * from one net to another
290 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
293 * used internally to reload global proxy settings
295 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
298 * used internally to set external dependency met/unmet
299 * arg1 = ENABLED (met) or DISABLED (unmet)
302 private static final int EVENT_SET_DEPENDENCY_MET = 10;
305 * used internally to restore DNS properties back to the
308 private static final int EVENT_RESTORE_DNS = 11;
311 * used internally to send a sticky broadcast delayed.
313 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
317 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
319 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
321 private static final int EVENT_VPN_STATE_CHANGED = 14;
324 * Used internally to disable fail fast of mobile data
326 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
328 /** Handler used for internal events. */
329 private InternalHandler mHandler;
330 /** Handler used for incoming {@link NetworkStateTracker} events. */
331 private NetworkStateTrackerHandler mTrackerHandler;
333 // list of DeathRecipients used to make sure features are turned off when
335 private List<FeatureUser> mFeatureUsers;
337 private boolean mSystemReady;
338 private Intent mInitialBroadcast;
340 private PowerManager.WakeLock mNetTransitionWakeLock;
341 private String mNetTransitionWakeLockCausedBy = "";
342 private int mNetTransitionWakeLockSerialNumber;
343 private int mNetTransitionWakeLockTimeout;
345 private InetAddress mDefaultDns;
347 // this collection is used to refcount the added routes - if there are none left
348 // it's time to remove the route from the route table
349 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
351 // used in DBG mode to track inet condition reports
352 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
353 private ArrayList mInetLog;
355 // track the current default http proxy - tell the world if we get a new one (real change)
356 private ProxyProperties mDefaultProxy = null;
357 private Object mProxyLock = new Object();
358 private boolean mDefaultProxyDisabled = false;
360 // track the global proxy.
361 private ProxyProperties mGlobalProxy = null;
363 private SettingsObserver mSettingsObserver;
365 NetworkConfig[] mNetConfigs;
366 int mNetworksDefined;
368 private static class RadioAttributes {
369 public int mSimultaneity;
371 public RadioAttributes(String init) {
372 String fragments[] = init.split(",");
373 mType = Integer.parseInt(fragments[0]);
374 mSimultaneity = Integer.parseInt(fragments[1]);
377 RadioAttributes[] mRadioAttributes;
379 // the set of network types that can only be enabled by system/sig apps
380 List mProtectedNetworks;
382 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
384 TelephonyManager mTelephonyManager;
386 // We only want one checkMobileProvisioning after booting.
387 volatile boolean mFirstProvisioningCheckStarted = false;
389 public ConnectivityService(Context context, INetworkManagementService netd,
390 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
391 // Currently, omitting a NetworkFactory will create one internally
392 // TODO: create here when we have cleaner WiMAX support
393 this(context, netd, statsService, policyManager, null);
396 public ConnectivityService(Context context, INetworkManagementService netManager,
397 INetworkStatsService statsService, INetworkPolicyManager policyManager,
398 NetworkFactory netFactory) {
399 if (DBG) log("ConnectivityService starting up");
401 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
402 handlerThread.start();
403 mHandler = new InternalHandler(handlerThread.getLooper());
404 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
406 if (netFactory == null) {
407 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
410 // setup our unique device name
411 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
412 String id = Settings.Secure.getString(context.getContentResolver(),
413 Settings.Secure.ANDROID_ID);
414 if (id != null && id.length() > 0) {
415 String name = new String("android-").concat(id);
416 SystemProperties.set("net.hostname", name);
420 // read our default dns server ip
421 String dns = Settings.Global.getString(context.getContentResolver(),
422 Settings.Global.DEFAULT_DNS_SERVER);
423 if (dns == null || dns.length() == 0) {
424 dns = context.getResources().getString(
425 com.android.internal.R.string.config_default_dns_server);
428 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
429 } catch (IllegalArgumentException e) {
430 loge("Error setting defaultDns using " + dns);
433 mContext = checkNotNull(context, "missing Context");
434 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
435 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
436 mKeyStore = KeyStore.getInstance();
437 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
440 mPolicyManager.registerListener(mPolicyListener);
441 } catch (RemoteException e) {
442 // ouch, no rules updates means some processes may never get network
443 loge("unable to register INetworkPolicyListener" + e.toString());
446 final PowerManager powerManager = (PowerManager) context.getSystemService(
447 Context.POWER_SERVICE);
448 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
449 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
450 com.android.internal.R.integer.config_networkTransitionTimeout);
452 mNetTrackers = new NetworkStateTracker[
453 ConnectivityManager.MAX_NETWORK_TYPE+1];
454 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
456 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
457 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
459 // Load device network attributes from resources
460 String[] raStrings = context.getResources().getStringArray(
461 com.android.internal.R.array.radioAttributes);
462 for (String raString : raStrings) {
463 RadioAttributes r = new RadioAttributes(raString);
464 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
465 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
468 if (mRadioAttributes[r.mType] != null) {
469 loge("Error in radioAttributes - ignoring attempt to redefine type " +
473 mRadioAttributes[r.mType] = r;
476 // TODO: What is the "correct" way to do determine if this is a wifi only device?
477 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
478 log("wifiOnly=" + wifiOnly);
479 String[] naStrings = context.getResources().getStringArray(
480 com.android.internal.R.array.networkAttributes);
481 for (String naString : naStrings) {
483 NetworkConfig n = new NetworkConfig(naString);
484 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
485 loge("Error in networkAttributes - ignoring attempt to define type " +
489 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
490 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
494 if (mNetConfigs[n.type] != null) {
495 loge("Error in networkAttributes - ignoring attempt to redefine type " +
499 if (mRadioAttributes[n.radio] == null) {
500 loge("Error in networkAttributes - ignoring attempt to use undefined " +
501 "radio " + n.radio + " in network type " + n.type);
504 mNetConfigs[n.type] = n;
506 } catch(Exception e) {
507 // ignore it - leave the entry null
511 mProtectedNetworks = new ArrayList<Integer>();
512 int[] protectedNetworks = context.getResources().getIntArray(
513 com.android.internal.R.array.config_protectedNetworks);
514 for (int p : protectedNetworks) {
515 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
516 mProtectedNetworks.add(p);
518 if (DBG) loge("Ignoring protectedNetwork " + p);
522 // high priority first
523 mPriorityList = new int[mNetworksDefined];
525 int insertionPoint = mNetworksDefined-1;
526 int currentLowest = 0;
528 while (insertionPoint > -1) {
529 for (NetworkConfig na : mNetConfigs) {
530 if (na == null) continue;
531 if (na.priority < currentLowest) continue;
532 if (na.priority > currentLowest) {
533 if (na.priority < nextLowest || nextLowest == 0) {
534 nextLowest = na.priority;
538 mPriorityList[insertionPoint--] = na.type;
540 currentLowest = nextLowest;
545 // Update mNetworkPreference according to user mannually first then overlay config.xml
546 mNetworkPreference = getPersistedNetworkPreference();
547 if (mNetworkPreference == -1) {
548 for (int n : mPriorityList) {
549 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
550 mNetworkPreference = n;
554 if (mNetworkPreference == -1) {
555 throw new IllegalStateException(
556 "You should set at least one default Network in config.xml!");
561 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
562 for (int i : mPriorityList) {
563 mNetRequestersPids[i] = new ArrayList<Integer>();
566 mFeatureUsers = new ArrayList<FeatureUser>();
568 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
569 && SystemProperties.get("ro.build.type").equals("eng");
571 // Create and start trackers for hard-coded networks
572 for (int targetNetworkType : mPriorityList) {
573 final NetworkConfig config = mNetConfigs[targetNetworkType];
574 final NetworkStateTracker tracker;
576 tracker = netFactory.createTracker(targetNetworkType, config);
577 mNetTrackers[targetNetworkType] = tracker;
578 } catch (IllegalArgumentException e) {
579 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
584 tracker.startMonitoring(context, mTrackerHandler);
585 if (config.isDefault()) {
590 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
592 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
593 mVpn.startMonitoring(mContext, mTrackerHandler);
595 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
598 mNetd.registerObserver(mTethering);
599 mNetd.registerObserver(mDataActivityObserver);
600 mNetd.registerObserver(mClat);
601 } catch (RemoteException e) {
602 loge("Error registering observer :" + e);
606 mInetLog = new ArrayList();
609 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
610 mSettingsObserver.observe(mContext);
612 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
617 * Factory that creates {@link NetworkStateTracker} instances using given
618 * {@link NetworkConfig}.
620 public interface NetworkFactory {
621 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
624 private static class DefaultNetworkFactory implements NetworkFactory {
625 private final Context mContext;
626 private final Handler mTrackerHandler;
628 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
630 mTrackerHandler = trackerHandler;
634 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
635 switch (config.radio) {
637 return new WifiStateTracker(targetNetworkType, config.name);
639 return new MobileDataStateTracker(targetNetworkType, config.name);
641 return new DummyDataStateTracker(targetNetworkType, config.name);
643 return BluetoothTetheringDataTracker.getInstance();
645 return makeWimaxStateTracker(mContext, mTrackerHandler);
647 return EthernetDataTracker.getInstance();
649 throw new IllegalArgumentException(
650 "Trying to create a NetworkStateTracker for an unknown radio type: "
657 * Loads external WiMAX library and registers as system service, returning a
658 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
659 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
661 private static NetworkStateTracker makeWimaxStateTracker(
662 Context context, Handler trackerHandler) {
664 DexClassLoader wimaxClassLoader;
665 Class wimaxStateTrackerClass = null;
666 Class wimaxServiceClass = null;
667 Class wimaxManagerClass;
668 String wimaxJarLocation;
669 String wimaxLibLocation;
670 String wimaxManagerClassName;
671 String wimaxServiceClassName;
672 String wimaxStateTrackerClassName;
674 NetworkStateTracker wimaxStateTracker = null;
676 boolean isWimaxEnabled = context.getResources().getBoolean(
677 com.android.internal.R.bool.config_wimaxEnabled);
679 if (isWimaxEnabled) {
681 wimaxJarLocation = context.getResources().getString(
682 com.android.internal.R.string.config_wimaxServiceJarLocation);
683 wimaxLibLocation = context.getResources().getString(
684 com.android.internal.R.string.config_wimaxNativeLibLocation);
685 wimaxManagerClassName = context.getResources().getString(
686 com.android.internal.R.string.config_wimaxManagerClassname);
687 wimaxServiceClassName = context.getResources().getString(
688 com.android.internal.R.string.config_wimaxServiceClassname);
689 wimaxStateTrackerClassName = context.getResources().getString(
690 com.android.internal.R.string.config_wimaxStateTrackerClassname);
692 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
693 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
694 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
695 wimaxLibLocation, ClassLoader.getSystemClassLoader());
698 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
699 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
700 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
701 } catch (ClassNotFoundException ex) {
702 loge("Exception finding Wimax classes: " + ex.toString());
705 } catch(Resources.NotFoundException ex) {
706 loge("Wimax Resources does not exist!!! ");
711 if (DBG) log("Starting Wimax Service... ");
713 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
714 (new Class[] {Context.class, Handler.class});
715 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
716 context, trackerHandler);
718 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
719 (new Class[] {Context.class, wimaxStateTrackerClass});
720 wmxSrvConst.setAccessible(true);
721 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
722 wmxSrvConst.setAccessible(false);
724 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
726 } catch(Exception ex) {
727 loge("Exception creating Wimax classes: " + ex.toString());
731 loge("Wimax is not enabled or not added to the network attributes!!! ");
735 return wimaxStateTracker;
739 * Sets the preferred network.
740 * @param preference the new preference
742 public void setNetworkPreference(int preference) {
743 enforceChangePermission();
745 mHandler.sendMessage(
746 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
749 public int getNetworkPreference() {
750 enforceAccessPermission();
753 preference = mNetworkPreference;
758 private void handleSetNetworkPreference(int preference) {
759 if (ConnectivityManager.isNetworkTypeValid(preference) &&
760 mNetConfigs[preference] != null &&
761 mNetConfigs[preference].isDefault()) {
762 if (mNetworkPreference != preference) {
763 final ContentResolver cr = mContext.getContentResolver();
764 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
766 mNetworkPreference = preference;
773 private int getConnectivityChangeDelay() {
774 final ContentResolver cr = mContext.getContentResolver();
776 /** Check system properties for the default value then use secure settings value, if any. */
777 int defaultDelay = SystemProperties.getInt(
778 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
779 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
780 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
784 private int getPersistedNetworkPreference() {
785 final ContentResolver cr = mContext.getContentResolver();
787 final int networkPrefSetting = Settings.Global
788 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
790 return networkPrefSetting;
794 * Make the state of network connectivity conform to the preference settings
795 * In this method, we only tear down a non-preferred network. Establishing
796 * a connection to the preferred network is taken care of when we handle
797 * the disconnect event from the non-preferred network
798 * (see {@link #handleDisconnect(NetworkInfo)}).
800 private void enforcePreference() {
801 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
804 if (!mNetTrackers[mNetworkPreference].isAvailable())
807 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
808 if (t != mNetworkPreference && mNetTrackers[t] != null &&
809 mNetTrackers[t].getNetworkInfo().isConnected()) {
811 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
812 " in enforcePreference");
814 teardown(mNetTrackers[t]);
819 private boolean teardown(NetworkStateTracker netTracker) {
820 if (netTracker.teardown()) {
821 netTracker.setTeardownRequested(true);
829 * Check if UID should be blocked from using the network represented by the
830 * given {@link NetworkStateTracker}.
832 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
833 final String iface = tracker.getLinkProperties().getInterfaceName();
835 final boolean networkCostly;
837 synchronized (mRulesLock) {
838 networkCostly = mMeteredIfaces.contains(iface);
839 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
842 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
846 // no restrictive rules; network is visible
851 * Return a filtered {@link NetworkInfo}, potentially marked
852 * {@link DetailedState#BLOCKED} based on
853 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
855 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
856 NetworkInfo info = tracker.getNetworkInfo();
857 if (isNetworkBlocked(tracker, uid)) {
858 // network is blocked; clone and override state
859 info = new NetworkInfo(info);
860 info.setDetailedState(DetailedState.BLOCKED, null, null);
862 if (mLockdownTracker != null) {
863 info = mLockdownTracker.augmentNetworkInfo(info);
869 * Return NetworkInfo for the active (i.e., connected) network interface.
870 * It is assumed that at most one network is active at a time. If more
871 * than one is active, it is indeterminate which will be returned.
872 * @return the info for the active network, or {@code null} if none is
876 public NetworkInfo getActiveNetworkInfo() {
877 enforceAccessPermission();
878 final int uid = Binder.getCallingUid();
879 return getNetworkInfo(mActiveDefaultNetwork, uid);
882 public NetworkInfo getActiveNetworkInfoUnfiltered() {
883 enforceAccessPermission();
884 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
885 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
886 if (tracker != null) {
887 return tracker.getNetworkInfo();
894 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
895 enforceConnectivityInternalPermission();
896 return getNetworkInfo(mActiveDefaultNetwork, uid);
900 public NetworkInfo getNetworkInfo(int networkType) {
901 enforceAccessPermission();
902 final int uid = Binder.getCallingUid();
903 return getNetworkInfo(networkType, uid);
906 private NetworkInfo getNetworkInfo(int networkType, int uid) {
907 NetworkInfo info = null;
908 if (isNetworkTypeValid(networkType)) {
909 final NetworkStateTracker tracker = mNetTrackers[networkType];
910 if (tracker != null) {
911 info = getFilteredNetworkInfo(tracker, uid);
918 public NetworkInfo[] getAllNetworkInfo() {
919 enforceAccessPermission();
920 final int uid = Binder.getCallingUid();
921 final ArrayList<NetworkInfo> result = Lists.newArrayList();
922 synchronized (mRulesLock) {
923 for (NetworkStateTracker tracker : mNetTrackers) {
924 if (tracker != null) {
925 result.add(getFilteredNetworkInfo(tracker, uid));
929 return result.toArray(new NetworkInfo[result.size()]);
933 public boolean isNetworkSupported(int networkType) {
934 enforceAccessPermission();
935 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
939 * Return LinkProperties for the active (i.e., connected) default
940 * network interface. It is assumed that at most one default network
941 * is active at a time. If more than one is active, it is indeterminate
942 * which will be returned.
943 * @return the ip properties for the active network, or {@code null} if
947 public LinkProperties getActiveLinkProperties() {
948 return getLinkProperties(mActiveDefaultNetwork);
952 public LinkProperties getLinkProperties(int networkType) {
953 enforceAccessPermission();
954 if (isNetworkTypeValid(networkType)) {
955 final NetworkStateTracker tracker = mNetTrackers[networkType];
956 if (tracker != null) {
957 return tracker.getLinkProperties();
964 public NetworkState[] getAllNetworkState() {
965 enforceAccessPermission();
966 final int uid = Binder.getCallingUid();
967 final ArrayList<NetworkState> result = Lists.newArrayList();
968 synchronized (mRulesLock) {
969 for (NetworkStateTracker tracker : mNetTrackers) {
970 if (tracker != null) {
971 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
972 result.add(new NetworkState(
973 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
977 return result.toArray(new NetworkState[result.size()]);
980 private NetworkState getNetworkStateUnchecked(int networkType) {
981 if (isNetworkTypeValid(networkType)) {
982 final NetworkStateTracker tracker = mNetTrackers[networkType];
983 if (tracker != null) {
984 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
985 tracker.getLinkCapabilities());
992 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
993 enforceAccessPermission();
995 final long token = Binder.clearCallingIdentity();
997 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1000 return mPolicyManager.getNetworkQuotaInfo(state);
1001 } catch (RemoteException e) {
1006 Binder.restoreCallingIdentity(token);
1011 public boolean isActiveNetworkMetered() {
1012 enforceAccessPermission();
1013 final long token = Binder.clearCallingIdentity();
1015 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1017 Binder.restoreCallingIdentity(token);
1021 private boolean isNetworkMeteredUnchecked(int networkType) {
1022 final NetworkState state = getNetworkStateUnchecked(networkType);
1023 if (state != null) {
1025 return mPolicyManager.isNetworkMetered(state);
1026 } catch (RemoteException e) {
1032 public boolean setRadios(boolean turnOn) {
1033 boolean result = true;
1034 enforceChangePermission();
1035 for (NetworkStateTracker t : mNetTrackers) {
1036 if (t != null) result = t.setRadio(turnOn) && result;
1041 public boolean setRadio(int netType, boolean turnOn) {
1042 enforceChangePermission();
1043 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1046 NetworkStateTracker tracker = mNetTrackers[netType];
1047 return tracker != null && tracker.setRadio(turnOn);
1050 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1052 public void interfaceClassDataActivityChanged(String label, boolean active) {
1053 int deviceType = Integer.parseInt(label);
1054 sendDataActivityBroadcast(deviceType, active);
1059 * Used to notice when the calling process dies so we can self-expire
1061 * Also used to know if the process has cleaned up after itself when
1062 * our auto-expire timer goes off. The timer has a link to an object.
1065 private class FeatureUser implements IBinder.DeathRecipient {
1073 FeatureUser(int type, String feature, IBinder binder) {
1075 mNetworkType = type;
1078 mPid = getCallingPid();
1079 mUid = getCallingUid();
1080 mCreateTime = System.currentTimeMillis();
1083 mBinder.linkToDeath(this, 0);
1084 } catch (RemoteException e) {
1089 void unlinkDeathRecipient() {
1090 mBinder.unlinkToDeath(this, 0);
1093 public void binderDied() {
1094 log("ConnectivityService FeatureUser binderDied(" +
1095 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1096 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1097 stopUsingNetworkFeature(this, false);
1100 public void expire() {
1102 log("ConnectivityService FeatureUser expire(" +
1103 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1104 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1106 stopUsingNetworkFeature(this, false);
1109 public boolean isSameUser(FeatureUser u) {
1110 if (u == null) return false;
1112 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1115 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1116 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1117 TextUtils.equals(mFeature, feature)) {
1123 public String toString() {
1124 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1125 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1129 // javadoc from interface
1130 public int startUsingNetworkFeature(int networkType, String feature,
1134 startTime = SystemClock.elapsedRealtime();
1137 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1138 + Binder.getCallingUid());
1140 enforceChangePermission();
1142 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1143 mNetConfigs[networkType] == null) {
1144 return PhoneConstants.APN_REQUEST_FAILED;
1147 FeatureUser f = new FeatureUser(networkType, feature, binder);
1149 // TODO - move this into individual networktrackers
1150 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1152 if (mLockdownEnabled) {
1153 // Since carrier APNs usually aren't available from VPN
1154 // endpoint, mark them as unavailable.
1155 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1158 if (mProtectedNetworks.contains(usedNetworkType)) {
1159 enforceConnectivityInternalPermission();
1162 // if UID is restricted, don't allow them to bring up metered APNs
1163 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1165 synchronized (mRulesLock) {
1166 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1168 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1169 return PhoneConstants.APN_REQUEST_FAILED;
1172 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1173 if (network != null) {
1174 Integer currentPid = new Integer(getCallingPid());
1175 if (usedNetworkType != networkType) {
1176 NetworkInfo ni = network.getNetworkInfo();
1178 if (ni.isAvailable() == false) {
1179 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1180 if (DBG) log("special network not available ni=" + ni.getTypeName());
1181 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1183 // else make the attempt anyway - probably giving REQUEST_STARTED below
1185 log("special network not available, but try anyway ni=" +
1191 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1193 synchronized(this) {
1194 boolean addToList = true;
1195 if (restoreTimer < 0) {
1196 // In case there is no timer is specified for the feature,
1197 // make sure we don't add duplicate entry with the same request.
1198 for (FeatureUser u : mFeatureUsers) {
1199 if (u.isSameUser(f)) {
1200 // Duplicate user is found. Do not add.
1207 if (addToList) mFeatureUsers.add(f);
1208 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1209 // this gets used for per-pid dns when connected
1210 mNetRequestersPids[usedNetworkType].add(currentPid);
1214 if (restoreTimer >= 0) {
1215 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1216 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1219 if ((ni.isConnectedOrConnecting() == true) &&
1220 !network.isTeardownRequested()) {
1221 if (ni.isConnected() == true) {
1222 final long token = Binder.clearCallingIdentity();
1224 // add the pid-specific dns
1225 handleDnsConfigurationChange(usedNetworkType);
1226 if (VDBG) log("special network already active");
1228 Binder.restoreCallingIdentity(token);
1230 return PhoneConstants.APN_ALREADY_ACTIVE;
1232 if (VDBG) log("special network already connecting");
1233 return PhoneConstants.APN_REQUEST_STARTED;
1236 // check if the radio in play can make another contact
1237 // assume if cannot for now
1240 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1243 if (network.reconnect()) {
1244 return PhoneConstants.APN_REQUEST_STARTED;
1246 return PhoneConstants.APN_REQUEST_FAILED;
1249 // need to remember this unsupported request so we respond appropriately on stop
1250 synchronized(this) {
1251 mFeatureUsers.add(f);
1252 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1253 // this gets used for per-pid dns when connected
1254 mNetRequestersPids[usedNetworkType].add(currentPid);
1260 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1263 final long execTime = SystemClock.elapsedRealtime() - startTime;
1264 if (execTime > 250) {
1265 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1267 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1273 // javadoc from interface
1274 public int stopUsingNetworkFeature(int networkType, String feature) {
1275 enforceChangePermission();
1277 int pid = getCallingPid();
1278 int uid = getCallingUid();
1280 FeatureUser u = null;
1281 boolean found = false;
1283 synchronized(this) {
1284 for (FeatureUser x : mFeatureUsers) {
1285 if (x.isSameUser(pid, uid, networkType, feature)) {
1292 if (found && u != null) {
1293 // stop regardless of how many other time this proc had called start
1294 return stopUsingNetworkFeature(u, true);
1297 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
1302 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1303 int networkType = u.mNetworkType;
1304 String feature = u.mFeature;
1308 NetworkStateTracker tracker = null;
1309 boolean callTeardown = false; // used to carry our decision outside of sync block
1312 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1315 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1318 ", net is invalid");
1323 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1325 synchronized(this) {
1326 // check if this process still has an outstanding start request
1327 if (!mFeatureUsers.contains(u)) {
1329 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1334 u.unlinkDeathRecipient();
1335 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1336 // If we care about duplicate requests, check for that here.
1338 // This is done to support the extension of a request - the app
1339 // can request we start the network feature again and renew the
1340 // auto-shutoff delay. Normal "stop" calls from the app though
1341 // do not pay attention to duplicate requests - in effect the
1342 // API does not refcount and a single stop will counter multiple starts.
1343 if (ignoreDups == false) {
1344 for (FeatureUser x : mFeatureUsers) {
1345 if (x.isSameUser(u)) {
1346 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1352 // TODO - move to individual network trackers
1353 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1355 tracker = mNetTrackers[usedNetworkType];
1356 if (tracker == null) {
1358 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1359 " no known tracker for used net type " + usedNetworkType);
1363 if (usedNetworkType != networkType) {
1364 Integer currentPid = new Integer(pid);
1365 mNetRequestersPids[usedNetworkType].remove(currentPid);
1367 final long token = Binder.clearCallingIdentity();
1369 reassessPidDns(pid, true);
1371 Binder.restoreCallingIdentity(token);
1374 if (mNetRequestersPids[usedNetworkType].size() != 0) {
1376 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1377 " others still using it");
1381 callTeardown = true;
1384 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1385 " not a known feature - dropping");
1392 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1402 * @deprecated use requestRouteToHostAddress instead
1404 * Ensure that a network route exists to deliver traffic to the specified
1405 * host via the specified network interface.
1406 * @param networkType the type of the network over which traffic to the
1407 * specified host is to be routed
1408 * @param hostAddress the IP address of the host to which the route is
1410 * @return {@code true} on success, {@code false} on failure
1412 public boolean requestRouteToHost(int networkType, int hostAddress) {
1413 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1415 if (inetAddress == null) {
1419 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1423 * Ensure that a network route exists to deliver traffic to the specified
1424 * host via the specified network interface.
1425 * @param networkType the type of the network over which traffic to the
1426 * specified host is to be routed
1427 * @param hostAddress the IP address of the host to which the route is
1429 * @return {@code true} on success, {@code false} on failure
1431 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1432 enforceChangePermission();
1433 if (mProtectedNetworks.contains(networkType)) {
1434 enforceConnectivityInternalPermission();
1437 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1438 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1441 NetworkStateTracker tracker = mNetTrackers[networkType];
1442 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
1444 if (tracker == null || (netState != DetailedState.CONNECTED &&
1445 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1446 tracker.isTeardownRequested()) {
1448 log("requestRouteToHostAddress on down network "
1449 + "(" + networkType + ") - dropped"
1450 + " tracker=" + tracker
1451 + " netState=" + netState
1452 + " isTeardownRequested="
1453 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
1457 final long token = Binder.clearCallingIdentity();
1459 InetAddress addr = InetAddress.getByAddress(hostAddress);
1460 LinkProperties lp = tracker.getLinkProperties();
1461 boolean ok = addRouteToAddress(lp, addr);
1462 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1464 } catch (UnknownHostException e) {
1465 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1467 Binder.restoreCallingIdentity(token);
1469 if (DBG) log("requestRouteToHostAddress X bottom return false");
1473 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1474 return modifyRoute(p, r, 0, ADD, toDefaultTable);
1477 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1478 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
1481 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1482 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
1485 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1486 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
1489 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1490 boolean toDefaultTable) {
1491 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1492 if (bestRoute == null) {
1493 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1495 String iface = bestRoute.getInterface();
1496 if (bestRoute.getGateway().equals(addr)) {
1497 // if there is no better route, add the implied hostroute for our gateway
1498 bestRoute = RouteInfo.makeHostRoute(addr, iface);
1500 // if we will connect to this through another route, add a direct route
1502 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1505 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
1508 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1509 boolean toDefaultTable) {
1510 if ((lp == null) || (r == null)) {
1511 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1515 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1516 loge("Error modifying route - too much recursion");
1520 String ifaceName = r.getInterface();
1521 if(ifaceName == null) {
1522 loge("Error modifying route - no interface name");
1525 if (r.hasGateway()) {
1526 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1527 if (bestRoute != null) {
1528 if (bestRoute.getGateway().equals(r.getGateway())) {
1529 // if there is no better route, add the implied hostroute for our gateway
1530 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1532 // if we will connect to our gateway through another route, add a direct
1533 // route to it's gateway
1534 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1535 bestRoute.getGateway(),
1538 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
1542 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1544 if (toDefaultTable) {
1545 mAddedRoutes.add(r); // only track default table - only one apps can effect
1546 mNetd.addRoute(ifaceName, r);
1548 mNetd.addSecondaryRoute(ifaceName, r);
1550 } catch (Exception e) {
1551 // never crash - catch them all
1552 if (DBG) loge("Exception trying to add a route: " + e);
1556 // if we remove this one and there are no more like it, then refcount==0 and
1557 // we can remove it from the table
1558 if (toDefaultTable) {
1559 mAddedRoutes.remove(r);
1560 if (mAddedRoutes.contains(r) == false) {
1561 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1563 mNetd.removeRoute(ifaceName, r);
1564 } catch (Exception e) {
1565 // never crash - catch them all
1566 if (VDBG) loge("Exception trying to remove a route: " + e);
1570 if (VDBG) log("not removing " + r + " as it's still in use");
1573 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1575 mNetd.removeSecondaryRoute(ifaceName, r);
1576 } catch (Exception e) {
1577 // never crash - catch them all
1578 if (VDBG) loge("Exception trying to remove a route: " + e);
1587 * @see ConnectivityManager#getMobileDataEnabled()
1589 public boolean getMobileDataEnabled() {
1590 // TODO: This detail should probably be in DataConnectionTracker's
1591 // which is where we store the value and maybe make this
1593 enforceAccessPermission();
1594 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1595 Settings.Global.MOBILE_DATA, 1) == 1;
1596 if (VDBG) log("getMobileDataEnabled returning " + retVal);
1600 public void setDataDependency(int networkType, boolean met) {
1601 enforceConnectivityInternalPermission();
1603 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1604 (met ? ENABLED : DISABLED), networkType));
1607 private void handleSetDependencyMet(int networkType, boolean met) {
1608 if (mNetTrackers[networkType] != null) {
1610 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1612 mNetTrackers[networkType].setDependencyMet(met);
1616 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1618 public void onUidRulesChanged(int uid, int uidRules) {
1619 // caller is NPMS, since we only register with them
1621 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1624 synchronized (mRulesLock) {
1625 // skip update when we've already applied rules
1626 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1627 if (oldRules == uidRules) return;
1629 mUidRules.put(uid, uidRules);
1632 // TODO: notify UID when it has requested targeted updates
1636 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1637 // caller is NPMS, since we only register with them
1639 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1642 synchronized (mRulesLock) {
1643 mMeteredIfaces.clear();
1644 for (String iface : meteredIfaces) {
1645 mMeteredIfaces.add(iface);
1651 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1652 // caller is NPMS, since we only register with them
1654 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1657 // kick off connectivity change broadcast for active network, since
1658 // global background policy change is radical.
1659 final int networkType = mActiveDefaultNetwork;
1660 if (isNetworkTypeValid(networkType)) {
1661 final NetworkStateTracker tracker = mNetTrackers[networkType];
1662 if (tracker != null) {
1663 final NetworkInfo info = tracker.getNetworkInfo();
1664 if (info != null && info.isConnected()) {
1665 sendConnectedBroadcast(info);
1673 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1675 public void setMobileDataEnabled(boolean enabled) {
1676 enforceChangePermission();
1677 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1680 (enabled ? ENABLED : DISABLED), 0));
1683 private void handleSetMobileData(boolean enabled) {
1684 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1686 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1688 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1690 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1692 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1694 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1699 public void setPolicyDataEnable(int networkType, boolean enabled) {
1700 // only someone like NPMS should only be calling us
1701 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1703 mHandler.sendMessage(mHandler.obtainMessage(
1704 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1707 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1708 if (isNetworkTypeValid(networkType)) {
1709 final NetworkStateTracker tracker = mNetTrackers[networkType];
1710 if (tracker != null) {
1711 tracker.setPolicyDataEnable(enabled);
1716 private void enforceAccessPermission() {
1717 mContext.enforceCallingOrSelfPermission(
1718 android.Manifest.permission.ACCESS_NETWORK_STATE,
1719 "ConnectivityService");
1722 private void enforceChangePermission() {
1723 mContext.enforceCallingOrSelfPermission(
1724 android.Manifest.permission.CHANGE_NETWORK_STATE,
1725 "ConnectivityService");
1728 // TODO Make this a special check when it goes public
1729 private void enforceTetherChangePermission() {
1730 mContext.enforceCallingOrSelfPermission(
1731 android.Manifest.permission.CHANGE_NETWORK_STATE,
1732 "ConnectivityService");
1735 private void enforceTetherAccessPermission() {
1736 mContext.enforceCallingOrSelfPermission(
1737 android.Manifest.permission.ACCESS_NETWORK_STATE,
1738 "ConnectivityService");
1741 private void enforceConnectivityInternalPermission() {
1742 mContext.enforceCallingOrSelfPermission(
1743 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1744 "ConnectivityService");
1748 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1749 * network, we ignore it. If it is for the active network, we send out a
1750 * broadcast. But first, we check whether it might be possible to connect
1751 * to a different network.
1752 * @param info the {@code NetworkInfo} for the network
1754 private void handleDisconnect(NetworkInfo info) {
1756 int prevNetType = info.getType();
1758 mNetTrackers[prevNetType].setTeardownRequested(false);
1760 // Remove idletimer previously setup in {@code handleConnect}
1761 removeDataActivityTracking(prevNetType);
1764 * If the disconnected network is not the active one, then don't report
1765 * this as a loss of connectivity. What probably happened is that we're
1766 * getting the disconnect for a network that we explicitly disabled
1767 * in accordance with network preference policies.
1769 if (!mNetConfigs[prevNetType].isDefault()) {
1770 List<Integer> pids = mNetRequestersPids[prevNetType];
1771 for (Integer pid : pids) {
1772 // will remove them because the net's no longer connected
1773 // need to do this now as only now do we know the pids and
1774 // can properly null things that are no longer referenced.
1775 reassessPidDns(pid.intValue(), false);
1779 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1780 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1781 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1782 if (info.isFailover()) {
1783 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1784 info.setFailover(false);
1786 if (info.getReason() != null) {
1787 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1789 if (info.getExtraInfo() != null) {
1790 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1791 info.getExtraInfo());
1794 if (mNetConfigs[prevNetType].isDefault()) {
1795 tryFailover(prevNetType);
1796 if (mActiveDefaultNetwork != -1) {
1797 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1798 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1800 mDefaultInetConditionPublished = 0; // we're not connected anymore
1801 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1804 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1806 // Reset interface if no other connections are using the same interface
1807 boolean doReset = true;
1808 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1809 if (linkProperties != null) {
1810 String oldIface = linkProperties.getInterfaceName();
1811 if (TextUtils.isEmpty(oldIface) == false) {
1812 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1813 if (networkStateTracker == null) continue;
1814 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1815 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1816 LinkProperties l = networkStateTracker.getLinkProperties();
1817 if (l == null) continue;
1818 if (oldIface.equals(l.getInterfaceName())) {
1827 // do this before we broadcast the change
1828 handleConnectivityChange(prevNetType, doReset);
1830 final Intent immediateIntent = new Intent(intent);
1831 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1832 sendStickyBroadcast(immediateIntent);
1833 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1835 * If the failover network is already connected, then immediately send
1836 * out a followup broadcast indicating successful failover
1838 if (mActiveDefaultNetwork != -1) {
1839 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1840 getConnectivityChangeDelay());
1844 private void tryFailover(int prevNetType) {
1846 * If this is a default network, check if other defaults are available.
1847 * Try to reconnect on all available and let them hash it out when
1848 * more than one connects.
1850 if (mNetConfigs[prevNetType].isDefault()) {
1851 if (mActiveDefaultNetwork == prevNetType) {
1852 mActiveDefaultNetwork = -1;
1855 // don't signal a reconnect for anything lower or equal priority than our
1856 // current connected default
1857 // TODO - don't filter by priority now - nice optimization but risky
1858 // int currentPriority = -1;
1859 // if (mActiveDefaultNetwork != -1) {
1860 // currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1862 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1863 if (checkType == prevNetType) continue;
1864 if (mNetConfigs[checkType] == null) continue;
1865 if (!mNetConfigs[checkType].isDefault()) continue;
1866 if (mNetTrackers[checkType] == null) continue;
1868 // Enabling the isAvailable() optimization caused mobile to not get
1869 // selected if it was in the middle of error handling. Specifically
1870 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1871 // would not be available and we wouldn't get connected to anything.
1872 // So removing the isAvailable() optimization below for now. TODO: This
1873 // optimization should work and we need to investigate why it doesn't work.
1874 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1875 // complete before it is really complete.
1876 // if (!mNetTrackers[checkType].isAvailable()) continue;
1878 // if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1880 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1881 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1882 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1883 checkInfo.setFailover(true);
1884 checkTracker.reconnect();
1886 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1891 public void sendConnectedBroadcast(NetworkInfo info) {
1892 enforceConnectivityInternalPermission();
1893 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1894 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1897 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1898 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1899 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1902 private void sendInetConditionBroadcast(NetworkInfo info) {
1903 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1906 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1907 if (mLockdownTracker != null) {
1908 info = mLockdownTracker.augmentNetworkInfo(info);
1911 Intent intent = new Intent(bcastType);
1912 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1913 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1914 if (info.isFailover()) {
1915 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1916 info.setFailover(false);
1918 if (info.getReason() != null) {
1919 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1921 if (info.getExtraInfo() != null) {
1922 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1923 info.getExtraInfo());
1925 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1929 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1930 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1933 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1934 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1937 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1938 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1939 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1940 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1941 final long ident = Binder.clearCallingIdentity();
1943 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1944 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1946 Binder.restoreCallingIdentity(ident);
1951 * Called when an attempt to fail over to another network has failed.
1952 * @param info the {@link NetworkInfo} for the failed network
1954 private void handleConnectionFailure(NetworkInfo info) {
1955 mNetTrackers[info.getType()].setTeardownRequested(false);
1957 String reason = info.getReason();
1958 String extraInfo = info.getExtraInfo();
1961 if (reason == null) {
1964 reasonText = " (" + reason + ").";
1966 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1968 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1969 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1970 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1971 if (getActiveNetworkInfo() == null) {
1972 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1974 if (reason != null) {
1975 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1977 if (extraInfo != null) {
1978 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1980 if (info.isFailover()) {
1981 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1982 info.setFailover(false);
1985 if (mNetConfigs[info.getType()].isDefault()) {
1986 tryFailover(info.getType());
1987 if (mActiveDefaultNetwork != -1) {
1988 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1989 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1991 mDefaultInetConditionPublished = 0;
1992 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1996 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1998 final Intent immediateIntent = new Intent(intent);
1999 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2000 sendStickyBroadcast(immediateIntent);
2001 sendStickyBroadcast(intent);
2003 * If the failover network is already connected, then immediately send
2004 * out a followup broadcast indicating successful failover
2006 if (mActiveDefaultNetwork != -1) {
2007 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
2011 private void sendStickyBroadcast(Intent intent) {
2012 synchronized(this) {
2013 if (!mSystemReady) {
2014 mInitialBroadcast = new Intent(intent);
2016 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2018 log("sendStickyBroadcast: action=" + intent.getAction());
2021 final long ident = Binder.clearCallingIdentity();
2023 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2025 Binder.restoreCallingIdentity(ident);
2030 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2032 sendStickyBroadcast(intent);
2035 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2036 + intent.getAction());
2038 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2039 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2043 void systemReady() {
2044 synchronized(this) {
2045 mSystemReady = true;
2046 if (mInitialBroadcast != null) {
2047 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2048 mInitialBroadcast = null;
2051 // load the global proxy at startup
2052 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2054 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2055 // for user to unlock device.
2056 if (!updateLockdownVpn()) {
2057 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2058 mContext.registerReceiver(mUserPresentReceiver, filter);
2062 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2064 public void onReceive(Context context, Intent intent) {
2065 // Try creating lockdown tracker, since user present usually means
2066 // unlocked keystore.
2067 if (updateLockdownVpn()) {
2068 mContext.unregisterReceiver(this);
2073 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2074 if ((type != mNetworkPreference &&
2075 mNetConfigs[mActiveDefaultNetwork].priority >
2076 mNetConfigs[type].priority) ||
2077 mNetworkPreference == mActiveDefaultNetwork) return false;
2081 private void handleConnect(NetworkInfo info) {
2082 final int newNetType = info.getType();
2084 setupDataActivityTracking(newNetType);
2086 // snapshot isFailover, because sendConnectedBroadcast() resets it
2087 boolean isFailover = info.isFailover();
2088 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2089 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2091 // if this is a default net and other default is running
2092 // kill the one not preferred
2093 if (mNetConfigs[newNetType].isDefault()) {
2094 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2095 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2096 // tear down the other
2097 NetworkStateTracker otherNet =
2098 mNetTrackers[mActiveDefaultNetwork];
2100 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2103 if (!teardown(otherNet)) {
2104 loge("Network declined teardown request");
2109 // don't accept this one
2111 log("Not broadcasting CONNECT_ACTION " +
2112 "to torn down network " + info.getTypeName());
2118 synchronized (ConnectivityService.this) {
2119 // have a new default network, release the transition wakelock in a second
2120 // if it's held. The second pause is to allow apps to reconnect over the
2122 if (mNetTransitionWakeLock.isHeld()) {
2123 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2124 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2125 mNetTransitionWakeLockSerialNumber, 0),
2129 mActiveDefaultNetwork = newNetType;
2130 // this will cause us to come up initially as unconnected and switching
2131 // to connected after our normal pause unless somebody reports us as reall
2133 mDefaultInetConditionPublished = 0;
2134 mDefaultConnectionSequence++;
2135 mInetConditionChangeInFlight = false;
2136 // Don't do this - if we never sign in stay, grey
2137 //reportNetworkCondition(mActiveDefaultNetwork, 100);
2139 thisNet.setTeardownRequested(false);
2140 updateNetworkSettings(thisNet);
2141 handleConnectivityChange(newNetType, false);
2142 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2144 // notify battery stats service about this network
2145 if (thisIface != null) {
2147 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2148 } catch (RemoteException e) {
2149 // ignored; service lives in system_server
2154 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2155 if (DBG) log("Captive portal check " + info);
2156 int type = info.getType();
2157 final NetworkStateTracker thisNet = mNetTrackers[type];
2158 if (mNetConfigs[type].isDefault()) {
2159 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2160 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2161 if (DBG) log("Captive check on " + info.getTypeName());
2162 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
2165 if (DBG) log("Tear down low priority net " + info.getTypeName());
2172 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
2173 thisNet.captivePortalCheckComplete();
2178 public void captivePortalCheckComplete(NetworkInfo info) {
2179 enforceConnectivityInternalPermission();
2180 if (DBG) log("captivePortalCheckComplete: ni=" + info);
2181 mNetTrackers[info.getType()].captivePortalCheckComplete();
2186 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2187 enforceConnectivityInternalPermission();
2188 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2189 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2193 * Setup data activity tracking for the given network interface.
2195 * Every {@code setupDataActivityTracking} should be paired with a
2196 * {@link removeDataActivityTracking} for cleanup.
2198 private void setupDataActivityTracking(int type) {
2199 final NetworkStateTracker thisNet = mNetTrackers[type];
2200 final String iface = thisNet.getLinkProperties().getInterfaceName();
2204 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2205 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2206 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2208 // Canonicalize mobile network type
2209 type = ConnectivityManager.TYPE_MOBILE;
2210 } else if (ConnectivityManager.TYPE_WIFI == type) {
2211 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2212 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2215 // do not track any other networks
2219 if (timeout > 0 && iface != null) {
2221 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2222 } catch (RemoteException e) {
2228 * Remove data activity tracking when network disconnects.
2230 private void removeDataActivityTracking(int type) {
2231 final NetworkStateTracker net = mNetTrackers[type];
2232 final String iface = net.getLinkProperties().getInterfaceName();
2234 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2235 ConnectivityManager.TYPE_WIFI == type)) {
2237 // the call fails silently if no idletimer setup for this interface
2238 mNetd.removeIdleTimer(iface);
2239 } catch (RemoteException e) {
2245 * After a change in the connectivity state of a network. We're mainly
2246 * concerned with making sure that the list of DNS servers is set up
2247 * according to which networks are connected, and ensuring that the
2248 * right routing table entries exist.
2250 private void handleConnectivityChange(int netType, boolean doReset) {
2251 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2254 * If a non-default network is enabled, add the host routes that
2255 * will allow it's DNS servers to be accessed.
2257 handleDnsConfigurationChange(netType);
2259 LinkProperties curLp = mCurrentLinkProperties[netType];
2260 LinkProperties newLp = null;
2262 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2263 newLp = mNetTrackers[netType].getLinkProperties();
2265 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2266 " doReset=" + doReset + " resetMask=" + resetMask +
2267 "\n curLp=" + curLp +
2268 "\n newLp=" + newLp);
2271 if (curLp != null) {
2272 if (curLp.isIdenticalInterfaceName(newLp)) {
2273 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2274 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2275 for (LinkAddress linkAddr : car.removed) {
2276 if (linkAddr.getAddress() instanceof Inet4Address) {
2277 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2279 if (linkAddr.getAddress() instanceof Inet6Address) {
2280 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2284 log("handleConnectivityChange: addresses changed" +
2285 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2290 log("handleConnectivityChange: address are the same reset per doReset" +
2291 " linkProperty[" + netType + "]:" +
2292 " resetMask=" + resetMask);
2296 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2298 log("handleConnectivityChange: interface not not equivalent reset both" +
2299 " linkProperty[" + netType + "]:" +
2300 " resetMask=" + resetMask);
2304 if (mNetConfigs[netType].isDefault()) {
2305 handleApplyDefaultProxy(newLp.getHttpProxy());
2309 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2310 " doReset=" + doReset + " resetMask=" + resetMask +
2311 "\n curLp=" + curLp +
2315 mCurrentLinkProperties[netType] = newLp;
2316 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2318 if (resetMask != 0 || resetDns) {
2319 if (curLp != null) {
2320 for (String iface : curLp.getAllInterfaceNames()) {
2321 if (TextUtils.isEmpty(iface) == false) {
2322 if (resetMask != 0) {
2323 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2324 NetworkUtils.resetConnections(iface, resetMask);
2326 // Tell VPN the interface is down. It is a temporary
2327 // but effective fix to make VPN aware of the change.
2328 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2329 mVpn.interfaceStatusChanged(iface, false);
2334 if (VDBG) log("resetting DNS cache for " + iface);
2336 mNetd.flushInterfaceDnsCache(iface);
2337 } catch (Exception e) {
2338 // never crash - catch them all
2339 if (DBG) loge("Exception resetting dns cache: " + e);
2343 loge("Can't reset connection for type "+netType);
2349 // Update 464xlat state.
2350 NetworkStateTracker tracker = mNetTrackers[netType];
2351 if (mClat.requiresClat(netType, tracker)) {
2352 // If the connection was previously using clat, but is not using it now, stop the clat
2353 // daemon. Normally, this happens automatically when the connection disconnects, but if
2354 // the disconnect is not reported, or if the connection's LinkProperties changed for
2355 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2356 // still be running. If it's not running, then stopping it is a no-op.
2357 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2360 // If the link requires clat to be running, then start the daemon now.
2361 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2362 mClat.startClat(tracker);
2368 // TODO: Temporary notifying upstread change to Tethering.
2370 /** Notify TetheringService if interface name has been changed. */
2371 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2372 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2373 if (isTetheringSupported()) {
2374 mTethering.handleTetherIfaceChange();
2380 * Add and remove routes using the old properties (null if not previously connected),
2381 * new properties (null if becoming disconnected). May even be double null, which
2383 * Uses isLinkDefault to determine if default routes should be set or conversely if
2384 * host routes should be set to the dns servers
2385 * returns a boolean indicating the routes changed
2387 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2388 boolean isLinkDefault) {
2389 Collection<RouteInfo> routesToAdd = null;
2390 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2391 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2392 if (curLp != null) {
2393 // check for the delta between the current set and the new
2394 routeDiff = curLp.compareRoutes(newLp);
2395 dnsDiff = curLp.compareDnses(newLp);
2396 } else if (newLp != null) {
2397 routeDiff.added = newLp.getAllRoutes();
2398 dnsDiff.added = newLp.getDnses();
2401 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2403 for (RouteInfo r : routeDiff.removed) {
2404 if (isLinkDefault || ! r.isDefaultRoute()) {
2405 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2407 if (isLinkDefault == false) {
2408 // remove from a secondary route table
2409 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2413 if (!isLinkDefault) {
2414 // handle DNS routes
2415 if (routesChanged) {
2416 // routes changed - remove all old dns entries and add new
2417 if (curLp != null) {
2418 for (InetAddress oldDns : curLp.getDnses()) {
2419 removeRouteToAddress(curLp, oldDns);
2422 if (newLp != null) {
2423 for (InetAddress newDns : newLp.getDnses()) {
2424 addRouteToAddress(newLp, newDns);
2428 // no change in routes, check for change in dns themselves
2429 for (InetAddress oldDns : dnsDiff.removed) {
2430 removeRouteToAddress(curLp, oldDns);
2432 for (InetAddress newDns : dnsDiff.added) {
2433 addRouteToAddress(newLp, newDns);
2438 for (RouteInfo r : routeDiff.added) {
2439 if (isLinkDefault || ! r.isDefaultRoute()) {
2440 addRoute(newLp, r, TO_DEFAULT_TABLE);
2442 // add to a secondary route table
2443 addRoute(newLp, r, TO_SECONDARY_TABLE);
2445 // many radios add a default route even when we don't want one.
2446 // remove the default route unless somebody else has asked for it
2447 String ifaceName = newLp.getInterfaceName();
2448 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2449 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2451 mNetd.removeRoute(ifaceName, r);
2452 } catch (Exception e) {
2453 // never crash - catch them all
2454 if (DBG) loge("Exception trying to remove a route: " + e);
2460 return routesChanged;
2465 * Reads the network specific TCP buffer sizes from SystemProperties
2466 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2469 private void updateNetworkSettings(NetworkStateTracker nt) {
2470 String key = nt.getTcpBufferSizesPropName();
2471 String bufferSizes = key == null ? null : SystemProperties.get(key);
2473 if (TextUtils.isEmpty(bufferSizes)) {
2474 if (VDBG) log(key + " not found in system properties. Using defaults");
2476 // Setting to default values so we won't be stuck to previous values
2477 key = "net.tcp.buffersize.default";
2478 bufferSizes = SystemProperties.get(key);
2481 // Set values in kernel
2482 if (bufferSizes.length() != 0) {
2484 log("Setting TCP values: [" + bufferSizes
2485 + "] which comes from [" + key + "]");
2487 setBufferSize(bufferSizes);
2492 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2493 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2495 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2496 * writeMin, writeInitial, writeMax"
2498 private void setBufferSize(String bufferSizes) {
2500 String[] values = bufferSizes.split(",");
2502 if (values.length == 6) {
2503 final String prefix = "/sys/kernel/ipv4/tcp_";
2504 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2505 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2506 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2507 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2508 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2509 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2511 loge("Invalid buffersize string: " + bufferSizes);
2513 } catch (IOException e) {
2514 loge("Can't set tcp buffer sizes:" + e);
2519 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2520 * on the highest priority active net which this process requested.
2521 * If there aren't any, clear it out
2523 private void reassessPidDns(int pid, boolean doBump)
2525 if (VDBG) log("reassessPidDns for pid " + pid);
2526 Integer myPid = new Integer(pid);
2527 for(int i : mPriorityList) {
2528 if (mNetConfigs[i].isDefault()) {
2531 NetworkStateTracker nt = mNetTrackers[i];
2532 if (nt.getNetworkInfo().isConnected() &&
2533 !nt.isTeardownRequested()) {
2534 LinkProperties p = nt.getLinkProperties();
2535 if (p == null) continue;
2536 if (mNetRequestersPids[i].contains(myPid)) {
2538 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2539 } catch (Exception e) {
2540 Slog.e(TAG, "exception reasseses pid dns: " + e);
2546 // nothing found - delete
2548 mNetd.clearDnsInterfaceForPid(pid);
2549 } catch (Exception e) {
2550 Slog.e(TAG, "exception clear interface from pid: " + e);
2554 private void flushVmDnsCache() {
2556 * Tell the VMs to toss their DNS caches
2558 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2559 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2561 * Connectivity events can happen before boot has completed ...
2563 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2564 final long ident = Binder.clearCallingIdentity();
2566 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2568 Binder.restoreCallingIdentity(ident);
2572 // Caller must grab mDnsLock.
2573 private void updateDnsLocked(String network, String iface,
2574 Collection<InetAddress> dnses, String domains) {
2576 if (dnses.size() == 0 && mDefaultDns != null) {
2577 dnses = new ArrayList();
2578 dnses.add(mDefaultDns);
2580 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2585 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2586 mNetd.setDefaultInterfaceForDns(iface);
2587 for (InetAddress dns : dnses) {
2589 String key = "net.dns" + last;
2590 String value = dns.getHostAddress();
2591 SystemProperties.set(key, value);
2593 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2594 String key = "net.dns" + i;
2595 SystemProperties.set(key, "");
2597 mNumDnsEntries = last;
2598 } catch (Exception e) {
2599 if (DBG) loge("exception setting default dns interface: " + e);
2603 private void handleDnsConfigurationChange(int netType) {
2604 // add default net's dns entries
2605 NetworkStateTracker nt = mNetTrackers[netType];
2606 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2607 LinkProperties p = nt.getLinkProperties();
2608 if (p == null) return;
2609 Collection<InetAddress> dnses = p.getDnses();
2610 if (mNetConfigs[netType].isDefault()) {
2611 String network = nt.getNetworkInfo().getTypeName();
2612 synchronized (mDnsLock) {
2613 if (!mDnsOverridden) {
2614 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
2619 mNetd.setDnsServersForInterface(p.getInterfaceName(),
2620 NetworkUtils.makeStrings(dnses), p.getDomains());
2621 } catch (Exception e) {
2622 if (DBG) loge("exception setting dns servers: " + e);
2624 // set per-pid dns for attached secondary nets
2625 List<Integer> pids = mNetRequestersPids[netType];
2626 for (Integer pid : pids) {
2628 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2629 } catch (Exception e) {
2630 Slog.e(TAG, "exception setting interface for pid: " + e);
2638 private int getRestoreDefaultNetworkDelay(int networkType) {
2639 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2640 NETWORK_RESTORE_DELAY_PROP_NAME);
2641 if(restoreDefaultNetworkDelayStr != null &&
2642 restoreDefaultNetworkDelayStr.length() != 0) {
2644 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2645 } catch (NumberFormatException e) {
2648 // if the system property isn't set, use the value for the apn type
2649 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2651 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2652 (mNetConfigs[networkType] != null)) {
2653 ret = mNetConfigs[networkType].restoreTime;
2659 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2660 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2661 if (mContext.checkCallingOrSelfPermission(
2662 android.Manifest.permission.DUMP)
2663 != PackageManager.PERMISSION_GRANTED) {
2664 pw.println("Permission Denial: can't dump ConnectivityService " +
2665 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2666 Binder.getCallingUid());
2670 // TODO: add locking to get atomic snapshot
2672 for (int i = 0; i < mNetTrackers.length; i++) {
2673 final NetworkStateTracker nst = mNetTrackers[i];
2675 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2676 pw.increaseIndent();
2677 if (nst.getNetworkInfo().isConnected()) {
2678 pw.println("Active network: " + nst.getNetworkInfo().
2681 pw.println(nst.getNetworkInfo());
2682 pw.println(nst.getLinkProperties());
2685 pw.decreaseIndent();
2689 pw.println("Network Requester Pids:");
2690 pw.increaseIndent();
2691 for (int net : mPriorityList) {
2692 String pidString = net + ": ";
2693 for (Integer pid : mNetRequestersPids[net]) {
2694 pidString = pidString + pid.toString() + ", ";
2696 pw.println(pidString);
2699 pw.decreaseIndent();
2701 pw.println("FeatureUsers:");
2702 pw.increaseIndent();
2703 for (Object requester : mFeatureUsers) {
2704 pw.println(requester.toString());
2707 pw.decreaseIndent();
2709 synchronized (this) {
2710 pw.println("NetworkTranstionWakeLock is currently " +
2711 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2712 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2716 mTethering.dump(fd, pw, args);
2718 if (mInetLog != null) {
2720 pw.println("Inet condition reports:");
2721 pw.increaseIndent();
2722 for(int i = 0; i < mInetLog.size(); i++) {
2723 pw.println(mInetLog.get(i));
2725 pw.decreaseIndent();
2729 // must be stateless - things change under us.
2730 private class NetworkStateTrackerHandler extends Handler {
2731 public NetworkStateTrackerHandler(Looper looper) {
2736 public void handleMessage(Message msg) {
2739 case NetworkStateTracker.EVENT_STATE_CHANGED:
2740 info = (NetworkInfo) msg.obj;
2741 int type = info.getType();
2742 NetworkInfo.State state = info.getState();
2744 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2745 (state == NetworkInfo.State.DISCONNECTED)) {
2746 log("ConnectivityChange for " +
2747 info.getTypeName() + ": " +
2748 state + "/" + info.getDetailedState());
2751 // After booting we'll check once for mobile provisioning
2752 // if we've provisioned by and connected.
2753 if (!mFirstProvisioningCheckStarted
2754 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2755 Settings.Global.DEVICE_PROVISIONED, 0))
2756 && (state == NetworkInfo.State.CONNECTED)) {
2757 log("check provisioning after booting");
2758 mFirstProvisioningCheckStarted = true;
2759 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2762 EventLogTags.writeConnectivityStateChanged(
2763 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2765 if (info.getDetailedState() ==
2766 NetworkInfo.DetailedState.FAILED) {
2767 handleConnectionFailure(info);
2768 } else if (info.getDetailedState() ==
2769 DetailedState.CAPTIVE_PORTAL_CHECK) {
2770 handleCaptivePortalTrackerCheck(info);
2771 } else if (state == NetworkInfo.State.DISCONNECTED) {
2772 handleDisconnect(info);
2773 } else if (state == NetworkInfo.State.SUSPENDED) {
2774 // TODO: need to think this over.
2775 // the logic here is, handle SUSPENDED the same as
2776 // DISCONNECTED. The only difference being we are
2777 // broadcasting an intent with NetworkInfo that's
2778 // suspended. This allows the applications an
2779 // opportunity to handle DISCONNECTED and SUSPENDED
2780 // differently, or not.
2781 handleDisconnect(info);
2782 } else if (state == NetworkInfo.State.CONNECTED) {
2783 handleConnect(info);
2785 if (mLockdownTracker != null) {
2786 mLockdownTracker.onNetworkInfoChanged(info);
2789 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2790 info = (NetworkInfo) msg.obj;
2791 // TODO: Temporary allowing network configuration
2792 // change not resetting sockets.
2794 handleConnectivityChange(info.getType(), false);
2796 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2797 info = (NetworkInfo) msg.obj;
2798 type = info.getType();
2799 updateNetworkSettings(mNetTrackers[type]);
2805 private class InternalHandler extends Handler {
2806 public InternalHandler(Looper looper) {
2811 public void handleMessage(Message msg) {
2814 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2815 String causedBy = null;
2816 synchronized (ConnectivityService.this) {
2817 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2818 mNetTransitionWakeLock.isHeld()) {
2819 mNetTransitionWakeLock.release();
2820 causedBy = mNetTransitionWakeLockCausedBy;
2823 if (causedBy != null) {
2824 log("NetTransition Wakelock for " + causedBy + " released by timeout");
2827 case EVENT_RESTORE_DEFAULT_NETWORK:
2828 FeatureUser u = (FeatureUser)msg.obj;
2831 case EVENT_INET_CONDITION_CHANGE:
2833 int netType = msg.arg1;
2834 int condition = msg.arg2;
2835 handleInetConditionChange(netType, condition);
2838 case EVENT_INET_CONDITION_HOLD_END:
2840 int netType = msg.arg1;
2841 int sequence = msg.arg2;
2842 handleInetConditionHoldEnd(netType, sequence);
2845 case EVENT_SET_NETWORK_PREFERENCE:
2847 int preference = msg.arg1;
2848 handleSetNetworkPreference(preference);
2851 case EVENT_SET_MOBILE_DATA:
2853 boolean enabled = (msg.arg1 == ENABLED);
2854 handleSetMobileData(enabled);
2857 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2859 handleDeprecatedGlobalHttpProxy();
2862 case EVENT_SET_DEPENDENCY_MET:
2864 boolean met = (msg.arg1 == ENABLED);
2865 handleSetDependencyMet(msg.arg2, met);
2868 case EVENT_RESTORE_DNS:
2870 if (mActiveDefaultNetwork != -1) {
2871 handleDnsConfigurationChange(mActiveDefaultNetwork);
2875 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2877 Intent intent = (Intent)msg.obj;
2878 sendStickyBroadcast(intent);
2881 case EVENT_SET_POLICY_DATA_ENABLE: {
2882 final int networkType = msg.arg1;
2883 final boolean enabled = msg.arg2 == ENABLED;
2884 handleSetPolicyDataEnable(networkType, enabled);
2887 case EVENT_VPN_STATE_CHANGED: {
2888 if (mLockdownTracker != null) {
2889 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2893 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2894 int tag = mEnableFailFastMobileDataTag.get();
2895 if (msg.arg1 == tag) {
2896 MobileDataStateTracker mobileDst =
2897 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2898 if (mobileDst != null) {
2899 mobileDst.setEnableFailFastMobileData(msg.arg2);
2902 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2903 + " != tag:" + tag);
2910 // javadoc from interface
2911 public int tether(String iface) {
2912 enforceTetherChangePermission();
2914 if (isTetheringSupported()) {
2915 return mTethering.tether(iface);
2917 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2921 // javadoc from interface
2922 public int untether(String iface) {
2923 enforceTetherChangePermission();
2925 if (isTetheringSupported()) {
2926 return mTethering.untether(iface);
2928 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2932 // javadoc from interface
2933 public int getLastTetherError(String iface) {
2934 enforceTetherAccessPermission();
2936 if (isTetheringSupported()) {
2937 return mTethering.getLastTetherError(iface);
2939 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2943 // TODO - proper iface API for selection by property, inspection, etc
2944 public String[] getTetherableUsbRegexs() {
2945 enforceTetherAccessPermission();
2946 if (isTetheringSupported()) {
2947 return mTethering.getTetherableUsbRegexs();
2949 return new String[0];
2953 public String[] getTetherableWifiRegexs() {
2954 enforceTetherAccessPermission();
2955 if (isTetheringSupported()) {
2956 return mTethering.getTetherableWifiRegexs();
2958 return new String[0];
2962 public String[] getTetherableBluetoothRegexs() {
2963 enforceTetherAccessPermission();
2964 if (isTetheringSupported()) {
2965 return mTethering.getTetherableBluetoothRegexs();
2967 return new String[0];
2971 public int setUsbTethering(boolean enable) {
2972 enforceTetherChangePermission();
2973 if (isTetheringSupported()) {
2974 return mTethering.setUsbTethering(enable);
2976 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2980 // TODO - move iface listing, queries, etc to new module
2981 // javadoc from interface
2982 public String[] getTetherableIfaces() {
2983 enforceTetherAccessPermission();
2984 return mTethering.getTetherableIfaces();
2987 public String[] getTetheredIfaces() {
2988 enforceTetherAccessPermission();
2989 return mTethering.getTetheredIfaces();
2993 public String[] getTetheredIfacePairs() {
2994 enforceTetherAccessPermission();
2995 return mTethering.getTetheredIfacePairs();
2998 public String[] getTetheringErroredIfaces() {
2999 enforceTetherAccessPermission();
3000 return mTethering.getErroredIfaces();
3003 // if ro.tether.denied = true we default to no tethering
3004 // gservices could set the secure setting to 1 though to enable it on a build where it
3005 // had previously been turned off.
3006 public boolean isTetheringSupported() {
3007 enforceTetherAccessPermission();
3008 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3009 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3010 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3011 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3012 mTethering.getTetherableWifiRegexs().length != 0 ||
3013 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3014 mTethering.getUpstreamIfaceTypes().length != 0);
3017 // An API NetworkStateTrackers can call when they lose their network.
3018 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3019 // whichever happens first. The timer is started by the first caller and not
3020 // restarted by subsequent callers.
3021 public void requestNetworkTransitionWakelock(String forWhom) {
3022 enforceConnectivityInternalPermission();
3023 synchronized (this) {
3024 if (mNetTransitionWakeLock.isHeld()) return;
3025 mNetTransitionWakeLockSerialNumber++;
3026 mNetTransitionWakeLock.acquire();
3027 mNetTransitionWakeLockCausedBy = forWhom;
3029 mHandler.sendMessageDelayed(mHandler.obtainMessage(
3030 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3031 mNetTransitionWakeLockSerialNumber, 0),
3032 mNetTransitionWakeLockTimeout);
3036 // 100 percent is full good, 0 is full bad.
3037 public void reportInetCondition(int networkType, int percentage) {
3038 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3039 mContext.enforceCallingOrSelfPermission(
3040 android.Manifest.permission.STATUS_BAR,
3041 "ConnectivityService");
3044 int pid = getCallingPid();
3045 int uid = getCallingUid();
3046 String s = pid + "(" + uid + ") reports inet is " +
3047 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3048 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3050 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3054 mHandler.sendMessage(mHandler.obtainMessage(
3055 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3058 private void handleInetConditionChange(int netType, int condition) {
3059 if (mActiveDefaultNetwork == -1) {
3060 if (DBG) log("handleInetConditionChange: no active default network - ignore");
3063 if (mActiveDefaultNetwork != netType) {
3064 if (DBG) log("handleInetConditionChange: net=" + netType +
3065 " != default=" + mActiveDefaultNetwork + " - ignore");
3069 log("handleInetConditionChange: net=" +
3070 netType + ", condition=" + condition +
3071 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3073 mDefaultInetCondition = condition;
3075 if (mInetConditionChangeInFlight == false) {
3076 if (VDBG) log("handleInetConditionChange: starting a change hold");
3077 // setup a new hold to debounce this
3078 if (mDefaultInetCondition > 50) {
3079 delay = Settings.Global.getInt(mContext.getContentResolver(),
3080 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3082 delay = Settings.Global.getInt(mContext.getContentResolver(),
3083 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3085 mInetConditionChangeInFlight = true;
3086 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3087 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3089 // we've set the new condition, when this hold ends that will get picked up
3090 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3094 private void handleInetConditionHoldEnd(int netType, int sequence) {
3096 log("handleInetConditionHoldEnd: net=" + netType +
3097 ", condition=" + mDefaultInetCondition +
3098 ", published condition=" + mDefaultInetConditionPublished);
3100 mInetConditionChangeInFlight = false;
3102 if (mActiveDefaultNetwork == -1) {
3103 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3106 if (mDefaultConnectionSequence != sequence) {
3107 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3110 // TODO: Figure out why this optimization sometimes causes a
3111 // change in mDefaultInetCondition to be missed and the
3112 // UI to not be updated.
3113 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3114 // if (DBG) log("no change in condition - aborting");
3117 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3118 if (networkInfo.isConnected() == false) {
3119 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3122 mDefaultInetConditionPublished = mDefaultInetCondition;
3123 sendInetConditionBroadcast(networkInfo);
3127 public ProxyProperties getProxy() {
3128 // this information is already available as a world read/writable jvm property
3129 // so this API change wouldn't have a benifit. It also breaks the passing
3130 // of proxy info to all the JVMs.
3131 // enforceAccessPermission();
3132 synchronized (mProxyLock) {
3133 if (mGlobalProxy != null) return mGlobalProxy;
3134 return (mDefaultProxyDisabled ? null : mDefaultProxy);
3138 public void setGlobalProxy(ProxyProperties proxyProperties) {
3139 enforceConnectivityInternalPermission();
3140 synchronized (mProxyLock) {
3141 if (proxyProperties == mGlobalProxy) return;
3142 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3143 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3147 String exclList = "";
3148 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3149 mGlobalProxy = new ProxyProperties(proxyProperties);
3150 host = mGlobalProxy.getHost();
3151 port = mGlobalProxy.getPort();
3152 exclList = mGlobalProxy.getExclusionList();
3154 mGlobalProxy = null;
3156 ContentResolver res = mContext.getContentResolver();
3157 final long token = Binder.clearCallingIdentity();
3159 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3160 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3161 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3164 Binder.restoreCallingIdentity(token);
3168 if (mGlobalProxy == null) {
3169 proxyProperties = mDefaultProxy;
3171 sendProxyBroadcast(proxyProperties);
3174 private void loadGlobalProxy() {
3175 ContentResolver res = mContext.getContentResolver();
3176 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3177 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3178 String exclList = Settings.Global.getString(res,
3179 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3180 if (!TextUtils.isEmpty(host)) {
3181 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3182 synchronized (mProxyLock) {
3183 mGlobalProxy = proxyProperties;
3188 public ProxyProperties getGlobalProxy() {
3189 // this information is already available as a world read/writable jvm property
3190 // so this API change wouldn't have a benifit. It also breaks the passing
3191 // of proxy info to all the JVMs.
3192 // enforceAccessPermission();
3193 synchronized (mProxyLock) {
3194 return mGlobalProxy;
3198 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3199 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3202 synchronized (mProxyLock) {
3203 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3204 if (mDefaultProxy == proxy) return; // catches repeated nulls
3205 mDefaultProxy = proxy;
3207 if (mGlobalProxy != null) return;
3208 if (!mDefaultProxyDisabled) {
3209 sendProxyBroadcast(proxy);
3214 private void handleDeprecatedGlobalHttpProxy() {
3215 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3216 Settings.Global.HTTP_PROXY);
3217 if (!TextUtils.isEmpty(proxy)) {
3218 String data[] = proxy.split(":");
3219 String proxyHost = data[0];
3220 int proxyPort = 8080;
3221 if (data.length > 1) {
3223 proxyPort = Integer.parseInt(data[1]);
3224 } catch (NumberFormatException e) {
3228 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3233 private void sendProxyBroadcast(ProxyProperties proxy) {
3234 if (proxy == null) proxy = new ProxyProperties("", 0, "");
3235 if (DBG) log("sending Proxy Broadcast for " + proxy);
3236 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3237 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3238 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3239 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3240 final long ident = Binder.clearCallingIdentity();
3242 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3244 Binder.restoreCallingIdentity(ident);
3248 private static class SettingsObserver extends ContentObserver {
3250 private Handler mHandler;
3251 SettingsObserver(Handler handler, int what) {
3257 void observe(Context context) {
3258 ContentResolver resolver = context.getContentResolver();
3259 resolver.registerContentObserver(Settings.Global.getUriFor(
3260 Settings.Global.HTTP_PROXY), false, this);
3264 public void onChange(boolean selfChange) {
3265 mHandler.obtainMessage(mWhat).sendToTarget();
3269 private static void log(String s) {
3273 private static void loge(String s) {
3277 int convertFeatureToNetworkType(int networkType, String feature) {
3278 int usedNetworkType = networkType;
3280 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3281 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3282 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3283 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3284 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3285 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3286 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3287 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3288 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3289 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3290 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3291 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3292 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3293 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3294 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3295 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3297 Slog.e(TAG, "Can't match any mobile netTracker!");
3299 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3300 if (TextUtils.equals(feature, "p2p")) {
3301 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3303 Slog.e(TAG, "Can't match any wifi netTracker!");
3306 Slog.e(TAG, "Unexpected network type");
3308 return usedNetworkType;
3311 private static <T> T checkNotNull(T value, String message) {
3312 if (value == null) {
3313 throw new NullPointerException(message);
3319 * Protect a socket from VPN routing rules. This method is used by
3320 * VpnBuilder and not available in ConnectivityManager. Permissions
3321 * are checked in Vpn class.
3325 public boolean protectVpn(ParcelFileDescriptor socket) {
3326 throwIfLockdownEnabled();
3328 int type = mActiveDefaultNetwork;
3329 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3330 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3333 } catch (Exception e) {
3338 } catch (Exception e) {
3346 * Prepare for a VPN application. This method is used by VpnDialogs
3347 * and not available in ConnectivityManager. Permissions are checked
3352 public boolean prepareVpn(String oldPackage, String newPackage) {
3353 throwIfLockdownEnabled();
3354 return mVpn.prepare(oldPackage, newPackage);
3358 * Configure a TUN interface and return its file descriptor. Parameters
3359 * are encoded and opaque to this class. This method is used by VpnBuilder
3360 * and not available in ConnectivityManager. Permissions are checked in
3365 public ParcelFileDescriptor establishVpn(VpnConfig config) {
3366 throwIfLockdownEnabled();
3367 return mVpn.establish(config);
3371 * Start legacy VPN, controlling native daemons as needed. Creates a
3372 * secondary thread to perform connection work, returning quickly.
3375 public void startLegacyVpn(VpnProfile profile) {
3376 throwIfLockdownEnabled();
3377 final LinkProperties egress = getActiveLinkProperties();
3378 if (egress == null) {
3379 throw new IllegalStateException("Missing active network connection");
3381 mVpn.startLegacyVpn(profile, mKeyStore, egress);
3385 * Return the information of the ongoing legacy VPN. This method is used
3386 * by VpnSettings and not available in ConnectivityManager. Permissions
3387 * are checked in Vpn class.
3391 public LegacyVpnInfo getLegacyVpnInfo() {
3392 throwIfLockdownEnabled();
3393 return mVpn.getLegacyVpnInfo();
3397 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3398 * through NetworkStateTracker since it works differently. For example, it
3399 * needs to override DNS servers but never takes the default routes. It
3400 * relies on another data network, and it could keep existing connections
3401 * alive after reconnecting, switching between networks, or even resuming
3402 * from deep sleep. Calls from applications should be done synchronously
3403 * to avoid race conditions. As these are all hidden APIs, refactoring can
3404 * be done whenever a better abstraction is developed.
3406 public class VpnCallback {
3407 private VpnCallback() {
3410 public void onStateChanged(NetworkInfo info) {
3411 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3414 public void override(List<String> dnsServers, List<String> searchDomains) {
3415 if (dnsServers == null) {
3420 // Convert DNS servers into addresses.
3421 List<InetAddress> addresses = new ArrayList<InetAddress>();
3422 for (String address : dnsServers) {
3423 // Double check the addresses and remove invalid ones.
3425 addresses.add(InetAddress.parseNumericAddress(address));
3426 } catch (Exception e) {
3430 if (addresses.isEmpty()) {
3435 // Concatenate search domains into a string.
3436 StringBuilder buffer = new StringBuilder();
3437 if (searchDomains != null) {
3438 for (String domain : searchDomains) {
3439 buffer.append(domain).append(' ');
3442 String domains = buffer.toString().trim();
3444 // Apply DNS changes.
3445 synchronized (mDnsLock) {
3446 updateDnsLocked("VPN", "VPN", addresses, domains);
3447 mDnsOverridden = true;
3450 // Temporarily disable the default proxy (not global).
3451 synchronized (mProxyLock) {
3452 mDefaultProxyDisabled = true;
3453 if (mGlobalProxy == null && mDefaultProxy != null) {
3454 sendProxyBroadcast(null);
3458 // TODO: support proxy per network.
3461 public void restore() {
3462 synchronized (mDnsLock) {
3463 if (mDnsOverridden) {
3464 mDnsOverridden = false;
3465 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3468 synchronized (mProxyLock) {
3469 mDefaultProxyDisabled = false;
3470 if (mGlobalProxy == null && mDefaultProxy != null) {
3471 sendProxyBroadcast(mDefaultProxy);
3478 public boolean updateLockdownVpn() {
3479 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3480 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3484 // Tear down existing lockdown if profile was removed
3485 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3486 if (mLockdownEnabled) {
3487 if (!mKeyStore.isUnlocked()) {
3488 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3492 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3493 final VpnProfile profile = VpnProfile.decode(
3494 profileName, mKeyStore.get(Credentials.VPN + profileName));
3495 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3497 setLockdownTracker(null);
3504 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3505 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3507 private void setLockdownTracker(LockdownVpnTracker tracker) {
3508 // Shutdown any existing tracker
3509 final LockdownVpnTracker existing = mLockdownTracker;
3510 mLockdownTracker = null;
3511 if (existing != null) {
3512 existing.shutdown();
3516 if (tracker != null) {
3517 mNetd.setFirewallEnabled(true);
3518 mNetd.setFirewallInterfaceRule("lo", true);
3519 mLockdownTracker = tracker;
3520 mLockdownTracker.init();
3522 mNetd.setFirewallEnabled(false);
3524 } catch (RemoteException e) {
3525 // ignored; NMS lives inside system_server
3529 private void throwIfLockdownEnabled() {
3530 if (mLockdownEnabled) {
3531 throw new IllegalStateException("Unavailable in lockdown mode");
3535 public void supplyMessenger(int networkType, Messenger messenger) {
3536 enforceConnectivityInternalPermission();
3538 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3539 mNetTrackers[networkType].supplyMessenger(messenger);
3543 public int findConnectionTypeForIface(String iface) {
3544 enforceConnectivityInternalPermission();
3546 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3547 for (NetworkStateTracker tracker : mNetTrackers) {
3548 if (tracker != null) {
3549 LinkProperties lp = tracker.getLinkProperties();
3550 if (lp != null && iface.equals(lp.getInterfaceName())) {
3551 return tracker.getNetworkInfo().getType();
3555 return ConnectivityManager.TYPE_NONE;
3559 * Have mobile data fail fast if enabled.
3561 * @param enabled DctConstants.ENABLED/DISABLED
3563 private void setEnableFailFastMobileData(int enabled) {
3566 if (enabled == DctConstants.ENABLED) {
3567 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3569 tag = mEnableFailFastMobileDataTag.get();
3571 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3575 private boolean isMobileDataStateTrackerReady() {
3576 MobileDataStateTracker mdst =
3577 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3578 return (mdst != null) && (mdst.isReady());
3582 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3583 final ResultReceiver resultReceiver) {
3584 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3585 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3586 + " resultReceiver=" + resultReceiver);
3587 enforceChangePermission();
3589 mFirstProvisioningCheckStarted = true;
3591 int timeOutMs = suggestedTimeOutMs;
3592 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3593 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3596 // Check that mobile networks are supported
3597 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3598 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3599 log("checkMobileProvisioning: X no mobile network");
3600 if (resultReceiver != null) {
3601 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3606 final long token = Binder.clearCallingIdentity();
3608 CheckMp checkMp = new CheckMp(mContext, this);
3609 CheckMp.CallBack cb = new CheckMp.CallBack() {
3611 void onComplete(Integer result) {
3612 log("CheckMp.onComplete: result=" + result);
3613 if (resultReceiver != null) {
3614 log("CheckMp.onComplete: send result");
3615 resultReceiver.send(result, null);
3618 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3620 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3621 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3622 log("CheckMp.onComplete: ignore, connected or no connection");
3625 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3626 log("CheckMp.onComplete: warm sim");
3627 String url = getMobileProvisioningUrl();
3628 if (TextUtils.isEmpty(url)) {
3629 url = getMobileRedirectedProvisioningUrl();
3631 if (TextUtils.isEmpty(url) == false) {
3632 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3633 setNotificationVisible(true, ni, url);
3635 log("CheckMp.onComplete: warm sim (redirected), no url");
3639 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3640 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3641 String url = getMobileProvisioningUrl();
3642 if (TextUtils.isEmpty(url) == false) {
3643 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3644 setNotificationVisible(true, ni, url);
3646 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3651 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3657 CheckMp.Params params =
3658 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3659 log("checkMobileProvisioning: params=" + params);
3660 setNotificationVisible(false, null, null);
3661 checkMp.execute(params);
3663 Binder.restoreCallingIdentity(token);
3664 log("checkMobileProvisioning: X");
3669 static class CheckMp extends
3670 AsyncTask<CheckMp.Params, Void, Integer> {
3671 private static final String CHECKMP_TAG = "CheckMp";
3672 public static final int MAX_TIMEOUT_MS = 60000;
3673 private static final int SOCKET_TIMEOUT_MS = 5000;
3674 private Context mContext;
3675 private ConnectivityService mCs;
3676 private TelephonyManager mTm;
3677 private Params mParams;
3680 * Parameters for AsyncTask.execute
3682 static class Params {
3683 private String mUrl;
3684 private long mTimeOutMs;
3685 private CallBack mCb;
3687 Params(String url, long timeOutMs, CallBack cb) {
3689 mTimeOutMs = timeOutMs;
3694 public String toString() {
3695 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3700 * The call back object passed in Params. onComplete will be called
3701 * on the main thread.
3703 abstract static class CallBack {
3704 // Called on the main thread.
3705 abstract void onComplete(Integer result);
3708 public CheckMp(Context context, ConnectivityService cs) {
3712 // Setup access to TelephonyService we'll be using.
3713 mTm = (TelephonyManager) mContext.getSystemService(
3714 Context.TELEPHONY_SERVICE);
3718 * Get the default url to use for the test.
3720 public String getDefaultUrl() {
3721 // See http://go/clientsdns for usage approval
3722 String server = Settings.Global.getString(mContext.getContentResolver(),
3723 Settings.Global.CAPTIVE_PORTAL_SERVER);
3724 if (server == null) {
3725 server = "clients3.google.com";
3727 return "http://" + server + "/generate_204";
3731 * Detect if its possible to connect to the http url. DNS based detection techniques
3732 * do not work at all hotspots. The best way to check is to perform a request to
3733 * a known address that fetches the data we expect.
3735 private synchronized Integer isMobileOk(Params params) {
3736 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3737 Uri orgUri = Uri.parse(params.mUrl);
3738 Random rand = new Random();
3741 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3742 log("isMobileOk: not mobile capable");
3743 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3748 // Continue trying to connect until time has run out
3749 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3751 if (!mCs.isMobileDataStateTrackerReady()) {
3752 // Wait for MobileDataStateTracker to be ready.
3753 if (DBG) log("isMobileOk: mdst is not ready");
3754 while(SystemClock.elapsedRealtime() < endTime) {
3755 if (mCs.isMobileDataStateTrackerReady()) {
3756 // Enable fail fast as we'll do retries here and use a
3757 // hipri connection so the default connection stays active.
3758 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3759 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3766 log("isMobileOk: start hipri url=" + params.mUrl);
3768 // First wait until we can start using hipri
3769 Binder binder = new Binder();
3770 while(SystemClock.elapsedRealtime() < endTime) {
3771 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3772 Phone.FEATURE_ENABLE_HIPRI, binder);
3773 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3774 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3775 log("isMobileOk: hipri started");
3778 if (VDBG) log("isMobileOk: hipri not started yet");
3779 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3783 // Continue trying to connect until time has run out
3784 while(SystemClock.elapsedRealtime() < endTime) {
3786 // Wait for hipri to connect.
3787 // TODO: Don't poll and handle situation where hipri fails
3788 // because default is retrying. See b/9569540
3789 NetworkInfo.State state = mCs
3790 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3791 if (state != NetworkInfo.State.CONNECTED) {
3793 log("isMobileOk: not connected ni=" +
3794 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3797 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3801 // Get of the addresses associated with the url host. We need to use the
3802 // address otherwise HttpURLConnection object will use the name to get
3803 // the addresses and is will try every address but that will bypass the
3804 // route to host we setup and the connection could succeed as the default
3805 // interface might be connected to the internet via wifi or other interface.
3806 InetAddress[] addresses;
3808 addresses = InetAddress.getAllByName(orgUri.getHost());
3809 } catch (UnknownHostException e) {
3810 log("isMobileOk: UnknownHostException");
3811 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3814 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3816 // Get the type of addresses supported by this link
3817 LinkProperties lp = mCs.getLinkProperties(
3818 ConnectivityManager.TYPE_MOBILE_HIPRI);
3819 boolean linkHasIpv4 = hasIPv4Address(lp);
3820 boolean linkHasIpv6 = hasIPv6Address(lp);
3821 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3822 + " linkHasIpv6=" + linkHasIpv6);
3824 // Loop through at most 3 valid addresses or all of the address or until
3825 // we run out of time
3826 int loops = Math.min(3, addresses.length);
3827 for(int validAddr=0, addrTried=0;
3828 (validAddr < loops) && (addrTried < addresses.length)
3829 && (SystemClock.elapsedRealtime() < endTime);
3832 // Choose the address at random but make sure its type is supported
3833 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3834 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3835 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3836 // Valid address, so use it
3839 // Invalid address so try next address
3843 // Make a route to host so we check the specific interface.
3844 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3845 hostAddr.getAddress())) {
3846 // Wait a short time to be sure the route is established ??
3848 + " wait to establish route to hostAddr=" + hostAddr);
3852 + " could not establish route to hostAddr=" + hostAddr);
3856 // Rewrite the url to have numeric address to use the specific route.
3857 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3858 // is used which is useless in this case.
3859 URL newUrl = new URL(orgUri.getScheme() + "://"
3860 + hostAddr.getHostAddress() + orgUri.getPath());
3861 log("isMobileOk: newUrl=" + newUrl);
3863 HttpURLConnection urlConn = null;
3865 // Open the connection set the request header and get the response
3866 urlConn = (HttpURLConnection) newUrl.openConnection(
3867 java.net.Proxy.NO_PROXY);
3868 urlConn.setInstanceFollowRedirects(false);
3869 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3870 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3871 urlConn.setUseCaches(false);
3872 urlConn.setAllowUserInteraction(false);
3873 urlConn.setRequestProperty("Connection", "close");
3874 int responseCode = urlConn.getResponseCode();
3875 if (responseCode == 204) {
3876 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3878 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3880 log("isMobileOk: connected responseCode=" + responseCode);
3881 urlConn.disconnect();
3884 } catch (Exception e) {
3885 log("isMobileOk: HttpURLConnection Exception e=" + e);
3886 if (urlConn != null) {
3887 urlConn.disconnect();
3892 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3893 log("isMobileOk: loops|timed out");
3895 } catch (Exception e) {
3896 log("isMobileOk: Exception e=" + e);
3900 log("isMobileOk: timed out");
3902 log("isMobileOk: F stop hipri");
3903 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3904 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3905 Phone.FEATURE_ENABLE_HIPRI);
3906 log("isMobileOk: X result=" + result);
3912 protected Integer doInBackground(Params... params) {
3913 return isMobileOk(params[0]);
3917 protected void onPostExecute(Integer result) {
3918 log("onPostExecute: result=" + result);
3919 if ((mParams != null) && (mParams.mCb != null)) {
3920 mParams.mCb.onComplete(result);
3924 private String inetAddressesToString(InetAddress[] addresses) {
3925 StringBuffer sb = new StringBuffer();
3926 boolean firstTime = true;
3927 for(InetAddress addr : addresses) {
3935 return sb.toString();
3938 private void printNetworkInfo() {
3939 boolean hasIccCard = mTm.hasIccCard();
3940 int simState = mTm.getSimState();
3941 log("hasIccCard=" + hasIccCard
3942 + " simState=" + simState);
3943 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3945 log("ni.length=" + ni.length);
3946 for (NetworkInfo netInfo: ni) {
3947 log("netInfo=" + netInfo.toString());
3950 log("no network info ni=null");
3955 * Sleep for a few seconds then return.
3958 private static void sleep(int seconds) {
3960 Thread.sleep(seconds * 1000);
3961 } catch (InterruptedException e) {
3962 e.printStackTrace();
3966 public boolean hasIPv4Address(LinkProperties lp) {
3967 return lp.hasIPv4Address();
3970 // Not implemented in LinkProperties, do it here.
3971 public boolean hasIPv6Address(LinkProperties lp) {
3972 for (LinkAddress address : lp.getLinkAddresses()) {
3973 if (address.getAddress() instanceof Inet6Address) {
3980 private void log(String s) {
3981 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3985 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3987 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3988 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3990 Resources r = Resources.getSystem();
3991 NotificationManager notificationManager = (NotificationManager) mContext
3992 .getSystemService(Context.NOTIFICATION_SERVICE);
3996 CharSequence details;
3998 switch (networkInfo.getType()) {
3999 case ConnectivityManager.TYPE_WIFI:
4000 log("setNotificationVisible: TYPE_WIFI");
4001 title = r.getString(R.string.wifi_available_sign_in, 0);
4002 details = r.getString(R.string.network_available_sign_in_detailed,
4003 networkInfo.getExtraInfo());
4004 icon = R.drawable.stat_notify_wifi_in_range;
4006 case ConnectivityManager.TYPE_MOBILE:
4007 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4008 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4009 title = r.getString(R.string.network_available_sign_in, 0);
4010 // TODO: Change this to pull from NetworkInfo once a printable
4011 // name has been added to it
4012 details = mTelephonyManager.getNetworkOperatorName();
4013 icon = R.drawable.stat_notify_rssi_in_range;
4016 log("setNotificationVisible: other type=" + networkInfo.getType());
4017 title = r.getString(R.string.network_available_sign_in, 0);
4018 details = r.getString(R.string.network_available_sign_in_detailed,
4019 networkInfo.getExtraInfo());
4020 icon = R.drawable.stat_notify_rssi_in_range;
4024 Notification notification = new Notification();
4025 notification.when = 0;
4026 notification.icon = icon;
4027 notification.flags = Notification.FLAG_AUTO_CANCEL;
4028 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4029 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4030 Intent.FLAG_ACTIVITY_NEW_TASK);
4031 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4032 notification.tickerText = title;
4033 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4035 log("setNotificaitionVisible: notify notificaiton=" + notification);
4036 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4038 log("setNotificaitionVisible: cancel");
4039 notificationManager.cancel(NOTIFICATION_ID, 1);
4041 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4044 /** Location to an updatable file listing carrier provisioning urls.
4047 * <?xml version="1.0" encoding="utf-8"?>
4048 * <provisioningUrls>
4049 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
4050 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4051 * </provisioningUrls>
4053 private static final String PROVISIONING_URL_PATH =
4054 "/data/misc/radio/provisioning_urls.xml";
4055 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4057 /** XML tag for root element. */
4058 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4059 /** XML tag for individual url */
4060 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4061 /** XML tag for redirected url */
4062 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4063 /** XML attribute for mcc */
4064 private static final String ATTR_MCC = "mcc";
4065 /** XML attribute for mnc */
4066 private static final String ATTR_MNC = "mnc";
4068 private static final int REDIRECTED_PROVISIONING = 1;
4069 private static final int PROVISIONING = 2;
4071 private String getProvisioningUrlBaseFromFile(int type) {
4072 FileReader fileReader = null;
4073 XmlPullParser parser = null;
4074 Configuration config = mContext.getResources().getConfiguration();
4079 tagType = TAG_PROVISIONING_URL;
4081 case REDIRECTED_PROVISIONING:
4082 tagType = TAG_REDIRECTED_URL;
4085 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4090 fileReader = new FileReader(mProvisioningUrlFile);
4091 parser = Xml.newPullParser();
4092 parser.setInput(fileReader);
4093 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4096 XmlUtils.nextElement(parser);
4098 String element = parser.getName();
4099 if (element == null) break;
4101 if (element.equals(tagType)) {
4102 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4104 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4105 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4106 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4108 if (parser.getEventType() == XmlPullParser.TEXT) {
4109 return parser.getText();
4113 } catch (NumberFormatException e) {
4114 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4119 } catch (FileNotFoundException e) {
4120 loge("Carrier Provisioning Urls file not found");
4121 } catch (XmlPullParserException e) {
4122 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4123 } catch (IOException e) {
4124 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4126 if (fileReader != null) {
4129 } catch (IOException e) {}
4136 public String getMobileRedirectedProvisioningUrl() {
4137 enforceConnectivityInternalPermission();
4138 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4139 if (TextUtils.isEmpty(url)) {
4140 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4146 public String getMobileProvisioningUrl() {
4147 enforceConnectivityInternalPermission();
4148 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4149 if (TextUtils.isEmpty(url)) {
4150 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4151 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
4153 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
4155 // populate the iccid, imei and phone number in the provisioning url.
4156 if (!TextUtils.isEmpty(url)) {
4157 String phoneNumber = mTelephonyManager.getLine1Number();
4158 if (TextUtils.isEmpty(phoneNumber)) {
4159 phoneNumber = "0000000000";
4161 url = String.format(url,
4162 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4163 mTelephonyManager.getDeviceId() /* IMEI */,
4164 phoneNumber /* Phone numer */);