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 thisNet.captivePortalCheckComplete();
2176 public void captivePortalCheckComplete(NetworkInfo info) {
2177 enforceConnectivityInternalPermission();
2178 mNetTrackers[info.getType()].captivePortalCheckComplete();
2182 * Setup data activity tracking for the given network interface.
2184 * Every {@code setupDataActivityTracking} should be paired with a
2185 * {@link removeDataActivityTracking} for cleanup.
2187 private void setupDataActivityTracking(int type) {
2188 final NetworkStateTracker thisNet = mNetTrackers[type];
2189 final String iface = thisNet.getLinkProperties().getInterfaceName();
2193 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2194 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2195 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2197 // Canonicalize mobile network type
2198 type = ConnectivityManager.TYPE_MOBILE;
2199 } else if (ConnectivityManager.TYPE_WIFI == type) {
2200 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2201 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2204 // do not track any other networks
2208 if (timeout > 0 && iface != null) {
2210 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2211 } catch (RemoteException e) {
2217 * Remove data activity tracking when network disconnects.
2219 private void removeDataActivityTracking(int type) {
2220 final NetworkStateTracker net = mNetTrackers[type];
2221 final String iface = net.getLinkProperties().getInterfaceName();
2223 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2224 ConnectivityManager.TYPE_WIFI == type)) {
2226 // the call fails silently if no idletimer setup for this interface
2227 mNetd.removeIdleTimer(iface);
2228 } catch (RemoteException e) {
2234 * After a change in the connectivity state of a network. We're mainly
2235 * concerned with making sure that the list of DNS servers is set up
2236 * according to which networks are connected, and ensuring that the
2237 * right routing table entries exist.
2239 private void handleConnectivityChange(int netType, boolean doReset) {
2240 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2243 * If a non-default network is enabled, add the host routes that
2244 * will allow it's DNS servers to be accessed.
2246 handleDnsConfigurationChange(netType);
2248 LinkProperties curLp = mCurrentLinkProperties[netType];
2249 LinkProperties newLp = null;
2251 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2252 newLp = mNetTrackers[netType].getLinkProperties();
2254 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2255 " doReset=" + doReset + " resetMask=" + resetMask +
2256 "\n curLp=" + curLp +
2257 "\n newLp=" + newLp);
2260 if (curLp != null) {
2261 if (curLp.isIdenticalInterfaceName(newLp)) {
2262 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2263 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2264 for (LinkAddress linkAddr : car.removed) {
2265 if (linkAddr.getAddress() instanceof Inet4Address) {
2266 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2268 if (linkAddr.getAddress() instanceof Inet6Address) {
2269 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2273 log("handleConnectivityChange: addresses changed" +
2274 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2279 log("handleConnectivityChange: address are the same reset per doReset" +
2280 " linkProperty[" + netType + "]:" +
2281 " resetMask=" + resetMask);
2285 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2287 log("handleConnectivityChange: interface not not equivalent reset both" +
2288 " linkProperty[" + netType + "]:" +
2289 " resetMask=" + resetMask);
2293 if (mNetConfigs[netType].isDefault()) {
2294 handleApplyDefaultProxy(newLp.getHttpProxy());
2298 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2299 " doReset=" + doReset + " resetMask=" + resetMask +
2300 "\n curLp=" + curLp +
2304 mCurrentLinkProperties[netType] = newLp;
2305 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2307 if (resetMask != 0 || resetDns) {
2308 if (curLp != null) {
2309 for (String iface : curLp.getAllInterfaceNames()) {
2310 if (TextUtils.isEmpty(iface) == false) {
2311 if (resetMask != 0) {
2312 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2313 NetworkUtils.resetConnections(iface, resetMask);
2315 // Tell VPN the interface is down. It is a temporary
2316 // but effective fix to make VPN aware of the change.
2317 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2318 mVpn.interfaceStatusChanged(iface, false);
2323 if (VDBG) log("resetting DNS cache for " + iface);
2325 mNetd.flushInterfaceDnsCache(iface);
2326 } catch (Exception e) {
2327 // never crash - catch them all
2328 if (DBG) loge("Exception resetting dns cache: " + e);
2332 loge("Can't reset connection for type "+netType);
2338 // Update 464xlat state.
2339 NetworkStateTracker tracker = mNetTrackers[netType];
2340 if (mClat.requiresClat(netType, tracker)) {
2341 // If the connection was previously using clat, but is not using it now, stop the clat
2342 // daemon. Normally, this happens automatically when the connection disconnects, but if
2343 // the disconnect is not reported, or if the connection's LinkProperties changed for
2344 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2345 // still be running. If it's not running, then stopping it is a no-op.
2346 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2349 // If the link requires clat to be running, then start the daemon now.
2350 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2351 mClat.startClat(tracker);
2357 // TODO: Temporary notifying upstread change to Tethering.
2359 /** Notify TetheringService if interface name has been changed. */
2360 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2361 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2362 if (isTetheringSupported()) {
2363 mTethering.handleTetherIfaceChange();
2369 * Add and remove routes using the old properties (null if not previously connected),
2370 * new properties (null if becoming disconnected). May even be double null, which
2372 * Uses isLinkDefault to determine if default routes should be set or conversely if
2373 * host routes should be set to the dns servers
2374 * returns a boolean indicating the routes changed
2376 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2377 boolean isLinkDefault) {
2378 Collection<RouteInfo> routesToAdd = null;
2379 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2380 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2381 if (curLp != null) {
2382 // check for the delta between the current set and the new
2383 routeDiff = curLp.compareRoutes(newLp);
2384 dnsDiff = curLp.compareDnses(newLp);
2385 } else if (newLp != null) {
2386 routeDiff.added = newLp.getAllRoutes();
2387 dnsDiff.added = newLp.getDnses();
2390 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2392 for (RouteInfo r : routeDiff.removed) {
2393 if (isLinkDefault || ! r.isDefaultRoute()) {
2394 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2396 if (isLinkDefault == false) {
2397 // remove from a secondary route table
2398 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2402 if (!isLinkDefault) {
2403 // handle DNS routes
2404 if (routesChanged) {
2405 // routes changed - remove all old dns entries and add new
2406 if (curLp != null) {
2407 for (InetAddress oldDns : curLp.getDnses()) {
2408 removeRouteToAddress(curLp, oldDns);
2411 if (newLp != null) {
2412 for (InetAddress newDns : newLp.getDnses()) {
2413 addRouteToAddress(newLp, newDns);
2417 // no change in routes, check for change in dns themselves
2418 for (InetAddress oldDns : dnsDiff.removed) {
2419 removeRouteToAddress(curLp, oldDns);
2421 for (InetAddress newDns : dnsDiff.added) {
2422 addRouteToAddress(newLp, newDns);
2427 for (RouteInfo r : routeDiff.added) {
2428 if (isLinkDefault || ! r.isDefaultRoute()) {
2429 addRoute(newLp, r, TO_DEFAULT_TABLE);
2431 // add to a secondary route table
2432 addRoute(newLp, r, TO_SECONDARY_TABLE);
2434 // many radios add a default route even when we don't want one.
2435 // remove the default route unless somebody else has asked for it
2436 String ifaceName = newLp.getInterfaceName();
2437 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2438 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2440 mNetd.removeRoute(ifaceName, r);
2441 } catch (Exception e) {
2442 // never crash - catch them all
2443 if (DBG) loge("Exception trying to remove a route: " + e);
2449 return routesChanged;
2454 * Reads the network specific TCP buffer sizes from SystemProperties
2455 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2458 private void updateNetworkSettings(NetworkStateTracker nt) {
2459 String key = nt.getTcpBufferSizesPropName();
2460 String bufferSizes = key == null ? null : SystemProperties.get(key);
2462 if (TextUtils.isEmpty(bufferSizes)) {
2463 if (VDBG) log(key + " not found in system properties. Using defaults");
2465 // Setting to default values so we won't be stuck to previous values
2466 key = "net.tcp.buffersize.default";
2467 bufferSizes = SystemProperties.get(key);
2470 // Set values in kernel
2471 if (bufferSizes.length() != 0) {
2473 log("Setting TCP values: [" + bufferSizes
2474 + "] which comes from [" + key + "]");
2476 setBufferSize(bufferSizes);
2481 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2482 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2484 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2485 * writeMin, writeInitial, writeMax"
2487 private void setBufferSize(String bufferSizes) {
2489 String[] values = bufferSizes.split(",");
2491 if (values.length == 6) {
2492 final String prefix = "/sys/kernel/ipv4/tcp_";
2493 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2494 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2495 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2496 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2497 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2498 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2500 loge("Invalid buffersize string: " + bufferSizes);
2502 } catch (IOException e) {
2503 loge("Can't set tcp buffer sizes:" + e);
2508 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2509 * on the highest priority active net which this process requested.
2510 * If there aren't any, clear it out
2512 private void reassessPidDns(int pid, boolean doBump)
2514 if (VDBG) log("reassessPidDns for pid " + pid);
2515 Integer myPid = new Integer(pid);
2516 for(int i : mPriorityList) {
2517 if (mNetConfigs[i].isDefault()) {
2520 NetworkStateTracker nt = mNetTrackers[i];
2521 if (nt.getNetworkInfo().isConnected() &&
2522 !nt.isTeardownRequested()) {
2523 LinkProperties p = nt.getLinkProperties();
2524 if (p == null) continue;
2525 if (mNetRequestersPids[i].contains(myPid)) {
2527 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2528 } catch (Exception e) {
2529 Slog.e(TAG, "exception reasseses pid dns: " + e);
2535 // nothing found - delete
2537 mNetd.clearDnsInterfaceForPid(pid);
2538 } catch (Exception e) {
2539 Slog.e(TAG, "exception clear interface from pid: " + e);
2543 private void flushVmDnsCache() {
2545 * Tell the VMs to toss their DNS caches
2547 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2548 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2550 * Connectivity events can happen before boot has completed ...
2552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2553 final long ident = Binder.clearCallingIdentity();
2555 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2557 Binder.restoreCallingIdentity(ident);
2561 // Caller must grab mDnsLock.
2562 private void updateDnsLocked(String network, String iface,
2563 Collection<InetAddress> dnses, String domains) {
2565 if (dnses.size() == 0 && mDefaultDns != null) {
2566 dnses = new ArrayList();
2567 dnses.add(mDefaultDns);
2569 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2574 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2575 mNetd.setDefaultInterfaceForDns(iface);
2576 for (InetAddress dns : dnses) {
2578 String key = "net.dns" + last;
2579 String value = dns.getHostAddress();
2580 SystemProperties.set(key, value);
2582 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2583 String key = "net.dns" + i;
2584 SystemProperties.set(key, "");
2586 mNumDnsEntries = last;
2587 } catch (Exception e) {
2588 if (DBG) loge("exception setting default dns interface: " + e);
2592 private void handleDnsConfigurationChange(int netType) {
2593 // add default net's dns entries
2594 NetworkStateTracker nt = mNetTrackers[netType];
2595 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2596 LinkProperties p = nt.getLinkProperties();
2597 if (p == null) return;
2598 Collection<InetAddress> dnses = p.getDnses();
2599 if (mNetConfigs[netType].isDefault()) {
2600 String network = nt.getNetworkInfo().getTypeName();
2601 synchronized (mDnsLock) {
2602 if (!mDnsOverridden) {
2603 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
2608 mNetd.setDnsServersForInterface(p.getInterfaceName(),
2609 NetworkUtils.makeStrings(dnses), p.getDomains());
2610 } catch (Exception e) {
2611 if (DBG) loge("exception setting dns servers: " + e);
2613 // set per-pid dns for attached secondary nets
2614 List<Integer> pids = mNetRequestersPids[netType];
2615 for (Integer pid : pids) {
2617 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2618 } catch (Exception e) {
2619 Slog.e(TAG, "exception setting interface for pid: " + e);
2627 private int getRestoreDefaultNetworkDelay(int networkType) {
2628 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2629 NETWORK_RESTORE_DELAY_PROP_NAME);
2630 if(restoreDefaultNetworkDelayStr != null &&
2631 restoreDefaultNetworkDelayStr.length() != 0) {
2633 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2634 } catch (NumberFormatException e) {
2637 // if the system property isn't set, use the value for the apn type
2638 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2640 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2641 (mNetConfigs[networkType] != null)) {
2642 ret = mNetConfigs[networkType].restoreTime;
2648 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2649 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2650 if (mContext.checkCallingOrSelfPermission(
2651 android.Manifest.permission.DUMP)
2652 != PackageManager.PERMISSION_GRANTED) {
2653 pw.println("Permission Denial: can't dump ConnectivityService " +
2654 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2655 Binder.getCallingUid());
2659 // TODO: add locking to get atomic snapshot
2661 for (int i = 0; i < mNetTrackers.length; i++) {
2662 final NetworkStateTracker nst = mNetTrackers[i];
2664 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2665 pw.increaseIndent();
2666 if (nst.getNetworkInfo().isConnected()) {
2667 pw.println("Active network: " + nst.getNetworkInfo().
2670 pw.println(nst.getNetworkInfo());
2671 pw.println(nst.getLinkProperties());
2674 pw.decreaseIndent();
2678 pw.println("Network Requester Pids:");
2679 pw.increaseIndent();
2680 for (int net : mPriorityList) {
2681 String pidString = net + ": ";
2682 for (Integer pid : mNetRequestersPids[net]) {
2683 pidString = pidString + pid.toString() + ", ";
2685 pw.println(pidString);
2688 pw.decreaseIndent();
2690 pw.println("FeatureUsers:");
2691 pw.increaseIndent();
2692 for (Object requester : mFeatureUsers) {
2693 pw.println(requester.toString());
2696 pw.decreaseIndent();
2698 synchronized (this) {
2699 pw.println("NetworkTranstionWakeLock is currently " +
2700 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2701 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2705 mTethering.dump(fd, pw, args);
2707 if (mInetLog != null) {
2709 pw.println("Inet condition reports:");
2710 pw.increaseIndent();
2711 for(int i = 0; i < mInetLog.size(); i++) {
2712 pw.println(mInetLog.get(i));
2714 pw.decreaseIndent();
2718 // must be stateless - things change under us.
2719 private class NetworkStateTrackerHandler extends Handler {
2720 public NetworkStateTrackerHandler(Looper looper) {
2725 public void handleMessage(Message msg) {
2728 case NetworkStateTracker.EVENT_STATE_CHANGED:
2729 info = (NetworkInfo) msg.obj;
2730 int type = info.getType();
2731 NetworkInfo.State state = info.getState();
2733 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2734 (state == NetworkInfo.State.DISCONNECTED)) {
2735 log("ConnectivityChange for " +
2736 info.getTypeName() + ": " +
2737 state + "/" + info.getDetailedState());
2740 // After booting we'll check once for mobile provisioning
2741 // if we've provisioned by and connected.
2742 if (!mFirstProvisioningCheckStarted
2743 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2744 Settings.Global.DEVICE_PROVISIONED, 0))
2745 && (state == NetworkInfo.State.CONNECTED)) {
2746 log("check provisioning after booting");
2747 mFirstProvisioningCheckStarted = true;
2748 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2751 EventLogTags.writeConnectivityStateChanged(
2752 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2754 if (info.getDetailedState() ==
2755 NetworkInfo.DetailedState.FAILED) {
2756 handleConnectionFailure(info);
2757 } else if (info.getDetailedState() ==
2758 DetailedState.CAPTIVE_PORTAL_CHECK) {
2759 handleCaptivePortalTrackerCheck(info);
2760 } else if (state == NetworkInfo.State.DISCONNECTED) {
2761 handleDisconnect(info);
2762 } else if (state == NetworkInfo.State.SUSPENDED) {
2763 // TODO: need to think this over.
2764 // the logic here is, handle SUSPENDED the same as
2765 // DISCONNECTED. The only difference being we are
2766 // broadcasting an intent with NetworkInfo that's
2767 // suspended. This allows the applications an
2768 // opportunity to handle DISCONNECTED and SUSPENDED
2769 // differently, or not.
2770 handleDisconnect(info);
2771 } else if (state == NetworkInfo.State.CONNECTED) {
2772 handleConnect(info);
2774 if (mLockdownTracker != null) {
2775 mLockdownTracker.onNetworkInfoChanged(info);
2778 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2779 info = (NetworkInfo) msg.obj;
2780 // TODO: Temporary allowing network configuration
2781 // change not resetting sockets.
2783 handleConnectivityChange(info.getType(), false);
2785 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2786 info = (NetworkInfo) msg.obj;
2787 type = info.getType();
2788 updateNetworkSettings(mNetTrackers[type]);
2794 private class InternalHandler extends Handler {
2795 public InternalHandler(Looper looper) {
2800 public void handleMessage(Message msg) {
2803 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2804 String causedBy = null;
2805 synchronized (ConnectivityService.this) {
2806 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2807 mNetTransitionWakeLock.isHeld()) {
2808 mNetTransitionWakeLock.release();
2809 causedBy = mNetTransitionWakeLockCausedBy;
2812 if (causedBy != null) {
2813 log("NetTransition Wakelock for " + causedBy + " released by timeout");
2816 case EVENT_RESTORE_DEFAULT_NETWORK:
2817 FeatureUser u = (FeatureUser)msg.obj;
2820 case EVENT_INET_CONDITION_CHANGE:
2822 int netType = msg.arg1;
2823 int condition = msg.arg2;
2824 handleInetConditionChange(netType, condition);
2827 case EVENT_INET_CONDITION_HOLD_END:
2829 int netType = msg.arg1;
2830 int sequence = msg.arg2;
2831 handleInetConditionHoldEnd(netType, sequence);
2834 case EVENT_SET_NETWORK_PREFERENCE:
2836 int preference = msg.arg1;
2837 handleSetNetworkPreference(preference);
2840 case EVENT_SET_MOBILE_DATA:
2842 boolean enabled = (msg.arg1 == ENABLED);
2843 handleSetMobileData(enabled);
2846 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2848 handleDeprecatedGlobalHttpProxy();
2851 case EVENT_SET_DEPENDENCY_MET:
2853 boolean met = (msg.arg1 == ENABLED);
2854 handleSetDependencyMet(msg.arg2, met);
2857 case EVENT_RESTORE_DNS:
2859 if (mActiveDefaultNetwork != -1) {
2860 handleDnsConfigurationChange(mActiveDefaultNetwork);
2864 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2866 Intent intent = (Intent)msg.obj;
2867 sendStickyBroadcast(intent);
2870 case EVENT_SET_POLICY_DATA_ENABLE: {
2871 final int networkType = msg.arg1;
2872 final boolean enabled = msg.arg2 == ENABLED;
2873 handleSetPolicyDataEnable(networkType, enabled);
2876 case EVENT_VPN_STATE_CHANGED: {
2877 if (mLockdownTracker != null) {
2878 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2882 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2883 int tag = mEnableFailFastMobileDataTag.get();
2884 if (msg.arg1 == tag) {
2885 MobileDataStateTracker mobileDst =
2886 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2887 if (mobileDst != null) {
2888 mobileDst.setEnableFailFastMobileData(msg.arg2);
2891 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2892 + " != tag:" + tag);
2899 // javadoc from interface
2900 public int tether(String iface) {
2901 enforceTetherChangePermission();
2903 if (isTetheringSupported()) {
2904 return mTethering.tether(iface);
2906 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2910 // javadoc from interface
2911 public int untether(String iface) {
2912 enforceTetherChangePermission();
2914 if (isTetheringSupported()) {
2915 return mTethering.untether(iface);
2917 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2921 // javadoc from interface
2922 public int getLastTetherError(String iface) {
2923 enforceTetherAccessPermission();
2925 if (isTetheringSupported()) {
2926 return mTethering.getLastTetherError(iface);
2928 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2932 // TODO - proper iface API for selection by property, inspection, etc
2933 public String[] getTetherableUsbRegexs() {
2934 enforceTetherAccessPermission();
2935 if (isTetheringSupported()) {
2936 return mTethering.getTetherableUsbRegexs();
2938 return new String[0];
2942 public String[] getTetherableWifiRegexs() {
2943 enforceTetherAccessPermission();
2944 if (isTetheringSupported()) {
2945 return mTethering.getTetherableWifiRegexs();
2947 return new String[0];
2951 public String[] getTetherableBluetoothRegexs() {
2952 enforceTetherAccessPermission();
2953 if (isTetheringSupported()) {
2954 return mTethering.getTetherableBluetoothRegexs();
2956 return new String[0];
2960 public int setUsbTethering(boolean enable) {
2961 enforceTetherChangePermission();
2962 if (isTetheringSupported()) {
2963 return mTethering.setUsbTethering(enable);
2965 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2969 // TODO - move iface listing, queries, etc to new module
2970 // javadoc from interface
2971 public String[] getTetherableIfaces() {
2972 enforceTetherAccessPermission();
2973 return mTethering.getTetherableIfaces();
2976 public String[] getTetheredIfaces() {
2977 enforceTetherAccessPermission();
2978 return mTethering.getTetheredIfaces();
2982 public String[] getTetheredIfacePairs() {
2983 enforceTetherAccessPermission();
2984 return mTethering.getTetheredIfacePairs();
2987 public String[] getTetheringErroredIfaces() {
2988 enforceTetherAccessPermission();
2989 return mTethering.getErroredIfaces();
2992 // if ro.tether.denied = true we default to no tethering
2993 // gservices could set the secure setting to 1 though to enable it on a build where it
2994 // had previously been turned off.
2995 public boolean isTetheringSupported() {
2996 enforceTetherAccessPermission();
2997 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2998 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2999 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3000 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3001 mTethering.getTetherableWifiRegexs().length != 0 ||
3002 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3003 mTethering.getUpstreamIfaceTypes().length != 0);
3006 // An API NetworkStateTrackers can call when they lose their network.
3007 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3008 // whichever happens first. The timer is started by the first caller and not
3009 // restarted by subsequent callers.
3010 public void requestNetworkTransitionWakelock(String forWhom) {
3011 enforceConnectivityInternalPermission();
3012 synchronized (this) {
3013 if (mNetTransitionWakeLock.isHeld()) return;
3014 mNetTransitionWakeLockSerialNumber++;
3015 mNetTransitionWakeLock.acquire();
3016 mNetTransitionWakeLockCausedBy = forWhom;
3018 mHandler.sendMessageDelayed(mHandler.obtainMessage(
3019 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3020 mNetTransitionWakeLockSerialNumber, 0),
3021 mNetTransitionWakeLockTimeout);
3025 // 100 percent is full good, 0 is full bad.
3026 public void reportInetCondition(int networkType, int percentage) {
3027 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3028 mContext.enforceCallingOrSelfPermission(
3029 android.Manifest.permission.STATUS_BAR,
3030 "ConnectivityService");
3033 int pid = getCallingPid();
3034 int uid = getCallingUid();
3035 String s = pid + "(" + uid + ") reports inet is " +
3036 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3037 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3039 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3043 mHandler.sendMessage(mHandler.obtainMessage(
3044 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3047 private void handleInetConditionChange(int netType, int condition) {
3048 if (mActiveDefaultNetwork == -1) {
3049 if (DBG) log("handleInetConditionChange: no active default network - ignore");
3052 if (mActiveDefaultNetwork != netType) {
3053 if (DBG) log("handleInetConditionChange: net=" + netType +
3054 " != default=" + mActiveDefaultNetwork + " - ignore");
3058 log("handleInetConditionChange: net=" +
3059 netType + ", condition=" + condition +
3060 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3062 mDefaultInetCondition = condition;
3064 if (mInetConditionChangeInFlight == false) {
3065 if (VDBG) log("handleInetConditionChange: starting a change hold");
3066 // setup a new hold to debounce this
3067 if (mDefaultInetCondition > 50) {
3068 delay = Settings.Global.getInt(mContext.getContentResolver(),
3069 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3071 delay = Settings.Global.getInt(mContext.getContentResolver(),
3072 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3074 mInetConditionChangeInFlight = true;
3075 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3076 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3078 // we've set the new condition, when this hold ends that will get picked up
3079 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3083 private void handleInetConditionHoldEnd(int netType, int sequence) {
3085 log("handleInetConditionHoldEnd: net=" + netType +
3086 ", condition=" + mDefaultInetCondition +
3087 ", published condition=" + mDefaultInetConditionPublished);
3089 mInetConditionChangeInFlight = false;
3091 if (mActiveDefaultNetwork == -1) {
3092 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3095 if (mDefaultConnectionSequence != sequence) {
3096 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3099 // TODO: Figure out why this optimization sometimes causes a
3100 // change in mDefaultInetCondition to be missed and the
3101 // UI to not be updated.
3102 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3103 // if (DBG) log("no change in condition - aborting");
3106 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3107 if (networkInfo.isConnected() == false) {
3108 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3111 mDefaultInetConditionPublished = mDefaultInetCondition;
3112 sendInetConditionBroadcast(networkInfo);
3116 public ProxyProperties getProxy() {
3117 // this information is already available as a world read/writable jvm property
3118 // so this API change wouldn't have a benifit. It also breaks the passing
3119 // of proxy info to all the JVMs.
3120 // enforceAccessPermission();
3121 synchronized (mProxyLock) {
3122 if (mGlobalProxy != null) return mGlobalProxy;
3123 return (mDefaultProxyDisabled ? null : mDefaultProxy);
3127 public void setGlobalProxy(ProxyProperties proxyProperties) {
3128 enforceConnectivityInternalPermission();
3129 synchronized (mProxyLock) {
3130 if (proxyProperties == mGlobalProxy) return;
3131 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3132 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3136 String exclList = "";
3137 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3138 mGlobalProxy = new ProxyProperties(proxyProperties);
3139 host = mGlobalProxy.getHost();
3140 port = mGlobalProxy.getPort();
3141 exclList = mGlobalProxy.getExclusionList();
3143 mGlobalProxy = null;
3145 ContentResolver res = mContext.getContentResolver();
3146 final long token = Binder.clearCallingIdentity();
3148 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3149 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3150 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3153 Binder.restoreCallingIdentity(token);
3157 if (mGlobalProxy == null) {
3158 proxyProperties = mDefaultProxy;
3160 sendProxyBroadcast(proxyProperties);
3163 private void loadGlobalProxy() {
3164 ContentResolver res = mContext.getContentResolver();
3165 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3166 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3167 String exclList = Settings.Global.getString(res,
3168 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3169 if (!TextUtils.isEmpty(host)) {
3170 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3171 synchronized (mProxyLock) {
3172 mGlobalProxy = proxyProperties;
3177 public ProxyProperties getGlobalProxy() {
3178 // this information is already available as a world read/writable jvm property
3179 // so this API change wouldn't have a benifit. It also breaks the passing
3180 // of proxy info to all the JVMs.
3181 // enforceAccessPermission();
3182 synchronized (mProxyLock) {
3183 return mGlobalProxy;
3187 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3188 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3191 synchronized (mProxyLock) {
3192 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3193 if (mDefaultProxy == proxy) return; // catches repeated nulls
3194 mDefaultProxy = proxy;
3196 if (mGlobalProxy != null) return;
3197 if (!mDefaultProxyDisabled) {
3198 sendProxyBroadcast(proxy);
3203 private void handleDeprecatedGlobalHttpProxy() {
3204 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3205 Settings.Global.HTTP_PROXY);
3206 if (!TextUtils.isEmpty(proxy)) {
3207 String data[] = proxy.split(":");
3208 String proxyHost = data[0];
3209 int proxyPort = 8080;
3210 if (data.length > 1) {
3212 proxyPort = Integer.parseInt(data[1]);
3213 } catch (NumberFormatException e) {
3217 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3222 private void sendProxyBroadcast(ProxyProperties proxy) {
3223 if (proxy == null) proxy = new ProxyProperties("", 0, "");
3224 if (DBG) log("sending Proxy Broadcast for " + proxy);
3225 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3226 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3227 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3228 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3229 final long ident = Binder.clearCallingIdentity();
3231 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3233 Binder.restoreCallingIdentity(ident);
3237 private static class SettingsObserver extends ContentObserver {
3239 private Handler mHandler;
3240 SettingsObserver(Handler handler, int what) {
3246 void observe(Context context) {
3247 ContentResolver resolver = context.getContentResolver();
3248 resolver.registerContentObserver(Settings.Global.getUriFor(
3249 Settings.Global.HTTP_PROXY), false, this);
3253 public void onChange(boolean selfChange) {
3254 mHandler.obtainMessage(mWhat).sendToTarget();
3258 private static void log(String s) {
3262 private static void loge(String s) {
3266 int convertFeatureToNetworkType(int networkType, String feature) {
3267 int usedNetworkType = networkType;
3269 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3270 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3271 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3272 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3273 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3274 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3275 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3276 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3277 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3278 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3279 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3280 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3281 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3282 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3283 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3284 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3286 Slog.e(TAG, "Can't match any mobile netTracker!");
3288 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3289 if (TextUtils.equals(feature, "p2p")) {
3290 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3292 Slog.e(TAG, "Can't match any wifi netTracker!");
3295 Slog.e(TAG, "Unexpected network type");
3297 return usedNetworkType;
3300 private static <T> T checkNotNull(T value, String message) {
3301 if (value == null) {
3302 throw new NullPointerException(message);
3308 * Protect a socket from VPN routing rules. This method is used by
3309 * VpnBuilder and not available in ConnectivityManager. Permissions
3310 * are checked in Vpn class.
3314 public boolean protectVpn(ParcelFileDescriptor socket) {
3315 throwIfLockdownEnabled();
3317 int type = mActiveDefaultNetwork;
3318 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3319 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3322 } catch (Exception e) {
3327 } catch (Exception e) {
3335 * Prepare for a VPN application. This method is used by VpnDialogs
3336 * and not available in ConnectivityManager. Permissions are checked
3341 public boolean prepareVpn(String oldPackage, String newPackage) {
3342 throwIfLockdownEnabled();
3343 return mVpn.prepare(oldPackage, newPackage);
3347 * Configure a TUN interface and return its file descriptor. Parameters
3348 * are encoded and opaque to this class. This method is used by VpnBuilder
3349 * and not available in ConnectivityManager. Permissions are checked in
3354 public ParcelFileDescriptor establishVpn(VpnConfig config) {
3355 throwIfLockdownEnabled();
3356 return mVpn.establish(config);
3360 * Start legacy VPN, controlling native daemons as needed. Creates a
3361 * secondary thread to perform connection work, returning quickly.
3364 public void startLegacyVpn(VpnProfile profile) {
3365 throwIfLockdownEnabled();
3366 final LinkProperties egress = getActiveLinkProperties();
3367 if (egress == null) {
3368 throw new IllegalStateException("Missing active network connection");
3370 mVpn.startLegacyVpn(profile, mKeyStore, egress);
3374 * Return the information of the ongoing legacy VPN. This method is used
3375 * by VpnSettings and not available in ConnectivityManager. Permissions
3376 * are checked in Vpn class.
3380 public LegacyVpnInfo getLegacyVpnInfo() {
3381 throwIfLockdownEnabled();
3382 return mVpn.getLegacyVpnInfo();
3386 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3387 * through NetworkStateTracker since it works differently. For example, it
3388 * needs to override DNS servers but never takes the default routes. It
3389 * relies on another data network, and it could keep existing connections
3390 * alive after reconnecting, switching between networks, or even resuming
3391 * from deep sleep. Calls from applications should be done synchronously
3392 * to avoid race conditions. As these are all hidden APIs, refactoring can
3393 * be done whenever a better abstraction is developed.
3395 public class VpnCallback {
3396 private VpnCallback() {
3399 public void onStateChanged(NetworkInfo info) {
3400 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3403 public void override(List<String> dnsServers, List<String> searchDomains) {
3404 if (dnsServers == null) {
3409 // Convert DNS servers into addresses.
3410 List<InetAddress> addresses = new ArrayList<InetAddress>();
3411 for (String address : dnsServers) {
3412 // Double check the addresses and remove invalid ones.
3414 addresses.add(InetAddress.parseNumericAddress(address));
3415 } catch (Exception e) {
3419 if (addresses.isEmpty()) {
3424 // Concatenate search domains into a string.
3425 StringBuilder buffer = new StringBuilder();
3426 if (searchDomains != null) {
3427 for (String domain : searchDomains) {
3428 buffer.append(domain).append(' ');
3431 String domains = buffer.toString().trim();
3433 // Apply DNS changes.
3434 synchronized (mDnsLock) {
3435 updateDnsLocked("VPN", "VPN", addresses, domains);
3436 mDnsOverridden = true;
3439 // Temporarily disable the default proxy (not global).
3440 synchronized (mProxyLock) {
3441 mDefaultProxyDisabled = true;
3442 if (mGlobalProxy == null && mDefaultProxy != null) {
3443 sendProxyBroadcast(null);
3447 // TODO: support proxy per network.
3450 public void restore() {
3451 synchronized (mDnsLock) {
3452 if (mDnsOverridden) {
3453 mDnsOverridden = false;
3454 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3457 synchronized (mProxyLock) {
3458 mDefaultProxyDisabled = false;
3459 if (mGlobalProxy == null && mDefaultProxy != null) {
3460 sendProxyBroadcast(mDefaultProxy);
3467 public boolean updateLockdownVpn() {
3468 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3469 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3473 // Tear down existing lockdown if profile was removed
3474 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3475 if (mLockdownEnabled) {
3476 if (!mKeyStore.isUnlocked()) {
3477 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3481 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3482 final VpnProfile profile = VpnProfile.decode(
3483 profileName, mKeyStore.get(Credentials.VPN + profileName));
3484 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3486 setLockdownTracker(null);
3493 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3494 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3496 private void setLockdownTracker(LockdownVpnTracker tracker) {
3497 // Shutdown any existing tracker
3498 final LockdownVpnTracker existing = mLockdownTracker;
3499 mLockdownTracker = null;
3500 if (existing != null) {
3501 existing.shutdown();
3505 if (tracker != null) {
3506 mNetd.setFirewallEnabled(true);
3507 mNetd.setFirewallInterfaceRule("lo", true);
3508 mLockdownTracker = tracker;
3509 mLockdownTracker.init();
3511 mNetd.setFirewallEnabled(false);
3513 } catch (RemoteException e) {
3514 // ignored; NMS lives inside system_server
3518 private void throwIfLockdownEnabled() {
3519 if (mLockdownEnabled) {
3520 throw new IllegalStateException("Unavailable in lockdown mode");
3524 public void supplyMessenger(int networkType, Messenger messenger) {
3525 enforceConnectivityInternalPermission();
3527 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3528 mNetTrackers[networkType].supplyMessenger(messenger);
3532 public int findConnectionTypeForIface(String iface) {
3533 enforceConnectivityInternalPermission();
3535 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3536 for (NetworkStateTracker tracker : mNetTrackers) {
3537 if (tracker != null) {
3538 LinkProperties lp = tracker.getLinkProperties();
3539 if (lp != null && iface.equals(lp.getInterfaceName())) {
3540 return tracker.getNetworkInfo().getType();
3544 return ConnectivityManager.TYPE_NONE;
3548 * Have mobile data fail fast if enabled.
3550 * @param enabled DctConstants.ENABLED/DISABLED
3552 private void setEnableFailFastMobileData(int enabled) {
3555 if (enabled == DctConstants.ENABLED) {
3556 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3558 tag = mEnableFailFastMobileDataTag.get();
3560 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3565 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3566 final ResultReceiver resultReceiver) {
3567 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3568 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3569 + " resultReceiver=" + resultReceiver);
3570 enforceChangePermission();
3572 mFirstProvisioningCheckStarted = true;
3574 int timeOutMs = suggestedTimeOutMs;
3575 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3576 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3579 // Check that mobile networks are supported
3580 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3581 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3582 log("checkMobileProvisioning: X no mobile network");
3583 if (resultReceiver != null) {
3584 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3589 final long token = Binder.clearCallingIdentity();
3591 CheckMp checkMp = new CheckMp(mContext, this);
3592 CheckMp.CallBack cb = new CheckMp.CallBack() {
3594 void onComplete(Integer result) {
3595 log("CheckMp.onComplete: result=" + result);
3596 if (resultReceiver != null) {
3597 log("CheckMp.onComplete: send result");
3598 resultReceiver.send(result, null);
3601 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3603 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3604 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3605 log("CheckMp.onComplete: ignore, connected or no connection");
3608 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3609 log("CheckMp.onComplete: warm sim");
3610 String url = getMobileProvisioningUrl();
3611 if (TextUtils.isEmpty(url)) {
3612 url = getMobileRedirectedProvisioningUrl();
3614 if (TextUtils.isEmpty(url) == false) {
3615 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3616 setNotificationVisible(true, ni, url);
3618 log("CheckMp.onComplete: warm sim (redirected), no url");
3622 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3623 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3624 String url = getMobileProvisioningUrl();
3625 if (TextUtils.isEmpty(url) == false) {
3626 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3627 setNotificationVisible(true, ni, url);
3629 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3634 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3640 CheckMp.Params params =
3641 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3642 log("checkMobileProvisioning: params=" + params);
3643 setNotificationVisible(false, null, null);
3644 checkMp.execute(params);
3646 Binder.restoreCallingIdentity(token);
3647 log("checkMobileProvisioning: X");
3652 static class CheckMp extends
3653 AsyncTask<CheckMp.Params, Void, Integer> {
3654 private static final String CHECKMP_TAG = "CheckMp";
3655 public static final int MAX_TIMEOUT_MS = 60000;
3656 private static final int SOCKET_TIMEOUT_MS = 5000;
3657 private Context mContext;
3658 private ConnectivityService mCs;
3659 private TelephonyManager mTm;
3660 private Params mParams;
3663 * Parameters for AsyncTask.execute
3665 static class Params {
3666 private String mUrl;
3667 private long mTimeOutMs;
3668 private CallBack mCb;
3670 Params(String url, long timeOutMs, CallBack cb) {
3672 mTimeOutMs = timeOutMs;
3677 public String toString() {
3678 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3683 * The call back object passed in Params. onComplete will be called
3684 * on the main thread.
3686 abstract static class CallBack {
3687 // Called on the main thread.
3688 abstract void onComplete(Integer result);
3691 public CheckMp(Context context, ConnectivityService cs) {
3695 // Setup access to TelephonyService we'll be using.
3696 mTm = (TelephonyManager) mContext.getSystemService(
3697 Context.TELEPHONY_SERVICE);
3701 * Get the default url to use for the test.
3703 public String getDefaultUrl() {
3704 // See http://go/clientsdns for usage approval
3705 String server = Settings.Global.getString(mContext.getContentResolver(),
3706 Settings.Global.CAPTIVE_PORTAL_SERVER);
3707 if (server == null) {
3708 server = "clients3.google.com";
3710 return "http://" + server + "/generate_204";
3714 * Detect if its possible to connect to the http url. DNS based detection techniques
3715 * do not work at all hotspots. The best way to check is to perform a request to
3716 * a known address that fetches the data we expect.
3718 private synchronized Integer isMobileOk(Params params) {
3719 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3720 Uri orgUri = Uri.parse(params.mUrl);
3721 Random rand = new Random();
3725 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3726 log("isMobileOk: not mobile capable");
3727 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3731 // Enable fail fast as we'll do retries here and use a
3732 // hipri connection so the default connection stays active.
3733 log("isMobileOk: start hipri url=" + params.mUrl);
3734 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3736 // Continue trying to connect until time has run out
3737 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3739 // First wait until we can start using hipri
3740 Binder binder = new Binder();
3741 while(SystemClock.elapsedRealtime() < endTime) {
3742 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3743 Phone.FEATURE_ENABLE_HIPRI, binder);
3744 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3745 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3746 log("isMobileOk: hipri started");
3749 if (VDBG) log("isMobileOk: hipri not started yet");
3750 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3754 // Continue trying to connect until time has run out
3755 while(SystemClock.elapsedRealtime() < endTime) {
3757 // Wait for hipri to connect.
3758 // TODO: Don't poll and handle situation where hipri fails
3759 // because default is retrying. See b/9569540
3760 NetworkInfo.State state = mCs
3761 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3762 if (state != NetworkInfo.State.CONNECTED) {
3764 log("isMobileOk: not connected ni=" +
3765 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3768 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3772 // Get of the addresses associated with the url host. We need to use the
3773 // address otherwise HttpURLConnection object will use the name to get
3774 // the addresses and is will try every address but that will bypass the
3775 // route to host we setup and the connection could succeed as the default
3776 // interface might be connected to the internet via wifi or other interface.
3777 InetAddress[] addresses;
3779 addresses = InetAddress.getAllByName(orgUri.getHost());
3780 } catch (UnknownHostException e) {
3781 log("isMobileOk: UnknownHostException");
3782 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3785 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3787 // Get the type of addresses supported by this link
3788 LinkProperties lp = mCs.getLinkProperties(
3789 ConnectivityManager.TYPE_MOBILE_HIPRI);
3790 boolean linkHasIpv4 = hasIPv4Address(lp);
3791 boolean linkHasIpv6 = hasIPv6Address(lp);
3792 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3793 + " linkHasIpv6=" + linkHasIpv6);
3795 // Loop through at most 3 valid addresses or all of the address or until
3796 // we run out of time
3797 int loops = Math.min(3, addresses.length);
3798 for(int validAddr=0, addrTried=0;
3799 (validAddr < loops) && (addrTried < addresses.length)
3800 && (SystemClock.elapsedRealtime() < endTime);
3803 // Choose the address at random but make sure its type is supported
3804 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3805 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3806 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3807 // Valid address, so use it
3810 // Invalid address so try next address
3814 // Make a route to host so we check the specific interface.
3815 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3816 hostAddr.getAddress())) {
3817 // Wait a short time to be sure the route is established ??
3819 + " wait to establish route to hostAddr=" + hostAddr);
3823 + " could not establish route to hostAddr=" + hostAddr);
3827 // Rewrite the url to have numeric address to use the specific route.
3828 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3829 // is used which is useless in this case.
3830 URL newUrl = new URL(orgUri.getScheme() + "://"
3831 + hostAddr.getHostAddress() + orgUri.getPath());
3832 log("isMobileOk: newUrl=" + newUrl);
3834 HttpURLConnection urlConn = null;
3836 // Open the connection set the request header and get the response
3837 urlConn = (HttpURLConnection) newUrl.openConnection(
3838 java.net.Proxy.NO_PROXY);
3839 urlConn.setInstanceFollowRedirects(false);
3840 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3841 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3842 urlConn.setUseCaches(false);
3843 urlConn.setAllowUserInteraction(false);
3844 urlConn.setRequestProperty("Connection", "close");
3845 int responseCode = urlConn.getResponseCode();
3846 if (responseCode == 204) {
3847 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3849 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3851 log("isMobileOk: connected responseCode=" + responseCode);
3852 urlConn.disconnect();
3855 } catch (Exception e) {
3856 log("isMobileOk: HttpURLConnection Exception e=" + e);
3857 if (urlConn != null) {
3858 urlConn.disconnect();
3863 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3864 log("isMobileOk: loops|timed out");
3866 } catch (Exception e) {
3867 log("isMobileOk: Exception e=" + e);
3871 log("isMobileOk: timed out");
3873 log("isMobileOk: F stop hipri");
3874 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3875 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3876 Phone.FEATURE_ENABLE_HIPRI);
3877 log("isMobileOk: X result=" + result);
3883 protected Integer doInBackground(Params... params) {
3884 return isMobileOk(params[0]);
3888 protected void onPostExecute(Integer result) {
3889 log("onPostExecute: result=" + result);
3890 if ((mParams != null) && (mParams.mCb != null)) {
3891 mParams.mCb.onComplete(result);
3895 private String inetAddressesToString(InetAddress[] addresses) {
3896 StringBuffer sb = new StringBuffer();
3897 boolean firstTime = true;
3898 for(InetAddress addr : addresses) {
3906 return sb.toString();
3909 private void printNetworkInfo() {
3910 boolean hasIccCard = mTm.hasIccCard();
3911 int simState = mTm.getSimState();
3912 log("hasIccCard=" + hasIccCard
3913 + " simState=" + simState);
3914 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3916 log("ni.length=" + ni.length);
3917 for (NetworkInfo netInfo: ni) {
3918 log("netInfo=" + netInfo.toString());
3921 log("no network info ni=null");
3926 * Sleep for a few seconds then return.
3929 private static void sleep(int seconds) {
3931 Thread.sleep(seconds * 1000);
3932 } catch (InterruptedException e) {
3933 e.printStackTrace();
3937 public boolean hasIPv4Address(LinkProperties lp) {
3938 return lp.hasIPv4Address();
3941 // Not implemented in LinkProperties, do it here.
3942 public boolean hasIPv6Address(LinkProperties lp) {
3943 for (LinkAddress address : lp.getLinkAddresses()) {
3944 if (address.getAddress() instanceof Inet6Address) {
3951 private void log(String s) {
3952 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3956 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3958 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3959 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3961 Resources r = Resources.getSystem();
3962 NotificationManager notificationManager = (NotificationManager) mContext
3963 .getSystemService(Context.NOTIFICATION_SERVICE);
3967 CharSequence details;
3969 switch (networkInfo.getType()) {
3970 case ConnectivityManager.TYPE_WIFI:
3971 log("setNotificationVisible: TYPE_WIFI");
3972 title = r.getString(R.string.wifi_available_sign_in, 0);
3973 details = r.getString(R.string.network_available_sign_in_detailed,
3974 networkInfo.getExtraInfo());
3975 icon = R.drawable.stat_notify_wifi_in_range;
3977 case ConnectivityManager.TYPE_MOBILE:
3978 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3979 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3980 title = r.getString(R.string.network_available_sign_in, 0);
3981 // TODO: Change this to pull from NetworkInfo once a printable
3982 // name has been added to it
3983 details = mTelephonyManager.getNetworkOperatorName();
3984 icon = R.drawable.stat_notify_rssi_in_range;
3987 log("setNotificationVisible: other type=" + networkInfo.getType());
3988 title = r.getString(R.string.network_available_sign_in, 0);
3989 details = r.getString(R.string.network_available_sign_in_detailed,
3990 networkInfo.getExtraInfo());
3991 icon = R.drawable.stat_notify_rssi_in_range;
3995 Notification notification = new Notification();
3996 notification.when = 0;
3997 notification.icon = icon;
3998 notification.flags = Notification.FLAG_AUTO_CANCEL;
3999 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4000 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4001 Intent.FLAG_ACTIVITY_NEW_TASK);
4002 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4003 notification.tickerText = title;
4004 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4006 log("setNotificaitionVisible: notify notificaiton=" + notification);
4007 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4009 log("setNotificaitionVisible: cancel");
4010 notificationManager.cancel(NOTIFICATION_ID, 1);
4012 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4015 /** Location to an updatable file listing carrier provisioning urls.
4018 * <?xml version="1.0" encoding="utf-8"?>
4019 * <provisioningUrls>
4020 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
4021 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4022 * </provisioningUrls>
4024 private static final String PROVISIONING_URL_PATH =
4025 "/data/misc/radio/provisioning_urls.xml";
4026 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4028 /** XML tag for root element. */
4029 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4030 /** XML tag for individual url */
4031 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4032 /** XML tag for redirected url */
4033 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4034 /** XML attribute for mcc */
4035 private static final String ATTR_MCC = "mcc";
4036 /** XML attribute for mnc */
4037 private static final String ATTR_MNC = "mnc";
4039 private static final int REDIRECTED_PROVISIONING = 1;
4040 private static final int PROVISIONING = 2;
4042 private String getProvisioningUrlBaseFromFile(int type) {
4043 FileReader fileReader = null;
4044 XmlPullParser parser = null;
4045 Configuration config = mContext.getResources().getConfiguration();
4050 tagType = TAG_PROVISIONING_URL;
4052 case REDIRECTED_PROVISIONING:
4053 tagType = TAG_REDIRECTED_URL;
4056 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4061 fileReader = new FileReader(mProvisioningUrlFile);
4062 parser = Xml.newPullParser();
4063 parser.setInput(fileReader);
4064 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4067 XmlUtils.nextElement(parser);
4069 String element = parser.getName();
4070 if (element == null) break;
4072 if (element.equals(tagType)) {
4073 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4075 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4076 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4077 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4079 if (parser.getEventType() == XmlPullParser.TEXT) {
4080 return parser.getText();
4084 } catch (NumberFormatException e) {
4085 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4090 } catch (FileNotFoundException e) {
4091 loge("Carrier Provisioning Urls file not found");
4092 } catch (XmlPullParserException e) {
4093 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4094 } catch (IOException e) {
4095 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4097 if (fileReader != null) {
4100 } catch (IOException e) {}
4106 private String getMobileRedirectedProvisioningUrl() {
4107 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4108 if (TextUtils.isEmpty(url)) {
4109 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4114 public String getMobileProvisioningUrl() {
4115 enforceConnectivityInternalPermission();
4116 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4117 if (TextUtils.isEmpty(url)) {
4118 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4119 log("getProvisioningUrl: mobile_provisioining_url from resource =" + url);
4121 log("getProvisioningUrl: mobile_provisioning_url from File =" + url);
4123 // populate the iccid, imei and phone number in the provisioning url.
4124 if (!TextUtils.isEmpty(url)) {
4125 String phoneNumber = mTelephonyManager.getLine1Number();
4126 if (TextUtils.isEmpty(phoneNumber)) {
4127 phoneNumber = "0000000000";
4129 url = String.format(url,
4130 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4131 mTelephonyManager.getDeviceId() /* IMEI */,
4132 phoneNumber /* Phone numer */);