OSDN Git Service

Check that hipri has started.
[android-x86/frameworks-base.git] / services / java / com / android / server / ConnectivityService.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server;
18
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;
33
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;
102
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;
120
121 import dalvik.system.DexClassLoader;
122
123 import org.xmlpull.v1.XmlPullParser;
124 import org.xmlpull.v1.XmlPullParserException;
125
126 import java.io.File;
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;
137 import java.net.URL;
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;
147
148 /**
149  * @hide
150  */
151 public class ConnectivityService extends IConnectivityManager.Stub {
152     private static final String TAG = "ConnectivityService";
153
154     private static final boolean DBG = true;
155     private static final boolean VDBG = false;
156
157     private static final boolean LOGD_RULES = false;
158
159     // TODO: create better separation between radio types and network types
160
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";
166
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";
172
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;
176
177     private Tethering mTethering;
178
179     private KeyStore mKeyStore;
180
181     private Vpn mVpn;
182     private VpnCallback mVpnCallback = new VpnCallback();
183
184     private boolean mLockdownEnabled;
185     private LockdownVpnTracker mLockdownTracker;
186
187     private Nat464Xlat mClat;
188
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();
195
196     /**
197      * Sometimes we want to refer to the individual network state
198      * trackers separately, and sometimes we just want to treat them
199      * abstractly.
200      */
201     private NetworkStateTracker mNetTrackers[];
202
203     /* Handles captive portal check on a network */
204     private CaptivePortalTracker mCaptivePortalTracker;
205
206     /**
207      * The link properties that define the current links
208      */
209     private LinkProperties mCurrentLinkProperties[];
210
211     /**
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
214      */
215     private List<Integer> mNetRequestersPids[];
216
217     // priority order of the nettrackers
218     // (excluding dynamically set mNetworkPreference)
219     // TODO - move mNetworkTypePreference into this
220     private int[] mPriorityList;
221
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;
230
231     private Object mDnsLock = new Object();
232     private int mNumDnsEntries;
233     private boolean mDnsOverridden = false;
234
235     private boolean mTestMode;
236     private static ConnectivityService sServiceInstance;
237
238     private INetworkManagementService mNetd;
239     private INetworkPolicyManager mPolicyManager;
240
241     private static final int ENABLED  = 1;
242     private static final int DISABLED = 0;
243
244     private static final boolean ADD = true;
245     private static final boolean REMOVE = false;
246
247     private static final boolean TO_DEFAULT_TABLE = true;
248     private static final boolean TO_SECONDARY_TABLE = false;
249
250     /**
251      * used internally as a delayed event to make us switch back to the
252      * default network
253      */
254     private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
255
256     /**
257      * used internally to change our mobile data enabled flag
258      */
259     private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
260
261     /**
262      * used internally to change our network preference setting
263      * arg1 = networkType to prefer
264      */
265     private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
266
267     /**
268      * used internally to synchronize inet condition reports
269      * arg1 = networkType
270      * arg2 = condition (0 bad, 100 good)
271      */
272     private static final int EVENT_INET_CONDITION_CHANGE = 4;
273
274     /**
275      * used internally to mark the end of inet condition hold periods
276      * arg1 = networkType
277      */
278     private static final int EVENT_INET_CONDITION_HOLD_END = 5;
279
280     /**
281      * used internally to set enable/disable cellular data
282      * arg1 = ENBALED or DISABLED
283      */
284     private static final int EVENT_SET_MOBILE_DATA = 7;
285
286     /**
287      * used internally to clear a wakelock when transitioning
288      * from one net to another
289      */
290     private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
291
292     /**
293      * used internally to reload global proxy settings
294      */
295     private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
296
297     /**
298      * used internally to set external dependency met/unmet
299      * arg1 = ENABLED (met) or DISABLED (unmet)
300      * arg2 = NetworkType
301      */
302     private static final int EVENT_SET_DEPENDENCY_MET = 10;
303
304     /**
305      * used internally to restore DNS properties back to the
306      * default network
307      */
308     private static final int EVENT_RESTORE_DNS = 11;
309
310     /**
311      * used internally to send a sticky broadcast delayed.
312      */
313     private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
314
315     /**
316      * Used internally to
317      * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
318      */
319     private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
320
321     private static final int EVENT_VPN_STATE_CHANGED = 14;
322
323     /**
324      * Used internally to disable fail fast of mobile data
325      */
326     private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
327
328     /** Handler used for internal events. */
329     private InternalHandler mHandler;
330     /** Handler used for incoming {@link NetworkStateTracker} events. */
331     private NetworkStateTrackerHandler mTrackerHandler;
332
333     // list of DeathRecipients used to make sure features are turned off when
334     // a process dies
335     private List<FeatureUser> mFeatureUsers;
336
337     private boolean mSystemReady;
338     private Intent mInitialBroadcast;
339
340     private PowerManager.WakeLock mNetTransitionWakeLock;
341     private String mNetTransitionWakeLockCausedBy = "";
342     private int mNetTransitionWakeLockSerialNumber;
343     private int mNetTransitionWakeLockTimeout;
344
345     private InetAddress mDefaultDns;
346
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>();
350
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;
354
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;
359
360     // track the global proxy.
361     private ProxyProperties mGlobalProxy = null;
362
363     private SettingsObserver mSettingsObserver;
364
365     NetworkConfig[] mNetConfigs;
366     int mNetworksDefined;
367
368     private static class RadioAttributes {
369         public int mSimultaneity;
370         public int mType;
371         public RadioAttributes(String init) {
372             String fragments[] = init.split(",");
373             mType = Integer.parseInt(fragments[0]);
374             mSimultaneity = Integer.parseInt(fragments[1]);
375         }
376     }
377     RadioAttributes[] mRadioAttributes;
378
379     // the set of network types that can only be enabled by system/sig apps
380     List mProtectedNetworks;
381
382     private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
383
384     TelephonyManager mTelephonyManager;
385
386     // We only want one checkMobileProvisioning after booting.
387     volatile boolean mFirstProvisioningCheckStarted = false;
388
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);
394     }
395
396     public ConnectivityService(Context context, INetworkManagementService netManager,
397             INetworkStatsService statsService, INetworkPolicyManager policyManager,
398             NetworkFactory netFactory) {
399         if (DBG) log("ConnectivityService starting up");
400
401         HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
402         handlerThread.start();
403         mHandler = new InternalHandler(handlerThread.getLooper());
404         mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
405
406         if (netFactory == null) {
407             netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
408         }
409
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);
417             }
418         }
419
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);
426         }
427         try {
428             mDefaultDns = NetworkUtils.numericToInetAddress(dns);
429         } catch (IllegalArgumentException e) {
430             loge("Error setting defaultDns using " + dns);
431         }
432
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);
438
439         try {
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());
444         }
445
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);
451
452         mNetTrackers = new NetworkStateTracker[
453                 ConnectivityManager.MAX_NETWORK_TYPE+1];
454         mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
455
456         mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
457         mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
458
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);
466                 continue;
467             }
468             if (mRadioAttributes[r.mType] != null) {
469                 loge("Error in radioAttributes - ignoring attempt to redefine type " +
470                         r.mType);
471                 continue;
472             }
473             mRadioAttributes[r.mType] = r;
474         }
475
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) {
482             try {
483                 NetworkConfig n = new NetworkConfig(naString);
484                 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
485                     loge("Error in networkAttributes - ignoring attempt to define type " +
486                             n.type);
487                     continue;
488                 }
489                 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
490                     log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
491                             n.type);
492                     continue;
493                 }
494                 if (mNetConfigs[n.type] != null) {
495                     loge("Error in networkAttributes - ignoring attempt to redefine type " +
496                             n.type);
497                     continue;
498                 }
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);
502                     continue;
503                 }
504                 mNetConfigs[n.type] = n;
505                 mNetworksDefined++;
506             } catch(Exception e) {
507                 // ignore it - leave the entry null
508             }
509         }
510
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);
517             } else {
518                 if (DBG) loge("Ignoring protectedNetwork " + p);
519             }
520         }
521
522         // high priority first
523         mPriorityList = new int[mNetworksDefined];
524         {
525             int insertionPoint = mNetworksDefined-1;
526             int currentLowest = 0;
527             int nextLowest = 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;
535                         }
536                         continue;
537                     }
538                     mPriorityList[insertionPoint--] = na.type;
539                 }
540                 currentLowest = nextLowest;
541                 nextLowest = 0;
542             }
543         }
544
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;
551                     break;
552                 }
553             }
554             if (mNetworkPreference == -1) {
555                 throw new IllegalStateException(
556                         "You should set at least one default Network in config.xml!");
557             }
558         }
559
560         mNetRequestersPids =
561                 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
562         for (int i : mPriorityList) {
563             mNetRequestersPids[i] = new ArrayList<Integer>();
564         }
565
566         mFeatureUsers = new ArrayList<FeatureUser>();
567
568         mTestMode = SystemProperties.get("cm.test.mode").equals("true")
569                 && SystemProperties.get("ro.build.type").equals("eng");
570
571         // Create and start trackers for hard-coded networks
572         for (int targetNetworkType : mPriorityList) {
573             final NetworkConfig config = mNetConfigs[targetNetworkType];
574             final NetworkStateTracker tracker;
575             try {
576                 tracker = netFactory.createTracker(targetNetworkType, config);
577                 mNetTrackers[targetNetworkType] = tracker;
578             } catch (IllegalArgumentException e) {
579                 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
580                         + " tracker: " + e);
581                 continue;
582             }
583
584             tracker.startMonitoring(context, mTrackerHandler);
585             if (config.isDefault()) {
586                 tracker.reconnect();
587             }
588         }
589
590         mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
591
592         mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
593         mVpn.startMonitoring(mContext, mTrackerHandler);
594
595         mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
596
597         try {
598             mNetd.registerObserver(mTethering);
599             mNetd.registerObserver(mDataActivityObserver);
600             mNetd.registerObserver(mClat);
601         } catch (RemoteException e) {
602             loge("Error registering observer :" + e);
603         }
604
605         if (DBG) {
606             mInetLog = new ArrayList();
607         }
608
609         mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
610         mSettingsObserver.observe(mContext);
611
612         mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
613         loadGlobalProxy();
614     }
615
616     /**
617      * Factory that creates {@link NetworkStateTracker} instances using given
618      * {@link NetworkConfig}.
619      */
620     public interface NetworkFactory {
621         public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
622     }
623
624     private static class DefaultNetworkFactory implements NetworkFactory {
625         private final Context mContext;
626         private final Handler mTrackerHandler;
627
628         public DefaultNetworkFactory(Context context, Handler trackerHandler) {
629             mContext = context;
630             mTrackerHandler = trackerHandler;
631         }
632
633         @Override
634         public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
635             switch (config.radio) {
636                 case TYPE_WIFI:
637                     return new WifiStateTracker(targetNetworkType, config.name);
638                 case TYPE_MOBILE:
639                     return new MobileDataStateTracker(targetNetworkType, config.name);
640                 case TYPE_DUMMY:
641                     return new DummyDataStateTracker(targetNetworkType, config.name);
642                 case TYPE_BLUETOOTH:
643                     return BluetoothTetheringDataTracker.getInstance();
644                 case TYPE_WIMAX:
645                     return makeWimaxStateTracker(mContext, mTrackerHandler);
646                 case TYPE_ETHERNET:
647                     return EthernetDataTracker.getInstance();
648                 default:
649                     throw new IllegalArgumentException(
650                             "Trying to create a NetworkStateTracker for an unknown radio type: "
651                             + config.radio);
652             }
653         }
654     }
655
656     /**
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)}.
660      */
661     private static NetworkStateTracker makeWimaxStateTracker(
662             Context context, Handler trackerHandler) {
663         // Initialize Wimax
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;
673
674         NetworkStateTracker wimaxStateTracker = null;
675
676         boolean isWimaxEnabled = context.getResources().getBoolean(
677                 com.android.internal.R.bool.config_wimaxEnabled);
678
679         if (isWimaxEnabled) {
680             try {
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);
691
692                 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
693                 wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
694                         new ContextWrapper(context).getCacheDir().getAbsolutePath(),
695                         wimaxLibLocation, ClassLoader.getSystemClassLoader());
696
697                 try {
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());
703                     return null;
704                 }
705             } catch(Resources.NotFoundException ex) {
706                 loge("Wimax Resources does not exist!!! ");
707                 return null;
708             }
709
710             try {
711                 if (DBG) log("Starting Wimax Service... ");
712
713                 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
714                         (new Class[] {Context.class, Handler.class});
715                 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
716                         context, trackerHandler);
717
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);
723
724                 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
725
726             } catch(Exception ex) {
727                 loge("Exception creating Wimax classes: " + ex.toString());
728                 return null;
729             }
730         } else {
731             loge("Wimax is not enabled or not added to the network attributes!!! ");
732             return null;
733         }
734
735         return wimaxStateTracker;
736     }
737
738     /**
739      * Sets the preferred network.
740      * @param preference the new preference
741      */
742     public void setNetworkPreference(int preference) {
743         enforceChangePermission();
744
745         mHandler.sendMessage(
746                 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
747     }
748
749     public int getNetworkPreference() {
750         enforceAccessPermission();
751         int preference;
752         synchronized(this) {
753             preference = mNetworkPreference;
754         }
755         return preference;
756     }
757
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);
765                 synchronized(this) {
766                     mNetworkPreference = preference;
767                 }
768                 enforcePreference();
769             }
770         }
771     }
772
773     private int getConnectivityChangeDelay() {
774         final ContentResolver cr = mContext.getContentResolver();
775
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,
781                 defaultDelay);
782     }
783
784     private int getPersistedNetworkPreference() {
785         final ContentResolver cr = mContext.getContentResolver();
786
787         final int networkPrefSetting = Settings.Global
788                 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
789
790         return networkPrefSetting;
791     }
792
793     /**
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)}).
799      */
800     private void enforcePreference() {
801         if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
802             return;
803
804         if (!mNetTrackers[mNetworkPreference].isAvailable())
805             return;
806
807         for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
808             if (t != mNetworkPreference && mNetTrackers[t] != null &&
809                     mNetTrackers[t].getNetworkInfo().isConnected()) {
810                 if (DBG) {
811                     log("tearing down " + mNetTrackers[t].getNetworkInfo() +
812                             " in enforcePreference");
813                 }
814                 teardown(mNetTrackers[t]);
815             }
816         }
817     }
818
819     private boolean teardown(NetworkStateTracker netTracker) {
820         if (netTracker.teardown()) {
821             netTracker.setTeardownRequested(true);
822             return true;
823         } else {
824             return false;
825         }
826     }
827
828     /**
829      * Check if UID should be blocked from using the network represented by the
830      * given {@link NetworkStateTracker}.
831      */
832     private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
833         final String iface = tracker.getLinkProperties().getInterfaceName();
834
835         final boolean networkCostly;
836         final int uidRules;
837         synchronized (mRulesLock) {
838             networkCostly = mMeteredIfaces.contains(iface);
839             uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
840         }
841
842         if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
843             return true;
844         }
845
846         // no restrictive rules; network is visible
847         return false;
848     }
849
850     /**
851      * Return a filtered {@link NetworkInfo}, potentially marked
852      * {@link DetailedState#BLOCKED} based on
853      * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
854      */
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);
861         }
862         if (mLockdownTracker != null) {
863             info = mLockdownTracker.augmentNetworkInfo(info);
864         }
865         return info;
866     }
867
868     /**
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
873      * active
874      */
875     @Override
876     public NetworkInfo getActiveNetworkInfo() {
877         enforceAccessPermission();
878         final int uid = Binder.getCallingUid();
879         return getNetworkInfo(mActiveDefaultNetwork, uid);
880     }
881
882     public NetworkInfo getActiveNetworkInfoUnfiltered() {
883         enforceAccessPermission();
884         if (isNetworkTypeValid(mActiveDefaultNetwork)) {
885             final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
886             if (tracker != null) {
887                 return tracker.getNetworkInfo();
888             }
889         }
890         return null;
891     }
892
893     @Override
894     public NetworkInfo getActiveNetworkInfoForUid(int uid) {
895         enforceConnectivityInternalPermission();
896         return getNetworkInfo(mActiveDefaultNetwork, uid);
897     }
898
899     @Override
900     public NetworkInfo getNetworkInfo(int networkType) {
901         enforceAccessPermission();
902         final int uid = Binder.getCallingUid();
903         return getNetworkInfo(networkType, uid);
904     }
905
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);
912             }
913         }
914         return info;
915     }
916
917     @Override
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));
926                 }
927             }
928         }
929         return result.toArray(new NetworkInfo[result.size()]);
930     }
931
932     @Override
933     public boolean isNetworkSupported(int networkType) {
934         enforceAccessPermission();
935         return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
936     }
937
938     /**
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
944      * none is active
945      */
946     @Override
947     public LinkProperties getActiveLinkProperties() {
948         return getLinkProperties(mActiveDefaultNetwork);
949     }
950
951     @Override
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();
958             }
959         }
960         return null;
961     }
962
963     @Override
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()));
974                 }
975             }
976         }
977         return result.toArray(new NetworkState[result.size()]);
978     }
979
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());
986             }
987         }
988         return null;
989     }
990
991     @Override
992     public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
993         enforceAccessPermission();
994
995         final long token = Binder.clearCallingIdentity();
996         try {
997             final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
998             if (state != null) {
999                 try {
1000                     return mPolicyManager.getNetworkQuotaInfo(state);
1001                 } catch (RemoteException e) {
1002                 }
1003             }
1004             return null;
1005         } finally {
1006             Binder.restoreCallingIdentity(token);
1007         }
1008     }
1009
1010     @Override
1011     public boolean isActiveNetworkMetered() {
1012         enforceAccessPermission();
1013         final long token = Binder.clearCallingIdentity();
1014         try {
1015             return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1016         } finally {
1017             Binder.restoreCallingIdentity(token);
1018         }
1019     }
1020
1021     private boolean isNetworkMeteredUnchecked(int networkType) {
1022         final NetworkState state = getNetworkStateUnchecked(networkType);
1023         if (state != null) {
1024             try {
1025                 return mPolicyManager.isNetworkMetered(state);
1026             } catch (RemoteException e) {
1027             }
1028         }
1029         return false;
1030     }
1031
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;
1037         }
1038         return result;
1039     }
1040
1041     public boolean setRadio(int netType, boolean turnOn) {
1042         enforceChangePermission();
1043         if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1044             return false;
1045         }
1046         NetworkStateTracker tracker = mNetTrackers[netType];
1047         return tracker != null && tracker.setRadio(turnOn);
1048     }
1049
1050     private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1051         @Override
1052         public void interfaceClassDataActivityChanged(String label, boolean active) {
1053             int deviceType = Integer.parseInt(label);
1054             sendDataActivityBroadcast(deviceType, active);
1055         }
1056     };
1057
1058     /**
1059      * Used to notice when the calling process dies so we can self-expire
1060      *
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.
1063      *
1064      */
1065     private class FeatureUser implements IBinder.DeathRecipient {
1066         int mNetworkType;
1067         String mFeature;
1068         IBinder mBinder;
1069         int mPid;
1070         int mUid;
1071         long mCreateTime;
1072
1073         FeatureUser(int type, String feature, IBinder binder) {
1074             super();
1075             mNetworkType = type;
1076             mFeature = feature;
1077             mBinder = binder;
1078             mPid = getCallingPid();
1079             mUid = getCallingUid();
1080             mCreateTime = System.currentTimeMillis();
1081
1082             try {
1083                 mBinder.linkToDeath(this, 0);
1084             } catch (RemoteException e) {
1085                 binderDied();
1086             }
1087         }
1088
1089         void unlinkDeathRecipient() {
1090             mBinder.unlinkToDeath(this, 0);
1091         }
1092
1093         public void binderDied() {
1094             log("ConnectivityService FeatureUser binderDied(" +
1095                     mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1096                     (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1097             stopUsingNetworkFeature(this, false);
1098         }
1099
1100         public void expire() {
1101             if (VDBG) {
1102                 log("ConnectivityService FeatureUser expire(" +
1103                         mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1104                         (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1105             }
1106             stopUsingNetworkFeature(this, false);
1107         }
1108
1109         public boolean isSameUser(FeatureUser u) {
1110             if (u == null) return false;
1111
1112             return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1113         }
1114
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)) {
1118                 return true;
1119             }
1120             return false;
1121         }
1122
1123         public String toString() {
1124             return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1125                     (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1126         }
1127     }
1128
1129     // javadoc from interface
1130     public int startUsingNetworkFeature(int networkType, String feature,
1131             IBinder binder) {
1132         long startTime = 0;
1133         if (DBG) {
1134             startTime = SystemClock.elapsedRealtime();
1135         }
1136         if (VDBG) {
1137             log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1138                     + Binder.getCallingUid());
1139         }
1140         enforceChangePermission();
1141         try {
1142             if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1143                     mNetConfigs[networkType] == null) {
1144                 return PhoneConstants.APN_REQUEST_FAILED;
1145             }
1146
1147             FeatureUser f = new FeatureUser(networkType, feature, binder);
1148
1149             // TODO - move this into individual networktrackers
1150             int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1151
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;
1156             }
1157
1158             if (mProtectedNetworks.contains(usedNetworkType)) {
1159                 enforceConnectivityInternalPermission();
1160             }
1161
1162             // if UID is restricted, don't allow them to bring up metered APNs
1163             final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1164             final int uidRules;
1165             synchronized (mRulesLock) {
1166                 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1167             }
1168             if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1169                 return PhoneConstants.APN_REQUEST_FAILED;
1170             }
1171
1172             NetworkStateTracker network = mNetTrackers[usedNetworkType];
1173             if (network != null) {
1174                 Integer currentPid = new Integer(getCallingPid());
1175                 if (usedNetworkType != networkType) {
1176                     NetworkInfo ni = network.getNetworkInfo();
1177
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;
1182                         } else {
1183                             // else make the attempt anyway - probably giving REQUEST_STARTED below
1184                             if (DBG) {
1185                                 log("special network not available, but try anyway ni=" +
1186                                         ni.getTypeName());
1187                             }
1188                         }
1189                     }
1190
1191                     int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1192
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.
1201                                     addToList = false;
1202                                     break;
1203                                 }
1204                             }
1205                         }
1206
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);
1211                         }
1212                     }
1213
1214                     if (restoreTimer >= 0) {
1215                         mHandler.sendMessageDelayed(mHandler.obtainMessage(
1216                                 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1217                     }
1218
1219                     if ((ni.isConnectedOrConnecting() == true) &&
1220                             !network.isTeardownRequested()) {
1221                         if (ni.isConnected() == true) {
1222                             final long token = Binder.clearCallingIdentity();
1223                             try {
1224                                 // add the pid-specific dns
1225                                 handleDnsConfigurationChange(usedNetworkType);
1226                                 if (VDBG) log("special network already active");
1227                             } finally {
1228                                 Binder.restoreCallingIdentity(token);
1229                             }
1230                             return PhoneConstants.APN_ALREADY_ACTIVE;
1231                         }
1232                         if (VDBG) log("special network already connecting");
1233                         return PhoneConstants.APN_REQUEST_STARTED;
1234                     }
1235
1236                     // check if the radio in play can make another contact
1237                     // assume if cannot for now
1238
1239                     if (DBG) {
1240                         log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1241                                 feature);
1242                     }
1243                     if (network.reconnect()) {
1244                         return PhoneConstants.APN_REQUEST_STARTED;
1245                     } else {
1246                         return PhoneConstants.APN_REQUEST_FAILED;
1247                     }
1248                 } else {
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);
1255                         }
1256                     }
1257                     return -1;
1258                 }
1259             }
1260             return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1261          } finally {
1262             if (DBG) {
1263                 final long execTime = SystemClock.elapsedRealtime() - startTime;
1264                 if (execTime > 250) {
1265                     loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1266                 } else {
1267                     if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1268                 }
1269             }
1270          }
1271     }
1272
1273     // javadoc from interface
1274     public int stopUsingNetworkFeature(int networkType, String feature) {
1275         enforceChangePermission();
1276
1277         int pid = getCallingPid();
1278         int uid = getCallingUid();
1279
1280         FeatureUser u = null;
1281         boolean found = false;
1282
1283         synchronized(this) {
1284             for (FeatureUser x : mFeatureUsers) {
1285                 if (x.isSameUser(pid, uid, networkType, feature)) {
1286                     u = x;
1287                     found = true;
1288                     break;
1289                 }
1290             }
1291         }
1292         if (found && u != null) {
1293             // stop regardless of how many other time this proc had called start
1294             return stopUsingNetworkFeature(u, true);
1295         } else {
1296             // none found!
1297             if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
1298             return 1;
1299         }
1300     }
1301
1302     private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1303         int networkType = u.mNetworkType;
1304         String feature = u.mFeature;
1305         int pid = u.mPid;
1306         int uid = u.mUid;
1307
1308         NetworkStateTracker tracker = null;
1309         boolean callTeardown = false;  // used to carry our decision outside of sync block
1310
1311         if (VDBG) {
1312             log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1313         }
1314
1315         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1316             if (DBG) {
1317                 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1318                         ", net is invalid");
1319             }
1320             return -1;
1321         }
1322
1323         // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1324         // sync block
1325         synchronized(this) {
1326             // check if this process still has an outstanding start request
1327             if (!mFeatureUsers.contains(u)) {
1328                 if (VDBG) {
1329                     log("stopUsingNetworkFeature: this process has no outstanding requests" +
1330                         ", ignoring");
1331                 }
1332                 return 1;
1333             }
1334             u.unlinkDeathRecipient();
1335             mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1336             // If we care about duplicate requests, check for that here.
1337             //
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");
1347                         return 1;
1348                     }
1349                 }
1350             }
1351
1352             // TODO - move to individual network trackers
1353             int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1354
1355             tracker =  mNetTrackers[usedNetworkType];
1356             if (tracker == null) {
1357                 if (DBG) {
1358                     log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1359                             " no known tracker for used net type " + usedNetworkType);
1360                 }
1361                 return -1;
1362             }
1363             if (usedNetworkType != networkType) {
1364                 Integer currentPid = new Integer(pid);
1365                 mNetRequestersPids[usedNetworkType].remove(currentPid);
1366
1367                 final long token = Binder.clearCallingIdentity();
1368                 try {
1369                     reassessPidDns(pid, true);
1370                 } finally {
1371                     Binder.restoreCallingIdentity(token);
1372                 }
1373                 flushVmDnsCache();
1374                 if (mNetRequestersPids[usedNetworkType].size() != 0) {
1375                     if (VDBG) {
1376                         log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1377                                 " others still using it");
1378                     }
1379                     return 1;
1380                 }
1381                 callTeardown = true;
1382             } else {
1383                 if (DBG) {
1384                     log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1385                             " not a known feature - dropping");
1386                 }
1387             }
1388         }
1389
1390         if (callTeardown) {
1391             if (DBG) {
1392                 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1393             }
1394             tracker.teardown();
1395             return 1;
1396         } else {
1397             return -1;
1398         }
1399     }
1400
1401     /**
1402      * @deprecated use requestRouteToHostAddress instead
1403      *
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
1409      * desired
1410      * @return {@code true} on success, {@code false} on failure
1411      */
1412     public boolean requestRouteToHost(int networkType, int hostAddress) {
1413         InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1414
1415         if (inetAddress == null) {
1416             return false;
1417         }
1418
1419         return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1420     }
1421
1422     /**
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
1428      * desired
1429      * @return {@code true} on success, {@code false} on failure
1430      */
1431     public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1432         enforceChangePermission();
1433         if (mProtectedNetworks.contains(networkType)) {
1434             enforceConnectivityInternalPermission();
1435         }
1436
1437         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1438             if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1439             return false;
1440         }
1441         NetworkStateTracker tracker = mNetTrackers[networkType];
1442         DetailedState netState = tracker.getNetworkInfo().getDetailedState();
1443
1444         if (tracker == null || (netState != DetailedState.CONNECTED &&
1445                 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1446                 tracker.isTeardownRequested()) {
1447             if (VDBG) {
1448                 log("requestRouteToHostAddress on down network "
1449                         + "(" + networkType + ") - dropped"
1450                         + " tracker=" + tracker
1451                         + " netState=" + netState
1452                         + " isTeardownRequested="
1453                             + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
1454             }
1455             return false;
1456         }
1457         final long token = Binder.clearCallingIdentity();
1458         try {
1459             InetAddress addr = InetAddress.getByAddress(hostAddress);
1460             LinkProperties lp = tracker.getLinkProperties();
1461             boolean ok = addRouteToAddress(lp, addr);
1462             if (DBG) log("requestRouteToHostAddress ok=" + ok);
1463             return ok;
1464         } catch (UnknownHostException e) {
1465             if (DBG) log("requestRouteToHostAddress got " + e.toString());
1466         } finally {
1467             Binder.restoreCallingIdentity(token);
1468         }
1469         if (DBG) log("requestRouteToHostAddress X bottom return false");
1470         return false;
1471     }
1472
1473     private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1474         return modifyRoute(p, r, 0, ADD, toDefaultTable);
1475     }
1476
1477     private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1478         return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
1479     }
1480
1481     private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1482         return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
1483     }
1484
1485     private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1486         return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
1487     }
1488
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());
1494         } else {
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);
1499             } else {
1500                 // if we will connect to this through another route, add a direct route
1501                 // to it's gateway
1502                 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1503             }
1504         }
1505         return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
1506     }
1507
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);
1512             return false;
1513         }
1514
1515         if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1516             loge("Error modifying route - too much recursion");
1517             return false;
1518         }
1519
1520         String ifaceName = r.getInterface();
1521         if(ifaceName == null) {
1522             loge("Error modifying route - no interface name");
1523             return false;
1524         }
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);
1531                 } else {
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(),
1536                                                         ifaceName);
1537                 }
1538                 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
1539             }
1540         }
1541         if (doAdd) {
1542             if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1543             try {
1544                 if (toDefaultTable) {
1545                     mAddedRoutes.add(r);  // only track default table - only one apps can effect
1546                     mNetd.addRoute(ifaceName, r);
1547                 } else {
1548                     mNetd.addSecondaryRoute(ifaceName, r);
1549                 }
1550             } catch (Exception e) {
1551                 // never crash - catch them all
1552                 if (DBG) loge("Exception trying to add a route: " + e);
1553                 return false;
1554             }
1555         } else {
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);
1562                     try {
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);
1567                         return false;
1568                     }
1569                 } else {
1570                     if (VDBG) log("not removing " + r + " as it's still in use");
1571                 }
1572             } else {
1573                 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1574                 try {
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);
1579                     return false;
1580                 }
1581             }
1582         }
1583         return true;
1584     }
1585
1586     /**
1587      * @see ConnectivityManager#getMobileDataEnabled()
1588      */
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
1592         //       asynchronous.
1593         enforceAccessPermission();
1594         boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1595                 Settings.Global.MOBILE_DATA, 1) == 1;
1596         if (VDBG) log("getMobileDataEnabled returning " + retVal);
1597         return retVal;
1598     }
1599
1600     public void setDataDependency(int networkType, boolean met) {
1601         enforceConnectivityInternalPermission();
1602
1603         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1604                 (met ? ENABLED : DISABLED), networkType));
1605     }
1606
1607     private void handleSetDependencyMet(int networkType, boolean met) {
1608         if (mNetTrackers[networkType] != null) {
1609             if (DBG) {
1610                 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1611             }
1612             mNetTrackers[networkType].setDependencyMet(met);
1613         }
1614     }
1615
1616     private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1617         @Override
1618         public void onUidRulesChanged(int uid, int uidRules) {
1619             // caller is NPMS, since we only register with them
1620             if (LOGD_RULES) {
1621                 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1622             }
1623
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;
1628
1629                 mUidRules.put(uid, uidRules);
1630             }
1631
1632             // TODO: notify UID when it has requested targeted updates
1633         }
1634
1635         @Override
1636         public void onMeteredIfacesChanged(String[] meteredIfaces) {
1637             // caller is NPMS, since we only register with them
1638             if (LOGD_RULES) {
1639                 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1640             }
1641
1642             synchronized (mRulesLock) {
1643                 mMeteredIfaces.clear();
1644                 for (String iface : meteredIfaces) {
1645                     mMeteredIfaces.add(iface);
1646                 }
1647             }
1648         }
1649
1650         @Override
1651         public void onRestrictBackgroundChanged(boolean restrictBackground) {
1652             // caller is NPMS, since we only register with them
1653             if (LOGD_RULES) {
1654                 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1655             }
1656
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);
1666                     }
1667                 }
1668             }
1669         }
1670     };
1671
1672     /**
1673      * @see ConnectivityManager#setMobileDataEnabled(boolean)
1674      */
1675     public void setMobileDataEnabled(boolean enabled) {
1676         enforceChangePermission();
1677         if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1678
1679         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1680                 (enabled ? ENABLED : DISABLED), 0));
1681     }
1682
1683     private void handleSetMobileData(boolean enabled) {
1684         if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1685             if (VDBG) {
1686                 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1687             }
1688             mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1689         }
1690         if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1691             if (VDBG) {
1692                 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1693             }
1694             mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1695         }
1696     }
1697
1698     @Override
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);
1702
1703         mHandler.sendMessage(mHandler.obtainMessage(
1704                 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1705     }
1706
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);
1712             }
1713         }
1714     }
1715
1716     private void enforceAccessPermission() {
1717         mContext.enforceCallingOrSelfPermission(
1718                 android.Manifest.permission.ACCESS_NETWORK_STATE,
1719                 "ConnectivityService");
1720     }
1721
1722     private void enforceChangePermission() {
1723         mContext.enforceCallingOrSelfPermission(
1724                 android.Manifest.permission.CHANGE_NETWORK_STATE,
1725                 "ConnectivityService");
1726     }
1727
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");
1733     }
1734
1735     private void enforceTetherAccessPermission() {
1736         mContext.enforceCallingOrSelfPermission(
1737                 android.Manifest.permission.ACCESS_NETWORK_STATE,
1738                 "ConnectivityService");
1739     }
1740
1741     private void enforceConnectivityInternalPermission() {
1742         mContext.enforceCallingOrSelfPermission(
1743                 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1744                 "ConnectivityService");
1745     }
1746
1747     /**
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
1753      */
1754     private void handleDisconnect(NetworkInfo info) {
1755
1756         int prevNetType = info.getType();
1757
1758         mNetTrackers[prevNetType].setTeardownRequested(false);
1759
1760         // Remove idletimer previously setup in {@code handleConnect}
1761         removeDataActivityTracking(prevNetType);
1762
1763         /*
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.
1768          */
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);
1776             }
1777         }
1778
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);
1785         }
1786         if (info.getReason() != null) {
1787             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1788         }
1789         if (info.getExtraInfo() != null) {
1790             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1791                     info.getExtraInfo());
1792         }
1793
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);
1799             } else {
1800                 mDefaultInetConditionPublished = 0; // we're not connected anymore
1801                 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1802             }
1803         }
1804         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1805
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())) {
1819                             doReset = false;
1820                             break;
1821                         }
1822                     }
1823                 }
1824             }
1825         }
1826
1827         // do this before we broadcast the change
1828         handleConnectivityChange(prevNetType, doReset);
1829
1830         final Intent immediateIntent = new Intent(intent);
1831         immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1832         sendStickyBroadcast(immediateIntent);
1833         sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1834         /*
1835          * If the failover network is already connected, then immediately send
1836          * out a followup broadcast indicating successful failover
1837          */
1838         if (mActiveDefaultNetwork != -1) {
1839             sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1840                     getConnectivityChangeDelay());
1841         }
1842     }
1843
1844     private void tryFailover(int prevNetType) {
1845         /*
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.
1849          */
1850         if (mNetConfigs[prevNetType].isDefault()) {
1851             if (mActiveDefaultNetwork == prevNetType) {
1852                 mActiveDefaultNetwork = -1;
1853             }
1854
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;
1861 //            }
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;
1867
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;
1877
1878 //                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1879
1880                 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1881                 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1882                 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1883                     checkInfo.setFailover(true);
1884                     checkTracker.reconnect();
1885                 }
1886                 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1887             }
1888         }
1889     }
1890
1891     public void sendConnectedBroadcast(NetworkInfo info) {
1892         enforceConnectivityInternalPermission();
1893         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1894         sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1895     }
1896
1897     private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1898         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1899         sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1900     }
1901
1902     private void sendInetConditionBroadcast(NetworkInfo info) {
1903         sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1904     }
1905
1906     private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1907         if (mLockdownTracker != null) {
1908             info = mLockdownTracker.augmentNetworkInfo(info);
1909         }
1910
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);
1917         }
1918         if (info.getReason() != null) {
1919             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1920         }
1921         if (info.getExtraInfo() != null) {
1922             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1923                     info.getExtraInfo());
1924         }
1925         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1926         return intent;
1927     }
1928
1929     private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1930         sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1931     }
1932
1933     private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1934         sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1935     }
1936
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();
1942         try {
1943             mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1944                     RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1945         } finally {
1946             Binder.restoreCallingIdentity(ident);
1947         }
1948     }
1949
1950     /**
1951      * Called when an attempt to fail over to another network has failed.
1952      * @param info the {@link NetworkInfo} for the failed network
1953      */
1954     private void handleConnectionFailure(NetworkInfo info) {
1955         mNetTrackers[info.getType()].setTeardownRequested(false);
1956
1957         String reason = info.getReason();
1958         String extraInfo = info.getExtraInfo();
1959
1960         String reasonText;
1961         if (reason == null) {
1962             reasonText = ".";
1963         } else {
1964             reasonText = " (" + reason + ").";
1965         }
1966         loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1967
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);
1973         }
1974         if (reason != null) {
1975             intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1976         }
1977         if (extraInfo != null) {
1978             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1979         }
1980         if (info.isFailover()) {
1981             intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1982             info.setFailover(false);
1983         }
1984
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);
1990             } else {
1991                 mDefaultInetConditionPublished = 0;
1992                 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1993             }
1994         }
1995
1996         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1997
1998         final Intent immediateIntent = new Intent(intent);
1999         immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2000         sendStickyBroadcast(immediateIntent);
2001         sendStickyBroadcast(intent);
2002         /*
2003          * If the failover network is already connected, then immediately send
2004          * out a followup broadcast indicating successful failover
2005          */
2006         if (mActiveDefaultNetwork != -1) {
2007             sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
2008         }
2009     }
2010
2011     private void sendStickyBroadcast(Intent intent) {
2012         synchronized(this) {
2013             if (!mSystemReady) {
2014                 mInitialBroadcast = new Intent(intent);
2015             }
2016             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2017             if (VDBG) {
2018                 log("sendStickyBroadcast: action=" + intent.getAction());
2019             }
2020
2021             final long ident = Binder.clearCallingIdentity();
2022             try {
2023                 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2024             } finally {
2025                 Binder.restoreCallingIdentity(ident);
2026             }
2027         }
2028     }
2029
2030     private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2031         if (delayMs <= 0) {
2032             sendStickyBroadcast(intent);
2033         } else {
2034             if (VDBG) {
2035                 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2036                         + intent.getAction());
2037             }
2038             mHandler.sendMessageDelayed(mHandler.obtainMessage(
2039                     EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2040         }
2041     }
2042
2043     void systemReady() {
2044         synchronized(this) {
2045             mSystemReady = true;
2046             if (mInitialBroadcast != null) {
2047                 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2048                 mInitialBroadcast = null;
2049             }
2050         }
2051         // load the global proxy at startup
2052         mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2053
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);
2059         }
2060     }
2061
2062     private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2063         @Override
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);
2069             }
2070         }
2071     };
2072
2073     private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2074         if ((type != mNetworkPreference &&
2075                     mNetConfigs[mActiveDefaultNetwork].priority >
2076                     mNetConfigs[type].priority) ||
2077                 mNetworkPreference == mActiveDefaultNetwork) return false;
2078         return true;
2079     }
2080
2081     private void handleConnect(NetworkInfo info) {
2082         final int newNetType = info.getType();
2083
2084         setupDataActivityTracking(newNetType);
2085
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();
2090
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];
2099                     if (DBG) {
2100                         log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2101                             " teardown");
2102                     }
2103                     if (!teardown(otherNet)) {
2104                         loge("Network declined teardown request");
2105                         teardown(thisNet);
2106                         return;
2107                     }
2108                 } else {
2109                        // don't accept this one
2110                         if (VDBG) {
2111                             log("Not broadcasting CONNECT_ACTION " +
2112                                 "to torn down network " + info.getTypeName());
2113                         }
2114                         teardown(thisNet);
2115                         return;
2116                 }
2117             }
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
2121                 // new network
2122                 if (mNetTransitionWakeLock.isHeld()) {
2123                     mHandler.sendMessageDelayed(mHandler.obtainMessage(
2124                             EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2125                             mNetTransitionWakeLockSerialNumber, 0),
2126                             1000);
2127                 }
2128             }
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
2132             // disconnected
2133             mDefaultInetConditionPublished = 0;
2134             mDefaultConnectionSequence++;
2135             mInetConditionChangeInFlight = false;
2136             // Don't do this - if we never sign in stay, grey
2137             //reportNetworkCondition(mActiveDefaultNetwork, 100);
2138         }
2139         thisNet.setTeardownRequested(false);
2140         updateNetworkSettings(thisNet);
2141         handleConnectivityChange(newNetType, false);
2142         sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2143
2144         // notify battery stats service about this network
2145         if (thisIface != null) {
2146             try {
2147                 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2148             } catch (RemoteException e) {
2149                 // ignored; service lives in system_server
2150             }
2151         }
2152     }
2153
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));
2163                     return;
2164                 } else {
2165                     if (DBG) log("Tear down low priority net " + info.getTypeName());
2166                     teardown(thisNet);
2167                     return;
2168                 }
2169             }
2170         }
2171
2172         thisNet.captivePortalCheckComplete();
2173     }
2174
2175     /** @hide */
2176     public void captivePortalCheckComplete(NetworkInfo info) {
2177         enforceConnectivityInternalPermission();
2178         mNetTrackers[info.getType()].captivePortalCheckComplete();
2179     }
2180
2181     /**
2182      * Setup data activity tracking for the given network interface.
2183      *
2184      * Every {@code setupDataActivityTracking} should be paired with a
2185      * {@link removeDataActivityTracking} for cleanup.
2186      */
2187     private void setupDataActivityTracking(int type) {
2188         final NetworkStateTracker thisNet = mNetTrackers[type];
2189         final String iface = thisNet.getLinkProperties().getInterfaceName();
2190
2191         final int timeout;
2192
2193         if (ConnectivityManager.isNetworkTypeMobile(type)) {
2194             timeout = Settings.Global.getInt(mContext.getContentResolver(),
2195                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2196                                              0);
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,
2202                                              0);
2203         } else {
2204             // do not track any other networks
2205             timeout = 0;
2206         }
2207
2208         if (timeout > 0 && iface != null) {
2209             try {
2210                 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2211             } catch (RemoteException e) {
2212             }
2213         }
2214     }
2215
2216     /**
2217      * Remove data activity tracking when network disconnects.
2218      */
2219     private void removeDataActivityTracking(int type) {
2220         final NetworkStateTracker net = mNetTrackers[type];
2221         final String iface = net.getLinkProperties().getInterfaceName();
2222
2223         if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2224                               ConnectivityManager.TYPE_WIFI == type)) {
2225             try {
2226                 // the call fails silently if no idletimer setup for this interface
2227                 mNetd.removeIdleTimer(iface);
2228             } catch (RemoteException e) {
2229             }
2230         }
2231     }
2232
2233     /**
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.
2238      */
2239     private void handleConnectivityChange(int netType, boolean doReset) {
2240         int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2241
2242         /*
2243          * If a non-default network is enabled, add the host routes that
2244          * will allow it's DNS servers to be accessed.
2245          */
2246         handleDnsConfigurationChange(netType);
2247
2248         LinkProperties curLp = mCurrentLinkProperties[netType];
2249         LinkProperties newLp = null;
2250
2251         if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2252             newLp = mNetTrackers[netType].getLinkProperties();
2253             if (VDBG) {
2254                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2255                         " doReset=" + doReset + " resetMask=" + resetMask +
2256                         "\n   curLp=" + curLp +
2257                         "\n   newLp=" + newLp);
2258             }
2259
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;
2267                             }
2268                             if (linkAddr.getAddress() instanceof Inet6Address) {
2269                                 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2270                             }
2271                         }
2272                         if (DBG) {
2273                             log("handleConnectivityChange: addresses changed" +
2274                                     " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2275                                     "\n   car=" + car);
2276                         }
2277                     } else {
2278                         if (DBG) {
2279                             log("handleConnectivityChange: address are the same reset per doReset" +
2280                                    " linkProperty[" + netType + "]:" +
2281                                    " resetMask=" + resetMask);
2282                         }
2283                     }
2284                 } else {
2285                     resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2286                     if (DBG) {
2287                         log("handleConnectivityChange: interface not not equivalent reset both" +
2288                                 " linkProperty[" + netType + "]:" +
2289                                 " resetMask=" + resetMask);
2290                     }
2291                 }
2292             }
2293             if (mNetConfigs[netType].isDefault()) {
2294                 handleApplyDefaultProxy(newLp.getHttpProxy());
2295             }
2296         } else {
2297             if (VDBG) {
2298                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2299                         " doReset=" + doReset + " resetMask=" + resetMask +
2300                         "\n  curLp=" + curLp +
2301                         "\n  newLp= null");
2302             }
2303         }
2304         mCurrentLinkProperties[netType] = newLp;
2305         boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2306
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);
2314
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);
2319                             }
2320                         }
2321                         if (resetDns) {
2322                             flushVmDnsCache();
2323                             if (VDBG) log("resetting DNS cache for " + iface);
2324                             try {
2325                                 mNetd.flushInterfaceDnsCache(iface);
2326                             } catch (Exception e) {
2327                                 // never crash - catch them all
2328                                 if (DBG) loge("Exception resetting dns cache: " + e);
2329                             }
2330                         }
2331                     } else {
2332                         loge("Can't reset connection for type "+netType);
2333                     }
2334                 }
2335             }
2336         }
2337
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)) {
2347                 mClat.stopClat();
2348             }
2349             // If the link requires clat to be running, then start the daemon now.
2350             if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2351                 mClat.startClat(tracker);
2352             } else {
2353                 mClat.stopClat();
2354             }
2355         }
2356
2357         // TODO: Temporary notifying upstread change to Tethering.
2358         //       @see bug/4455071
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();
2364             }
2365         }
2366     }
2367
2368     /**
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
2371      * is a noop.
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
2375      */
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();
2388         }
2389
2390         boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2391
2392         for (RouteInfo r : routeDiff.removed) {
2393             if (isLinkDefault || ! r.isDefaultRoute()) {
2394                 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2395             }
2396             if (isLinkDefault == false) {
2397                 // remove from a secondary route table
2398                 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2399             }
2400         }
2401
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);
2409                     }
2410                 }
2411                 if (newLp != null) {
2412                     for (InetAddress newDns : newLp.getDnses()) {
2413                         addRouteToAddress(newLp, newDns);
2414                     }
2415                 }
2416             } else {
2417                 // no change in routes, check for change in dns themselves
2418                 for (InetAddress oldDns : dnsDiff.removed) {
2419                     removeRouteToAddress(curLp, oldDns);
2420                 }
2421                 for (InetAddress newDns : dnsDiff.added) {
2422                     addRouteToAddress(newLp, newDns);
2423                 }
2424             }
2425         }
2426
2427         for (RouteInfo r :  routeDiff.added) {
2428             if (isLinkDefault || ! r.isDefaultRoute()) {
2429                 addRoute(newLp, r, TO_DEFAULT_TABLE);
2430             } else {
2431                 // add to a secondary route table
2432                 addRoute(newLp, r, TO_SECONDARY_TABLE);
2433
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);
2439                     try {
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);
2444                     }
2445                 }
2446             }
2447         }
2448
2449         return routesChanged;
2450     }
2451
2452
2453    /**
2454      * Reads the network specific TCP buffer sizes from SystemProperties
2455      * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2456      * wide use
2457      */
2458    private void updateNetworkSettings(NetworkStateTracker nt) {
2459         String key = nt.getTcpBufferSizesPropName();
2460         String bufferSizes = key == null ? null : SystemProperties.get(key);
2461
2462         if (TextUtils.isEmpty(bufferSizes)) {
2463             if (VDBG) log(key + " not found in system properties. Using defaults");
2464
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);
2468         }
2469
2470         // Set values in kernel
2471         if (bufferSizes.length() != 0) {
2472             if (VDBG) {
2473                 log("Setting TCP values: [" + bufferSizes
2474                         + "] which comes from [" + key + "]");
2475             }
2476             setBufferSize(bufferSizes);
2477         }
2478     }
2479
2480    /**
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
2483      *
2484      * @param bufferSizes in the format of "readMin, readInitial, readMax,
2485      *        writeMin, writeInitial, writeMax"
2486      */
2487     private void setBufferSize(String bufferSizes) {
2488         try {
2489             String[] values = bufferSizes.split(",");
2490
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]);
2499             } else {
2500                 loge("Invalid buffersize string: " + bufferSizes);
2501             }
2502         } catch (IOException e) {
2503             loge("Can't set tcp buffer sizes:" + e);
2504         }
2505     }
2506
2507     /**
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
2511      */
2512     private void reassessPidDns(int pid, boolean doBump)
2513     {
2514         if (VDBG) log("reassessPidDns for pid " + pid);
2515         Integer myPid = new Integer(pid);
2516         for(int i : mPriorityList) {
2517             if (mNetConfigs[i].isDefault()) {
2518                 continue;
2519             }
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)) {
2526                     try {
2527                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2528                     } catch (Exception e) {
2529                         Slog.e(TAG, "exception reasseses pid dns: " + e);
2530                     }
2531                     return;
2532                 }
2533            }
2534         }
2535         // nothing found - delete
2536         try {
2537             mNetd.clearDnsInterfaceForPid(pid);
2538         } catch (Exception e) {
2539             Slog.e(TAG, "exception clear interface from pid: " + e);
2540         }
2541     }
2542
2543     private void flushVmDnsCache() {
2544         /*
2545          * Tell the VMs to toss their DNS caches
2546          */
2547         Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2548         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2549         /*
2550          * Connectivity events can happen before boot has completed ...
2551          */
2552         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2553         final long ident = Binder.clearCallingIdentity();
2554         try {
2555             mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2556         } finally {
2557             Binder.restoreCallingIdentity(ident);
2558         }
2559     }
2560
2561     // Caller must grab mDnsLock.
2562     private void updateDnsLocked(String network, String iface,
2563             Collection<InetAddress> dnses, String domains) {
2564         int last = 0;
2565         if (dnses.size() == 0 && mDefaultDns != null) {
2566             dnses = new ArrayList();
2567             dnses.add(mDefaultDns);
2568             if (DBG) {
2569                 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2570             }
2571         }
2572
2573         try {
2574             mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2575             mNetd.setDefaultInterfaceForDns(iface);
2576             for (InetAddress dns : dnses) {
2577                 ++last;
2578                 String key = "net.dns" + last;
2579                 String value = dns.getHostAddress();
2580                 SystemProperties.set(key, value);
2581             }
2582             for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2583                 String key = "net.dns" + i;
2584                 SystemProperties.set(key, "");
2585             }
2586             mNumDnsEntries = last;
2587         } catch (Exception e) {
2588             if (DBG) loge("exception setting default dns interface: " + e);
2589         }
2590     }
2591
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());
2604                     }
2605                 }
2606             } else {
2607                 try {
2608                     mNetd.setDnsServersForInterface(p.getInterfaceName(),
2609                             NetworkUtils.makeStrings(dnses), p.getDomains());
2610                 } catch (Exception e) {
2611                     if (DBG) loge("exception setting dns servers: " + e);
2612                 }
2613                 // set per-pid dns for attached secondary nets
2614                 List<Integer> pids = mNetRequestersPids[netType];
2615                 for (Integer pid : pids) {
2616                     try {
2617                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2618                     } catch (Exception e) {
2619                         Slog.e(TAG, "exception setting interface for pid: " + e);
2620                     }
2621                 }
2622             }
2623             flushVmDnsCache();
2624         }
2625     }
2626
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) {
2632             try {
2633                 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2634             } catch (NumberFormatException e) {
2635             }
2636         }
2637         // if the system property isn't set, use the value for the apn type
2638         int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2639
2640         if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2641                 (mNetConfigs[networkType] != null)) {
2642             ret = mNetConfigs[networkType].restoreTime;
2643         }
2644         return ret;
2645     }
2646
2647     @Override
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());
2656             return;
2657         }
2658
2659         // TODO: add locking to get atomic snapshot
2660         pw.println();
2661         for (int i = 0; i < mNetTrackers.length; i++) {
2662             final NetworkStateTracker nst = mNetTrackers[i];
2663             if (nst != null) {
2664                 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2665                 pw.increaseIndent();
2666                 if (nst.getNetworkInfo().isConnected()) {
2667                     pw.println("Active network: " + nst.getNetworkInfo().
2668                             getTypeName());
2669                 }
2670                 pw.println(nst.getNetworkInfo());
2671                 pw.println(nst.getLinkProperties());
2672                 pw.println(nst);
2673                 pw.println();
2674                 pw.decreaseIndent();
2675             }
2676         }
2677
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() + ", ";
2684             }
2685             pw.println(pidString);
2686         }
2687         pw.println();
2688         pw.decreaseIndent();
2689
2690         pw.println("FeatureUsers:");
2691         pw.increaseIndent();
2692         for (Object requester : mFeatureUsers) {
2693             pw.println(requester.toString());
2694         }
2695         pw.println();
2696         pw.decreaseIndent();
2697
2698         synchronized (this) {
2699             pw.println("NetworkTranstionWakeLock is currently " +
2700                     (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2701             pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2702         }
2703         pw.println();
2704
2705         mTethering.dump(fd, pw, args);
2706
2707         if (mInetLog != null) {
2708             pw.println();
2709             pw.println("Inet condition reports:");
2710             pw.increaseIndent();
2711             for(int i = 0; i < mInetLog.size(); i++) {
2712                 pw.println(mInetLog.get(i));
2713             }
2714             pw.decreaseIndent();
2715         }
2716     }
2717
2718     // must be stateless - things change under us.
2719     private class NetworkStateTrackerHandler extends Handler {
2720         public NetworkStateTrackerHandler(Looper looper) {
2721             super(looper);
2722         }
2723
2724         @Override
2725         public void handleMessage(Message msg) {
2726             NetworkInfo info;
2727             switch (msg.what) {
2728                 case NetworkStateTracker.EVENT_STATE_CHANGED:
2729                     info = (NetworkInfo) msg.obj;
2730                     int type = info.getType();
2731                     NetworkInfo.State state = info.getState();
2732
2733                     if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2734                             (state == NetworkInfo.State.DISCONNECTED)) {
2735                         log("ConnectivityChange for " +
2736                             info.getTypeName() + ": " +
2737                             state + "/" + info.getDetailedState());
2738                     }
2739
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);
2749                     }
2750
2751                     EventLogTags.writeConnectivityStateChanged(
2752                             info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2753
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);
2773                     }
2774                     if (mLockdownTracker != null) {
2775                         mLockdownTracker.onNetworkInfoChanged(info);
2776                     }
2777                     break;
2778                 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2779                     info = (NetworkInfo) msg.obj;
2780                     // TODO: Temporary allowing network configuration
2781                     //       change not resetting sockets.
2782                     //       @see bug/4455071
2783                     handleConnectivityChange(info.getType(), false);
2784                     break;
2785                 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2786                     info = (NetworkInfo) msg.obj;
2787                     type = info.getType();
2788                     updateNetworkSettings(mNetTrackers[type]);
2789                     break;
2790             }
2791         }
2792     }
2793
2794     private class InternalHandler extends Handler {
2795         public InternalHandler(Looper looper) {
2796             super(looper);
2797         }
2798
2799         @Override
2800         public void handleMessage(Message msg) {
2801             NetworkInfo info;
2802             switch (msg.what) {
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;
2810                         }
2811                     }
2812                     if (causedBy != null) {
2813                         log("NetTransition Wakelock for " + causedBy + " released by timeout");
2814                     }
2815                     break;
2816                 case EVENT_RESTORE_DEFAULT_NETWORK:
2817                     FeatureUser u = (FeatureUser)msg.obj;
2818                     u.expire();
2819                     break;
2820                 case EVENT_INET_CONDITION_CHANGE:
2821                 {
2822                     int netType = msg.arg1;
2823                     int condition = msg.arg2;
2824                     handleInetConditionChange(netType, condition);
2825                     break;
2826                 }
2827                 case EVENT_INET_CONDITION_HOLD_END:
2828                 {
2829                     int netType = msg.arg1;
2830                     int sequence = msg.arg2;
2831                     handleInetConditionHoldEnd(netType, sequence);
2832                     break;
2833                 }
2834                 case EVENT_SET_NETWORK_PREFERENCE:
2835                 {
2836                     int preference = msg.arg1;
2837                     handleSetNetworkPreference(preference);
2838                     break;
2839                 }
2840                 case EVENT_SET_MOBILE_DATA:
2841                 {
2842                     boolean enabled = (msg.arg1 == ENABLED);
2843                     handleSetMobileData(enabled);
2844                     break;
2845                 }
2846                 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2847                 {
2848                     handleDeprecatedGlobalHttpProxy();
2849                     break;
2850                 }
2851                 case EVENT_SET_DEPENDENCY_MET:
2852                 {
2853                     boolean met = (msg.arg1 == ENABLED);
2854                     handleSetDependencyMet(msg.arg2, met);
2855                     break;
2856                 }
2857                 case EVENT_RESTORE_DNS:
2858                 {
2859                     if (mActiveDefaultNetwork != -1) {
2860                         handleDnsConfigurationChange(mActiveDefaultNetwork);
2861                     }
2862                     break;
2863                 }
2864                 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2865                 {
2866                     Intent intent = (Intent)msg.obj;
2867                     sendStickyBroadcast(intent);
2868                     break;
2869                 }
2870                 case EVENT_SET_POLICY_DATA_ENABLE: {
2871                     final int networkType = msg.arg1;
2872                     final boolean enabled = msg.arg2 == ENABLED;
2873                     handleSetPolicyDataEnable(networkType, enabled);
2874                     break;
2875                 }
2876                 case EVENT_VPN_STATE_CHANGED: {
2877                     if (mLockdownTracker != null) {
2878                         mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2879                     }
2880                     break;
2881                 }
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);
2889                         }
2890                     } else {
2891                         log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2892                                 + " != tag:" + tag);
2893                     }
2894                 }
2895             }
2896         }
2897     }
2898
2899     // javadoc from interface
2900     public int tether(String iface) {
2901         enforceTetherChangePermission();
2902
2903         if (isTetheringSupported()) {
2904             return mTethering.tether(iface);
2905         } else {
2906             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2907         }
2908     }
2909
2910     // javadoc from interface
2911     public int untether(String iface) {
2912         enforceTetherChangePermission();
2913
2914         if (isTetheringSupported()) {
2915             return mTethering.untether(iface);
2916         } else {
2917             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2918         }
2919     }
2920
2921     // javadoc from interface
2922     public int getLastTetherError(String iface) {
2923         enforceTetherAccessPermission();
2924
2925         if (isTetheringSupported()) {
2926             return mTethering.getLastTetherError(iface);
2927         } else {
2928             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2929         }
2930     }
2931
2932     // TODO - proper iface API for selection by property, inspection, etc
2933     public String[] getTetherableUsbRegexs() {
2934         enforceTetherAccessPermission();
2935         if (isTetheringSupported()) {
2936             return mTethering.getTetherableUsbRegexs();
2937         } else {
2938             return new String[0];
2939         }
2940     }
2941
2942     public String[] getTetherableWifiRegexs() {
2943         enforceTetherAccessPermission();
2944         if (isTetheringSupported()) {
2945             return mTethering.getTetherableWifiRegexs();
2946         } else {
2947             return new String[0];
2948         }
2949     }
2950
2951     public String[] getTetherableBluetoothRegexs() {
2952         enforceTetherAccessPermission();
2953         if (isTetheringSupported()) {
2954             return mTethering.getTetherableBluetoothRegexs();
2955         } else {
2956             return new String[0];
2957         }
2958     }
2959
2960     public int setUsbTethering(boolean enable) {
2961         enforceTetherChangePermission();
2962         if (isTetheringSupported()) {
2963             return mTethering.setUsbTethering(enable);
2964         } else {
2965             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2966         }
2967     }
2968
2969     // TODO - move iface listing, queries, etc to new module
2970     // javadoc from interface
2971     public String[] getTetherableIfaces() {
2972         enforceTetherAccessPermission();
2973         return mTethering.getTetherableIfaces();
2974     }
2975
2976     public String[] getTetheredIfaces() {
2977         enforceTetherAccessPermission();
2978         return mTethering.getTetheredIfaces();
2979     }
2980
2981     @Override
2982     public String[] getTetheredIfacePairs() {
2983         enforceTetherAccessPermission();
2984         return mTethering.getTetheredIfacePairs();
2985     }
2986
2987     public String[] getTetheringErroredIfaces() {
2988         enforceTetherAccessPermission();
2989         return mTethering.getErroredIfaces();
2990     }
2991
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);
3004     }
3005
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;
3017         }
3018         mHandler.sendMessageDelayed(mHandler.obtainMessage(
3019                 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3020                 mNetTransitionWakeLockSerialNumber, 0),
3021                 mNetTransitionWakeLockTimeout);
3022         return;
3023     }
3024
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");
3031
3032         if (DBG) {
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();
3038             mInetLog.add(s);
3039             while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3040                 mInetLog.remove(0);
3041             }
3042         }
3043         mHandler.sendMessage(mHandler.obtainMessage(
3044             EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3045     }
3046
3047     private void handleInetConditionChange(int netType, int condition) {
3048         if (mActiveDefaultNetwork == -1) {
3049             if (DBG) log("handleInetConditionChange: no active default network - ignore");
3050             return;
3051         }
3052         if (mActiveDefaultNetwork != netType) {
3053             if (DBG) log("handleInetConditionChange: net=" + netType +
3054                             " != default=" + mActiveDefaultNetwork + " - ignore");
3055             return;
3056         }
3057         if (VDBG) {
3058             log("handleInetConditionChange: net=" +
3059                     netType + ", condition=" + condition +
3060                     ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3061         }
3062         mDefaultInetCondition = condition;
3063         int delay;
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);
3070             } else {
3071                 delay = Settings.Global.getInt(mContext.getContentResolver(),
3072                         Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3073             }
3074             mInetConditionChangeInFlight = true;
3075             mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3076                     mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3077         } else {
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");
3080         }
3081     }
3082
3083     private void handleInetConditionHoldEnd(int netType, int sequence) {
3084         if (DBG) {
3085             log("handleInetConditionHoldEnd: net=" + netType +
3086                     ", condition=" + mDefaultInetCondition +
3087                     ", published condition=" + mDefaultInetConditionPublished);
3088         }
3089         mInetConditionChangeInFlight = false;
3090
3091         if (mActiveDefaultNetwork == -1) {
3092             if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3093             return;
3094         }
3095         if (mDefaultConnectionSequence != sequence) {
3096             if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3097             return;
3098         }
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");
3104         //    return;
3105         //}
3106         NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3107         if (networkInfo.isConnected() == false) {
3108             if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3109             return;
3110         }
3111         mDefaultInetConditionPublished = mDefaultInetCondition;
3112         sendInetConditionBroadcast(networkInfo);
3113         return;
3114     }
3115
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);
3124         }
3125     }
3126
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;
3133
3134             String host = "";
3135             int port = 0;
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();
3142             } else {
3143                 mGlobalProxy = null;
3144             }
3145             ContentResolver res = mContext.getContentResolver();
3146             final long token = Binder.clearCallingIdentity();
3147             try {
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,
3151                         exclList);
3152             } finally {
3153                 Binder.restoreCallingIdentity(token);
3154             }
3155         }
3156
3157         if (mGlobalProxy == null) {
3158             proxyProperties = mDefaultProxy;
3159         }
3160         sendProxyBroadcast(proxyProperties);
3161     }
3162
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;
3173             }
3174         }
3175     }
3176
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;
3184         }
3185     }
3186
3187     private void handleApplyDefaultProxy(ProxyProperties proxy) {
3188         if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3189             proxy = null;
3190         }
3191         synchronized (mProxyLock) {
3192             if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3193             if (mDefaultProxy == proxy) return; // catches repeated nulls
3194             mDefaultProxy = proxy;
3195
3196             if (mGlobalProxy != null) return;
3197             if (!mDefaultProxyDisabled) {
3198                 sendProxyBroadcast(proxy);
3199             }
3200         }
3201     }
3202
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) {
3211                 try {
3212                     proxyPort = Integer.parseInt(data[1]);
3213                 } catch (NumberFormatException e) {
3214                     return;
3215                 }
3216             }
3217             ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3218             setGlobalProxy(p);
3219         }
3220     }
3221
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();
3230         try {
3231             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3232         } finally {
3233             Binder.restoreCallingIdentity(ident);
3234         }
3235     }
3236
3237     private static class SettingsObserver extends ContentObserver {
3238         private int mWhat;
3239         private Handler mHandler;
3240         SettingsObserver(Handler handler, int what) {
3241             super(handler);
3242             mHandler = handler;
3243             mWhat = what;
3244         }
3245
3246         void observe(Context context) {
3247             ContentResolver resolver = context.getContentResolver();
3248             resolver.registerContentObserver(Settings.Global.getUriFor(
3249                     Settings.Global.HTTP_PROXY), false, this);
3250         }
3251
3252         @Override
3253         public void onChange(boolean selfChange) {
3254             mHandler.obtainMessage(mWhat).sendToTarget();
3255         }
3256     }
3257
3258     private static void log(String s) {
3259         Slog.d(TAG, s);
3260     }
3261
3262     private static void loge(String s) {
3263         Slog.e(TAG, s);
3264     }
3265
3266     int convertFeatureToNetworkType(int networkType, String feature) {
3267         int usedNetworkType = networkType;
3268
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;
3285             } else {
3286                 Slog.e(TAG, "Can't match any mobile netTracker!");
3287             }
3288         } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3289             if (TextUtils.equals(feature, "p2p")) {
3290                 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3291             } else {
3292                 Slog.e(TAG, "Can't match any wifi netTracker!");
3293             }
3294         } else {
3295             Slog.e(TAG, "Unexpected network type");
3296         }
3297         return usedNetworkType;
3298     }
3299
3300     private static <T> T checkNotNull(T value, String message) {
3301         if (value == null) {
3302             throw new NullPointerException(message);
3303         }
3304         return value;
3305     }
3306
3307     /**
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.
3311      * @hide
3312      */
3313     @Override
3314     public boolean protectVpn(ParcelFileDescriptor socket) {
3315         throwIfLockdownEnabled();
3316         try {
3317             int type = mActiveDefaultNetwork;
3318             if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3319                 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3320                 return true;
3321             }
3322         } catch (Exception e) {
3323             // ignore
3324         } finally {
3325             try {
3326                 socket.close();
3327             } catch (Exception e) {
3328                 // ignore
3329             }
3330         }
3331         return false;
3332     }
3333
3334     /**
3335      * Prepare for a VPN application. This method is used by VpnDialogs
3336      * and not available in ConnectivityManager. Permissions are checked
3337      * in Vpn class.
3338      * @hide
3339      */
3340     @Override
3341     public boolean prepareVpn(String oldPackage, String newPackage) {
3342         throwIfLockdownEnabled();
3343         return mVpn.prepare(oldPackage, newPackage);
3344     }
3345
3346     /**
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
3350      * Vpn class.
3351      * @hide
3352      */
3353     @Override
3354     public ParcelFileDescriptor establishVpn(VpnConfig config) {
3355         throwIfLockdownEnabled();
3356         return mVpn.establish(config);
3357     }
3358
3359     /**
3360      * Start legacy VPN, controlling native daemons as needed. Creates a
3361      * secondary thread to perform connection work, returning quickly.
3362      */
3363     @Override
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");
3369         }
3370         mVpn.startLegacyVpn(profile, mKeyStore, egress);
3371     }
3372
3373     /**
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.
3377      * @hide
3378      */
3379     @Override
3380     public LegacyVpnInfo getLegacyVpnInfo() {
3381         throwIfLockdownEnabled();
3382         return mVpn.getLegacyVpnInfo();
3383     }
3384
3385     /**
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.
3394      */
3395     public class VpnCallback {
3396         private VpnCallback() {
3397         }
3398
3399         public void onStateChanged(NetworkInfo info) {
3400             mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3401         }
3402
3403         public void override(List<String> dnsServers, List<String> searchDomains) {
3404             if (dnsServers == null) {
3405                 restore();
3406                 return;
3407             }
3408
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.
3413                 try {
3414                     addresses.add(InetAddress.parseNumericAddress(address));
3415                 } catch (Exception e) {
3416                     // ignore
3417                 }
3418             }
3419             if (addresses.isEmpty()) {
3420                 restore();
3421                 return;
3422             }
3423
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(' ');
3429                 }
3430             }
3431             String domains = buffer.toString().trim();
3432
3433             // Apply DNS changes.
3434             synchronized (mDnsLock) {
3435                 updateDnsLocked("VPN", "VPN", addresses, domains);
3436                 mDnsOverridden = true;
3437             }
3438
3439             // Temporarily disable the default proxy (not global).
3440             synchronized (mProxyLock) {
3441                 mDefaultProxyDisabled = true;
3442                 if (mGlobalProxy == null && mDefaultProxy != null) {
3443                     sendProxyBroadcast(null);
3444                 }
3445             }
3446
3447             // TODO: support proxy per network.
3448         }
3449
3450         public void restore() {
3451             synchronized (mDnsLock) {
3452                 if (mDnsOverridden) {
3453                     mDnsOverridden = false;
3454                     mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3455                 }
3456             }
3457             synchronized (mProxyLock) {
3458                 mDefaultProxyDisabled = false;
3459                 if (mGlobalProxy == null && mDefaultProxy != null) {
3460                     sendProxyBroadcast(mDefaultProxy);
3461                 }
3462             }
3463         }
3464     }
3465
3466     @Override
3467     public boolean updateLockdownVpn() {
3468         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3469             Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3470             return false;
3471         }
3472
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");
3478                 return false;
3479             }
3480
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));
3485         } else {
3486             setLockdownTracker(null);
3487         }
3488
3489         return true;
3490     }
3491
3492     /**
3493      * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3494      * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3495      */
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();
3502         }
3503
3504         try {
3505             if (tracker != null) {
3506                 mNetd.setFirewallEnabled(true);
3507                 mNetd.setFirewallInterfaceRule("lo", true);
3508                 mLockdownTracker = tracker;
3509                 mLockdownTracker.init();
3510             } else {
3511                 mNetd.setFirewallEnabled(false);
3512             }
3513         } catch (RemoteException e) {
3514             // ignored; NMS lives inside system_server
3515         }
3516     }
3517
3518     private void throwIfLockdownEnabled() {
3519         if (mLockdownEnabled) {
3520             throw new IllegalStateException("Unavailable in lockdown mode");
3521         }
3522     }
3523
3524     public void supplyMessenger(int networkType, Messenger messenger) {
3525         enforceConnectivityInternalPermission();
3526
3527         if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3528             mNetTrackers[networkType].supplyMessenger(messenger);
3529         }
3530     }
3531
3532     public int findConnectionTypeForIface(String iface) {
3533         enforceConnectivityInternalPermission();
3534
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();
3541                 }
3542             }
3543         }
3544         return ConnectivityManager.TYPE_NONE;
3545     }
3546
3547     /**
3548      * Have mobile data fail fast if enabled.
3549      *
3550      * @param enabled DctConstants.ENABLED/DISABLED
3551      */
3552     private void setEnableFailFastMobileData(int enabled) {
3553         int tag;
3554
3555         if (enabled == DctConstants.ENABLED) {
3556             tag = mEnableFailFastMobileDataTag.incrementAndGet();
3557         } else {
3558             tag = mEnableFailFastMobileDataTag.get();
3559         }
3560         mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3561                          enabled));
3562     }
3563
3564     @Override
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();
3571
3572         mFirstProvisioningCheckStarted = true;
3573
3574         int timeOutMs = suggestedTimeOutMs;
3575         if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3576             timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3577         }
3578
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);
3585             }
3586             return timeOutMs;
3587         }
3588
3589         final long token = Binder.clearCallingIdentity();
3590         try {
3591             CheckMp checkMp = new CheckMp(mContext, this);
3592             CheckMp.CallBack cb = new CheckMp.CallBack() {
3593                 @Override
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);
3599                     }
3600                     NetworkInfo ni =
3601                             mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3602                     switch(result) {
3603                         case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3604                         case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3605                             log("CheckMp.onComplete: ignore, connected or no connection");
3606                             break;
3607                         }
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();
3613                             }
3614                             if (TextUtils.isEmpty(url) == false) {
3615                                 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3616                                 setNotificationVisible(true, ni, url);
3617                             } else {
3618                                 log("CheckMp.onComplete: warm sim (redirected), no url");
3619                             }
3620                             break;
3621                         }
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);
3628                             } else {
3629                                 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3630                             }
3631                             break;
3632                         }
3633                         default: {
3634                             loge("CheckMp.onComplete: ignore unexpected result=" + result);
3635                             break;
3636                         }
3637                     }
3638                 }
3639             };
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);
3645         } finally {
3646             Binder.restoreCallingIdentity(token);
3647             log("checkMobileProvisioning: X");
3648         }
3649         return timeOutMs;
3650     }
3651
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;
3661
3662         /**
3663          * Parameters for AsyncTask.execute
3664          */
3665         static class Params {
3666             private String mUrl;
3667             private long mTimeOutMs;
3668             private CallBack mCb;
3669
3670             Params(String url, long timeOutMs, CallBack cb) {
3671                 mUrl = url;
3672                 mTimeOutMs = timeOutMs;
3673                 mCb = cb;
3674             }
3675
3676             @Override
3677             public String toString() {
3678                 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3679             }
3680         }
3681
3682         /**
3683          * The call back object passed in Params. onComplete will be called
3684          * on the main thread.
3685          */
3686         abstract static class CallBack {
3687             // Called on the main thread.
3688             abstract void onComplete(Integer result);
3689         }
3690
3691         public CheckMp(Context context, ConnectivityService cs) {
3692             mContext = context;
3693             mCs = cs;
3694
3695             // Setup access to TelephonyService we'll be using.
3696             mTm = (TelephonyManager) mContext.getSystemService(
3697                     Context.TELEPHONY_SERVICE);
3698         }
3699
3700         /**
3701          * Get the default url to use for the test.
3702          */
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";
3709             }
3710             return "http://" + server + "/generate_204";
3711         }
3712
3713         /**
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.
3717          */
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();
3722             mParams = params;
3723
3724             try {
3725                 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3726                     log("isMobileOk: not mobile capable");
3727                     result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3728                     return result;
3729                 }
3730
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);
3735
3736                 // Continue trying to connect until time has run out
3737                 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3738
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");
3747                             break;
3748                     }
3749                     if (VDBG) log("isMobileOk: hipri not started yet");
3750                     result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3751                     sleep(1);
3752                 }
3753
3754                 // Continue trying to connect until time has run out
3755                 while(SystemClock.elapsedRealtime() < endTime) {
3756                     try {
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) {
3763                             if (VDBG) {
3764                                 log("isMobileOk: not connected ni=" +
3765                                     mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3766                             }
3767                             sleep(1);
3768                             result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3769                             continue;
3770                         }
3771
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;
3778                         try {
3779                             addresses = InetAddress.getAllByName(orgUri.getHost());
3780                         } catch (UnknownHostException e) {
3781                             log("isMobileOk: UnknownHostException");
3782                             result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3783                             return result;
3784                         }
3785                         log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3786
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);
3794
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);
3801                                 addrTried ++) {
3802
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
3808                                 validAddr += 1;
3809                             } else {
3810                                 // Invalid address so try next address
3811                                 continue;
3812                             }
3813
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 ??
3818                                 log("isMobileOk:"
3819                                         + " wait to establish route to hostAddr=" + hostAddr);
3820                                 sleep(3);
3821                             } else {
3822                                 log("isMobileOk:"
3823                                         + " could not establish route to hostAddr=" + hostAddr);
3824                                 continue;
3825                             }
3826
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);
3833
3834                             HttpURLConnection urlConn = null;
3835                             try {
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;
3848                                 } else {
3849                                     result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3850                                 }
3851                                 log("isMobileOk: connected responseCode=" + responseCode);
3852                                 urlConn.disconnect();
3853                                 urlConn = null;
3854                                 return result;
3855                             } catch (Exception e) {
3856                                 log("isMobileOk: HttpURLConnection Exception e=" + e);
3857                                 if (urlConn != null) {
3858                                     urlConn.disconnect();
3859                                     urlConn = null;
3860                                 }
3861                             }
3862                         }
3863                         result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3864                         log("isMobileOk: loops|timed out");
3865                         return result;
3866                     } catch (Exception e) {
3867                         log("isMobileOk: Exception e=" + e);
3868                         continue;
3869                     }
3870                 }
3871                 log("isMobileOk: timed out");
3872             } finally {
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);
3878             }
3879             return result;
3880         }
3881
3882         @Override
3883         protected Integer doInBackground(Params... params) {
3884             return isMobileOk(params[0]);
3885         }
3886
3887         @Override
3888         protected void onPostExecute(Integer result) {
3889             log("onPostExecute: result=" + result);
3890             if ((mParams != null) && (mParams.mCb != null)) {
3891                 mParams.mCb.onComplete(result);
3892             }
3893         }
3894
3895         private String inetAddressesToString(InetAddress[] addresses) {
3896             StringBuffer sb = new StringBuffer();
3897             boolean firstTime = true;
3898             for(InetAddress addr : addresses) {
3899                 if (firstTime) {
3900                     firstTime = false;
3901                 } else {
3902                     sb.append(",");
3903                 }
3904                 sb.append(addr);
3905             }
3906             return sb.toString();
3907         }
3908
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();
3915             if (ni != null) {
3916                 log("ni.length=" + ni.length);
3917                 for (NetworkInfo netInfo: ni) {
3918                     log("netInfo=" + netInfo.toString());
3919                 }
3920             } else {
3921                 log("no network info ni=null");
3922             }
3923         }
3924
3925         /**
3926          * Sleep for a few seconds then return.
3927          * @param seconds
3928          */
3929         private static void sleep(int seconds) {
3930             try {
3931                 Thread.sleep(seconds * 1000);
3932             } catch (InterruptedException e) {
3933                 e.printStackTrace();
3934             }
3935         }
3936
3937         public boolean hasIPv4Address(LinkProperties lp) {
3938             return lp.hasIPv4Address();
3939         }
3940
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) {
3945                 return true;
3946               }
3947             }
3948             return false;
3949         }
3950
3951         private void log(String s) {
3952             Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3953         }
3954     }
3955
3956     private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3957
3958     private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3959         log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3960
3961         Resources r = Resources.getSystem();
3962         NotificationManager notificationManager = (NotificationManager) mContext
3963             .getSystemService(Context.NOTIFICATION_SERVICE);
3964
3965         if (visible) {
3966             CharSequence title;
3967             CharSequence details;
3968             int icon;
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;
3976                     break;
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;
3985                     break;
3986                 default:
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;
3992                     break;
3993             }
3994
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);
4005
4006             log("setNotificaitionVisible: notify notificaiton=" + notification);
4007             notificationManager.notify(NOTIFICATION_ID, 1, notification);
4008         } else {
4009             log("setNotificaitionVisible: cancel");
4010             notificationManager.cancel(NOTIFICATION_ID, 1);
4011         }
4012         log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4013     }
4014
4015     /** Location to an updatable file listing carrier provisioning urls.
4016      *  An example:
4017      *
4018      * <?xml version="1.0" encoding="utf-8"?>
4019      *  <provisioningUrls>
4020      *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4021      *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4022      *  </provisioningUrls>
4023      */
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);
4027
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";
4038
4039     private static final int REDIRECTED_PROVISIONING = 1;
4040     private static final int PROVISIONING = 2;
4041
4042     private String getProvisioningUrlBaseFromFile(int type) {
4043         FileReader fileReader = null;
4044         XmlPullParser parser = null;
4045         Configuration config = mContext.getResources().getConfiguration();
4046         String tagType;
4047
4048         switch (type) {
4049             case PROVISIONING:
4050                 tagType = TAG_PROVISIONING_URL;
4051                 break;
4052             case REDIRECTED_PROVISIONING:
4053                 tagType = TAG_REDIRECTED_URL;
4054                 break;
4055             default:
4056                 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4057                         type);
4058         }
4059
4060         try {
4061             fileReader = new FileReader(mProvisioningUrlFile);
4062             parser = Xml.newPullParser();
4063             parser.setInput(fileReader);
4064             XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4065
4066             while (true) {
4067                 XmlUtils.nextElement(parser);
4068
4069                 String element = parser.getName();
4070                 if (element == null) break;
4071
4072                 if (element.equals(tagType)) {
4073                     String mcc = parser.getAttributeValue(null, ATTR_MCC);
4074                     try {
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) {
4078                                 parser.next();
4079                                 if (parser.getEventType() == XmlPullParser.TEXT) {
4080                                     return parser.getText();
4081                                 }
4082                             }
4083                         }
4084                     } catch (NumberFormatException e) {
4085                         loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4086                     }
4087                 }
4088             }
4089             return null;
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);
4096         } finally {
4097             if (fileReader != null) {
4098                 try {
4099                     fileReader.close();
4100                 } catch (IOException e) {}
4101             }
4102         }
4103         return null;
4104     }
4105
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);
4110         }
4111         return url;
4112     }
4113
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);
4120         } else {
4121             log("getProvisioningUrl: mobile_provisioning_url from File =" + url);
4122         }
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";
4128             }
4129             url = String.format(url,
4130                     mTelephonyManager.getSimSerialNumber() /* ICCID */,
4131                     mTelephonyManager.getDeviceId() /* IMEI */,
4132                     phoneNumber /* Phone numer */);
4133         }
4134
4135         return url;
4136     }
4137 }