OSDN Git Service

06708191d9e4a777f26d2e905e139cc98bf300a2
[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         if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
2173         thisNet.captivePortalCheckComplete();
2174     }
2175
2176     /** @hide */
2177     @Override
2178     public void captivePortalCheckComplete(NetworkInfo info) {
2179         enforceConnectivityInternalPermission();
2180         if (DBG) log("captivePortalCheckComplete: ni=" + info);
2181         mNetTrackers[info.getType()].captivePortalCheckComplete();
2182     }
2183
2184     /** @hide */
2185     @Override
2186     public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2187         enforceConnectivityInternalPermission();
2188         if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2189         mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2190     }
2191
2192     /**
2193      * Setup data activity tracking for the given network interface.
2194      *
2195      * Every {@code setupDataActivityTracking} should be paired with a
2196      * {@link removeDataActivityTracking} for cleanup.
2197      */
2198     private void setupDataActivityTracking(int type) {
2199         final NetworkStateTracker thisNet = mNetTrackers[type];
2200         final String iface = thisNet.getLinkProperties().getInterfaceName();
2201
2202         final int timeout;
2203
2204         if (ConnectivityManager.isNetworkTypeMobile(type)) {
2205             timeout = Settings.Global.getInt(mContext.getContentResolver(),
2206                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2207                                              0);
2208             // Canonicalize mobile network type
2209             type = ConnectivityManager.TYPE_MOBILE;
2210         } else if (ConnectivityManager.TYPE_WIFI == type) {
2211             timeout = Settings.Global.getInt(mContext.getContentResolver(),
2212                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2213                                              0);
2214         } else {
2215             // do not track any other networks
2216             timeout = 0;
2217         }
2218
2219         if (timeout > 0 && iface != null) {
2220             try {
2221                 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2222             } catch (RemoteException e) {
2223             }
2224         }
2225     }
2226
2227     /**
2228      * Remove data activity tracking when network disconnects.
2229      */
2230     private void removeDataActivityTracking(int type) {
2231         final NetworkStateTracker net = mNetTrackers[type];
2232         final String iface = net.getLinkProperties().getInterfaceName();
2233
2234         if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2235                               ConnectivityManager.TYPE_WIFI == type)) {
2236             try {
2237                 // the call fails silently if no idletimer setup for this interface
2238                 mNetd.removeIdleTimer(iface);
2239             } catch (RemoteException e) {
2240             }
2241         }
2242     }
2243
2244     /**
2245      * After a change in the connectivity state of a network. We're mainly
2246      * concerned with making sure that the list of DNS servers is set up
2247      * according to which networks are connected, and ensuring that the
2248      * right routing table entries exist.
2249      */
2250     private void handleConnectivityChange(int netType, boolean doReset) {
2251         int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2252
2253         /*
2254          * If a non-default network is enabled, add the host routes that
2255          * will allow it's DNS servers to be accessed.
2256          */
2257         handleDnsConfigurationChange(netType);
2258
2259         LinkProperties curLp = mCurrentLinkProperties[netType];
2260         LinkProperties newLp = null;
2261
2262         if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2263             newLp = mNetTrackers[netType].getLinkProperties();
2264             if (VDBG) {
2265                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2266                         " doReset=" + doReset + " resetMask=" + resetMask +
2267                         "\n   curLp=" + curLp +
2268                         "\n   newLp=" + newLp);
2269             }
2270
2271             if (curLp != null) {
2272                 if (curLp.isIdenticalInterfaceName(newLp)) {
2273                     CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2274                     if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2275                         for (LinkAddress linkAddr : car.removed) {
2276                             if (linkAddr.getAddress() instanceof Inet4Address) {
2277                                 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2278                             }
2279                             if (linkAddr.getAddress() instanceof Inet6Address) {
2280                                 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2281                             }
2282                         }
2283                         if (DBG) {
2284                             log("handleConnectivityChange: addresses changed" +
2285                                     " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2286                                     "\n   car=" + car);
2287                         }
2288                     } else {
2289                         if (DBG) {
2290                             log("handleConnectivityChange: address are the same reset per doReset" +
2291                                    " linkProperty[" + netType + "]:" +
2292                                    " resetMask=" + resetMask);
2293                         }
2294                     }
2295                 } else {
2296                     resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2297                     if (DBG) {
2298                         log("handleConnectivityChange: interface not not equivalent reset both" +
2299                                 " linkProperty[" + netType + "]:" +
2300                                 " resetMask=" + resetMask);
2301                     }
2302                 }
2303             }
2304             if (mNetConfigs[netType].isDefault()) {
2305                 handleApplyDefaultProxy(newLp.getHttpProxy());
2306             }
2307         } else {
2308             if (VDBG) {
2309                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2310                         " doReset=" + doReset + " resetMask=" + resetMask +
2311                         "\n  curLp=" + curLp +
2312                         "\n  newLp= null");
2313             }
2314         }
2315         mCurrentLinkProperties[netType] = newLp;
2316         boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2317
2318         if (resetMask != 0 || resetDns) {
2319             if (curLp != null) {
2320                 for (String iface : curLp.getAllInterfaceNames()) {
2321                     if (TextUtils.isEmpty(iface) == false) {
2322                         if (resetMask != 0) {
2323                             if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2324                             NetworkUtils.resetConnections(iface, resetMask);
2325
2326                             // Tell VPN the interface is down. It is a temporary
2327                             // but effective fix to make VPN aware of the change.
2328                             if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2329                                 mVpn.interfaceStatusChanged(iface, false);
2330                             }
2331                         }
2332                         if (resetDns) {
2333                             flushVmDnsCache();
2334                             if (VDBG) log("resetting DNS cache for " + iface);
2335                             try {
2336                                 mNetd.flushInterfaceDnsCache(iface);
2337                             } catch (Exception e) {
2338                                 // never crash - catch them all
2339                                 if (DBG) loge("Exception resetting dns cache: " + e);
2340                             }
2341                         }
2342                     } else {
2343                         loge("Can't reset connection for type "+netType);
2344                     }
2345                 }
2346             }
2347         }
2348
2349         // Update 464xlat state.
2350         NetworkStateTracker tracker = mNetTrackers[netType];
2351         if (mClat.requiresClat(netType, tracker)) {
2352             // If the connection was previously using clat, but is not using it now, stop the clat
2353             // daemon. Normally, this happens automatically when the connection disconnects, but if
2354             // the disconnect is not reported, or if the connection's LinkProperties changed for
2355             // some other reason (e.g., handoff changes the IP addresses on the link), it would
2356             // still be running. If it's not running, then stopping it is a no-op.
2357             if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2358                 mClat.stopClat();
2359             }
2360             // If the link requires clat to be running, then start the daemon now.
2361             if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2362                 mClat.startClat(tracker);
2363             } else {
2364                 mClat.stopClat();
2365             }
2366         }
2367
2368         // TODO: Temporary notifying upstread change to Tethering.
2369         //       @see bug/4455071
2370         /** Notify TetheringService if interface name has been changed. */
2371         if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2372                              PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2373             if (isTetheringSupported()) {
2374                 mTethering.handleTetherIfaceChange();
2375             }
2376         }
2377     }
2378
2379     /**
2380      * Add and remove routes using the old properties (null if not previously connected),
2381      * new properties (null if becoming disconnected).  May even be double null, which
2382      * is a noop.
2383      * Uses isLinkDefault to determine if default routes should be set or conversely if
2384      * host routes should be set to the dns servers
2385      * returns a boolean indicating the routes changed
2386      */
2387     private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2388             boolean isLinkDefault) {
2389         Collection<RouteInfo> routesToAdd = null;
2390         CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2391         CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2392         if (curLp != null) {
2393             // check for the delta between the current set and the new
2394             routeDiff = curLp.compareRoutes(newLp);
2395             dnsDiff = curLp.compareDnses(newLp);
2396         } else if (newLp != null) {
2397             routeDiff.added = newLp.getAllRoutes();
2398             dnsDiff.added = newLp.getDnses();
2399         }
2400
2401         boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2402
2403         for (RouteInfo r : routeDiff.removed) {
2404             if (isLinkDefault || ! r.isDefaultRoute()) {
2405                 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2406             }
2407             if (isLinkDefault == false) {
2408                 // remove from a secondary route table
2409                 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2410             }
2411         }
2412
2413         if (!isLinkDefault) {
2414             // handle DNS routes
2415             if (routesChanged) {
2416                 // routes changed - remove all old dns entries and add new
2417                 if (curLp != null) {
2418                     for (InetAddress oldDns : curLp.getDnses()) {
2419                         removeRouteToAddress(curLp, oldDns);
2420                     }
2421                 }
2422                 if (newLp != null) {
2423                     for (InetAddress newDns : newLp.getDnses()) {
2424                         addRouteToAddress(newLp, newDns);
2425                     }
2426                 }
2427             } else {
2428                 // no change in routes, check for change in dns themselves
2429                 for (InetAddress oldDns : dnsDiff.removed) {
2430                     removeRouteToAddress(curLp, oldDns);
2431                 }
2432                 for (InetAddress newDns : dnsDiff.added) {
2433                     addRouteToAddress(newLp, newDns);
2434                 }
2435             }
2436         }
2437
2438         for (RouteInfo r :  routeDiff.added) {
2439             if (isLinkDefault || ! r.isDefaultRoute()) {
2440                 addRoute(newLp, r, TO_DEFAULT_TABLE);
2441             } else {
2442                 // add to a secondary route table
2443                 addRoute(newLp, r, TO_SECONDARY_TABLE);
2444
2445                 // many radios add a default route even when we don't want one.
2446                 // remove the default route unless somebody else has asked for it
2447                 String ifaceName = newLp.getInterfaceName();
2448                 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2449                     if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2450                     try {
2451                         mNetd.removeRoute(ifaceName, r);
2452                     } catch (Exception e) {
2453                         // never crash - catch them all
2454                         if (DBG) loge("Exception trying to remove a route: " + e);
2455                     }
2456                 }
2457             }
2458         }
2459
2460         return routesChanged;
2461     }
2462
2463
2464    /**
2465      * Reads the network specific TCP buffer sizes from SystemProperties
2466      * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2467      * wide use
2468      */
2469    private void updateNetworkSettings(NetworkStateTracker nt) {
2470         String key = nt.getTcpBufferSizesPropName();
2471         String bufferSizes = key == null ? null : SystemProperties.get(key);
2472
2473         if (TextUtils.isEmpty(bufferSizes)) {
2474             if (VDBG) log(key + " not found in system properties. Using defaults");
2475
2476             // Setting to default values so we won't be stuck to previous values
2477             key = "net.tcp.buffersize.default";
2478             bufferSizes = SystemProperties.get(key);
2479         }
2480
2481         // Set values in kernel
2482         if (bufferSizes.length() != 0) {
2483             if (VDBG) {
2484                 log("Setting TCP values: [" + bufferSizes
2485                         + "] which comes from [" + key + "]");
2486             }
2487             setBufferSize(bufferSizes);
2488         }
2489     }
2490
2491    /**
2492      * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2493      * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2494      *
2495      * @param bufferSizes in the format of "readMin, readInitial, readMax,
2496      *        writeMin, writeInitial, writeMax"
2497      */
2498     private void setBufferSize(String bufferSizes) {
2499         try {
2500             String[] values = bufferSizes.split(",");
2501
2502             if (values.length == 6) {
2503               final String prefix = "/sys/kernel/ipv4/tcp_";
2504                 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2505                 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2506                 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2507                 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2508                 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2509                 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2510             } else {
2511                 loge("Invalid buffersize string: " + bufferSizes);
2512             }
2513         } catch (IOException e) {
2514             loge("Can't set tcp buffer sizes:" + e);
2515         }
2516     }
2517
2518     /**
2519      * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2520      * on the highest priority active net which this process requested.
2521      * If there aren't any, clear it out
2522      */
2523     private void reassessPidDns(int pid, boolean doBump)
2524     {
2525         if (VDBG) log("reassessPidDns for pid " + pid);
2526         Integer myPid = new Integer(pid);
2527         for(int i : mPriorityList) {
2528             if (mNetConfigs[i].isDefault()) {
2529                 continue;
2530             }
2531             NetworkStateTracker nt = mNetTrackers[i];
2532             if (nt.getNetworkInfo().isConnected() &&
2533                     !nt.isTeardownRequested()) {
2534                 LinkProperties p = nt.getLinkProperties();
2535                 if (p == null) continue;
2536                 if (mNetRequestersPids[i].contains(myPid)) {
2537                     try {
2538                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2539                     } catch (Exception e) {
2540                         Slog.e(TAG, "exception reasseses pid dns: " + e);
2541                     }
2542                     return;
2543                 }
2544            }
2545         }
2546         // nothing found - delete
2547         try {
2548             mNetd.clearDnsInterfaceForPid(pid);
2549         } catch (Exception e) {
2550             Slog.e(TAG, "exception clear interface from pid: " + e);
2551         }
2552     }
2553
2554     private void flushVmDnsCache() {
2555         /*
2556          * Tell the VMs to toss their DNS caches
2557          */
2558         Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2559         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2560         /*
2561          * Connectivity events can happen before boot has completed ...
2562          */
2563         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2564         final long ident = Binder.clearCallingIdentity();
2565         try {
2566             mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2567         } finally {
2568             Binder.restoreCallingIdentity(ident);
2569         }
2570     }
2571
2572     // Caller must grab mDnsLock.
2573     private void updateDnsLocked(String network, String iface,
2574             Collection<InetAddress> dnses, String domains) {
2575         int last = 0;
2576         if (dnses.size() == 0 && mDefaultDns != null) {
2577             dnses = new ArrayList();
2578             dnses.add(mDefaultDns);
2579             if (DBG) {
2580                 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2581             }
2582         }
2583
2584         try {
2585             mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2586             mNetd.setDefaultInterfaceForDns(iface);
2587             for (InetAddress dns : dnses) {
2588                 ++last;
2589                 String key = "net.dns" + last;
2590                 String value = dns.getHostAddress();
2591                 SystemProperties.set(key, value);
2592             }
2593             for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2594                 String key = "net.dns" + i;
2595                 SystemProperties.set(key, "");
2596             }
2597             mNumDnsEntries = last;
2598         } catch (Exception e) {
2599             if (DBG) loge("exception setting default dns interface: " + e);
2600         }
2601     }
2602
2603     private void handleDnsConfigurationChange(int netType) {
2604         // add default net's dns entries
2605         NetworkStateTracker nt = mNetTrackers[netType];
2606         if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2607             LinkProperties p = nt.getLinkProperties();
2608             if (p == null) return;
2609             Collection<InetAddress> dnses = p.getDnses();
2610             if (mNetConfigs[netType].isDefault()) {
2611                 String network = nt.getNetworkInfo().getTypeName();
2612                 synchronized (mDnsLock) {
2613                     if (!mDnsOverridden) {
2614                         updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
2615                     }
2616                 }
2617             } else {
2618                 try {
2619                     mNetd.setDnsServersForInterface(p.getInterfaceName(),
2620                             NetworkUtils.makeStrings(dnses), p.getDomains());
2621                 } catch (Exception e) {
2622                     if (DBG) loge("exception setting dns servers: " + e);
2623                 }
2624                 // set per-pid dns for attached secondary nets
2625                 List<Integer> pids = mNetRequestersPids[netType];
2626                 for (Integer pid : pids) {
2627                     try {
2628                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2629                     } catch (Exception e) {
2630                         Slog.e(TAG, "exception setting interface for pid: " + e);
2631                     }
2632                 }
2633             }
2634             flushVmDnsCache();
2635         }
2636     }
2637
2638     private int getRestoreDefaultNetworkDelay(int networkType) {
2639         String restoreDefaultNetworkDelayStr = SystemProperties.get(
2640                 NETWORK_RESTORE_DELAY_PROP_NAME);
2641         if(restoreDefaultNetworkDelayStr != null &&
2642                 restoreDefaultNetworkDelayStr.length() != 0) {
2643             try {
2644                 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2645             } catch (NumberFormatException e) {
2646             }
2647         }
2648         // if the system property isn't set, use the value for the apn type
2649         int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2650
2651         if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2652                 (mNetConfigs[networkType] != null)) {
2653             ret = mNetConfigs[networkType].restoreTime;
2654         }
2655         return ret;
2656     }
2657
2658     @Override
2659     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2660         final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2661         if (mContext.checkCallingOrSelfPermission(
2662                 android.Manifest.permission.DUMP)
2663                 != PackageManager.PERMISSION_GRANTED) {
2664             pw.println("Permission Denial: can't dump ConnectivityService " +
2665                     "from from pid=" + Binder.getCallingPid() + ", uid=" +
2666                     Binder.getCallingUid());
2667             return;
2668         }
2669
2670         // TODO: add locking to get atomic snapshot
2671         pw.println();
2672         for (int i = 0; i < mNetTrackers.length; i++) {
2673             final NetworkStateTracker nst = mNetTrackers[i];
2674             if (nst != null) {
2675                 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2676                 pw.increaseIndent();
2677                 if (nst.getNetworkInfo().isConnected()) {
2678                     pw.println("Active network: " + nst.getNetworkInfo().
2679                             getTypeName());
2680                 }
2681                 pw.println(nst.getNetworkInfo());
2682                 pw.println(nst.getLinkProperties());
2683                 pw.println(nst);
2684                 pw.println();
2685                 pw.decreaseIndent();
2686             }
2687         }
2688
2689         pw.println("Network Requester Pids:");
2690         pw.increaseIndent();
2691         for (int net : mPriorityList) {
2692             String pidString = net + ": ";
2693             for (Integer pid : mNetRequestersPids[net]) {
2694                 pidString = pidString + pid.toString() + ", ";
2695             }
2696             pw.println(pidString);
2697         }
2698         pw.println();
2699         pw.decreaseIndent();
2700
2701         pw.println("FeatureUsers:");
2702         pw.increaseIndent();
2703         for (Object requester : mFeatureUsers) {
2704             pw.println(requester.toString());
2705         }
2706         pw.println();
2707         pw.decreaseIndent();
2708
2709         synchronized (this) {
2710             pw.println("NetworkTranstionWakeLock is currently " +
2711                     (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2712             pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2713         }
2714         pw.println();
2715
2716         mTethering.dump(fd, pw, args);
2717
2718         if (mInetLog != null) {
2719             pw.println();
2720             pw.println("Inet condition reports:");
2721             pw.increaseIndent();
2722             for(int i = 0; i < mInetLog.size(); i++) {
2723                 pw.println(mInetLog.get(i));
2724             }
2725             pw.decreaseIndent();
2726         }
2727     }
2728
2729     // must be stateless - things change under us.
2730     private class NetworkStateTrackerHandler extends Handler {
2731         public NetworkStateTrackerHandler(Looper looper) {
2732             super(looper);
2733         }
2734
2735         @Override
2736         public void handleMessage(Message msg) {
2737             NetworkInfo info;
2738             switch (msg.what) {
2739                 case NetworkStateTracker.EVENT_STATE_CHANGED:
2740                     info = (NetworkInfo) msg.obj;
2741                     int type = info.getType();
2742                     NetworkInfo.State state = info.getState();
2743
2744                     if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2745                             (state == NetworkInfo.State.DISCONNECTED)) {
2746                         log("ConnectivityChange for " +
2747                             info.getTypeName() + ": " +
2748                             state + "/" + info.getDetailedState());
2749                     }
2750
2751                     // After booting we'll check once for mobile provisioning
2752                     // if we've provisioned by and connected.
2753                     if (!mFirstProvisioningCheckStarted
2754                             && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2755                                         Settings.Global.DEVICE_PROVISIONED, 0))
2756                             && (state == NetworkInfo.State.CONNECTED)) {
2757                         log("check provisioning after booting");
2758                         mFirstProvisioningCheckStarted = true;
2759                         checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2760                     }
2761
2762                     EventLogTags.writeConnectivityStateChanged(
2763                             info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2764
2765                     if (info.getDetailedState() ==
2766                             NetworkInfo.DetailedState.FAILED) {
2767                         handleConnectionFailure(info);
2768                     } else if (info.getDetailedState() ==
2769                             DetailedState.CAPTIVE_PORTAL_CHECK) {
2770                         handleCaptivePortalTrackerCheck(info);
2771                     } else if (state == NetworkInfo.State.DISCONNECTED) {
2772                         handleDisconnect(info);
2773                     } else if (state == NetworkInfo.State.SUSPENDED) {
2774                         // TODO: need to think this over.
2775                         // the logic here is, handle SUSPENDED the same as
2776                         // DISCONNECTED. The only difference being we are
2777                         // broadcasting an intent with NetworkInfo that's
2778                         // suspended. This allows the applications an
2779                         // opportunity to handle DISCONNECTED and SUSPENDED
2780                         // differently, or not.
2781                         handleDisconnect(info);
2782                     } else if (state == NetworkInfo.State.CONNECTED) {
2783                         handleConnect(info);
2784                     }
2785                     if (mLockdownTracker != null) {
2786                         mLockdownTracker.onNetworkInfoChanged(info);
2787                     }
2788                     break;
2789                 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2790                     info = (NetworkInfo) msg.obj;
2791                     // TODO: Temporary allowing network configuration
2792                     //       change not resetting sockets.
2793                     //       @see bug/4455071
2794                     handleConnectivityChange(info.getType(), false);
2795                     break;
2796                 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2797                     info = (NetworkInfo) msg.obj;
2798                     type = info.getType();
2799                     updateNetworkSettings(mNetTrackers[type]);
2800                     break;
2801             }
2802         }
2803     }
2804
2805     private class InternalHandler extends Handler {
2806         public InternalHandler(Looper looper) {
2807             super(looper);
2808         }
2809
2810         @Override
2811         public void handleMessage(Message msg) {
2812             NetworkInfo info;
2813             switch (msg.what) {
2814                 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2815                     String causedBy = null;
2816                     synchronized (ConnectivityService.this) {
2817                         if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2818                                 mNetTransitionWakeLock.isHeld()) {
2819                             mNetTransitionWakeLock.release();
2820                             causedBy = mNetTransitionWakeLockCausedBy;
2821                         }
2822                     }
2823                     if (causedBy != null) {
2824                         log("NetTransition Wakelock for " + causedBy + " released by timeout");
2825                     }
2826                     break;
2827                 case EVENT_RESTORE_DEFAULT_NETWORK:
2828                     FeatureUser u = (FeatureUser)msg.obj;
2829                     u.expire();
2830                     break;
2831                 case EVENT_INET_CONDITION_CHANGE:
2832                 {
2833                     int netType = msg.arg1;
2834                     int condition = msg.arg2;
2835                     handleInetConditionChange(netType, condition);
2836                     break;
2837                 }
2838                 case EVENT_INET_CONDITION_HOLD_END:
2839                 {
2840                     int netType = msg.arg1;
2841                     int sequence = msg.arg2;
2842                     handleInetConditionHoldEnd(netType, sequence);
2843                     break;
2844                 }
2845                 case EVENT_SET_NETWORK_PREFERENCE:
2846                 {
2847                     int preference = msg.arg1;
2848                     handleSetNetworkPreference(preference);
2849                     break;
2850                 }
2851                 case EVENT_SET_MOBILE_DATA:
2852                 {
2853                     boolean enabled = (msg.arg1 == ENABLED);
2854                     handleSetMobileData(enabled);
2855                     break;
2856                 }
2857                 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2858                 {
2859                     handleDeprecatedGlobalHttpProxy();
2860                     break;
2861                 }
2862                 case EVENT_SET_DEPENDENCY_MET:
2863                 {
2864                     boolean met = (msg.arg1 == ENABLED);
2865                     handleSetDependencyMet(msg.arg2, met);
2866                     break;
2867                 }
2868                 case EVENT_RESTORE_DNS:
2869                 {
2870                     if (mActiveDefaultNetwork != -1) {
2871                         handleDnsConfigurationChange(mActiveDefaultNetwork);
2872                     }
2873                     break;
2874                 }
2875                 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2876                 {
2877                     Intent intent = (Intent)msg.obj;
2878                     sendStickyBroadcast(intent);
2879                     break;
2880                 }
2881                 case EVENT_SET_POLICY_DATA_ENABLE: {
2882                     final int networkType = msg.arg1;
2883                     final boolean enabled = msg.arg2 == ENABLED;
2884                     handleSetPolicyDataEnable(networkType, enabled);
2885                     break;
2886                 }
2887                 case EVENT_VPN_STATE_CHANGED: {
2888                     if (mLockdownTracker != null) {
2889                         mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2890                     }
2891                     break;
2892                 }
2893                 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2894                     int tag = mEnableFailFastMobileDataTag.get();
2895                     if (msg.arg1 == tag) {
2896                         MobileDataStateTracker mobileDst =
2897                             (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2898                         if (mobileDst != null) {
2899                             mobileDst.setEnableFailFastMobileData(msg.arg2);
2900                         }
2901                     } else {
2902                         log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2903                                 + " != tag:" + tag);
2904                     }
2905                 }
2906             }
2907         }
2908     }
2909
2910     // javadoc from interface
2911     public int tether(String iface) {
2912         enforceTetherChangePermission();
2913
2914         if (isTetheringSupported()) {
2915             return mTethering.tether(iface);
2916         } else {
2917             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2918         }
2919     }
2920
2921     // javadoc from interface
2922     public int untether(String iface) {
2923         enforceTetherChangePermission();
2924
2925         if (isTetheringSupported()) {
2926             return mTethering.untether(iface);
2927         } else {
2928             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2929         }
2930     }
2931
2932     // javadoc from interface
2933     public int getLastTetherError(String iface) {
2934         enforceTetherAccessPermission();
2935
2936         if (isTetheringSupported()) {
2937             return mTethering.getLastTetherError(iface);
2938         } else {
2939             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2940         }
2941     }
2942
2943     // TODO - proper iface API for selection by property, inspection, etc
2944     public String[] getTetherableUsbRegexs() {
2945         enforceTetherAccessPermission();
2946         if (isTetheringSupported()) {
2947             return mTethering.getTetherableUsbRegexs();
2948         } else {
2949             return new String[0];
2950         }
2951     }
2952
2953     public String[] getTetherableWifiRegexs() {
2954         enforceTetherAccessPermission();
2955         if (isTetheringSupported()) {
2956             return mTethering.getTetherableWifiRegexs();
2957         } else {
2958             return new String[0];
2959         }
2960     }
2961
2962     public String[] getTetherableBluetoothRegexs() {
2963         enforceTetherAccessPermission();
2964         if (isTetheringSupported()) {
2965             return mTethering.getTetherableBluetoothRegexs();
2966         } else {
2967             return new String[0];
2968         }
2969     }
2970
2971     public int setUsbTethering(boolean enable) {
2972         enforceTetherChangePermission();
2973         if (isTetheringSupported()) {
2974             return mTethering.setUsbTethering(enable);
2975         } else {
2976             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2977         }
2978     }
2979
2980     // TODO - move iface listing, queries, etc to new module
2981     // javadoc from interface
2982     public String[] getTetherableIfaces() {
2983         enforceTetherAccessPermission();
2984         return mTethering.getTetherableIfaces();
2985     }
2986
2987     public String[] getTetheredIfaces() {
2988         enforceTetherAccessPermission();
2989         return mTethering.getTetheredIfaces();
2990     }
2991
2992     @Override
2993     public String[] getTetheredIfacePairs() {
2994         enforceTetherAccessPermission();
2995         return mTethering.getTetheredIfacePairs();
2996     }
2997
2998     public String[] getTetheringErroredIfaces() {
2999         enforceTetherAccessPermission();
3000         return mTethering.getErroredIfaces();
3001     }
3002
3003     // if ro.tether.denied = true we default to no tethering
3004     // gservices could set the secure setting to 1 though to enable it on a build where it
3005     // had previously been turned off.
3006     public boolean isTetheringSupported() {
3007         enforceTetherAccessPermission();
3008         int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3009         boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3010                 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3011         return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3012                 mTethering.getTetherableWifiRegexs().length != 0 ||
3013                 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3014                 mTethering.getUpstreamIfaceTypes().length != 0);
3015     }
3016
3017     // An API NetworkStateTrackers can call when they lose their network.
3018     // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3019     // whichever happens first.  The timer is started by the first caller and not
3020     // restarted by subsequent callers.
3021     public void requestNetworkTransitionWakelock(String forWhom) {
3022         enforceConnectivityInternalPermission();
3023         synchronized (this) {
3024             if (mNetTransitionWakeLock.isHeld()) return;
3025             mNetTransitionWakeLockSerialNumber++;
3026             mNetTransitionWakeLock.acquire();
3027             mNetTransitionWakeLockCausedBy = forWhom;
3028         }
3029         mHandler.sendMessageDelayed(mHandler.obtainMessage(
3030                 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3031                 mNetTransitionWakeLockSerialNumber, 0),
3032                 mNetTransitionWakeLockTimeout);
3033         return;
3034     }
3035
3036     // 100 percent is full good, 0 is full bad.
3037     public void reportInetCondition(int networkType, int percentage) {
3038         if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3039         mContext.enforceCallingOrSelfPermission(
3040                 android.Manifest.permission.STATUS_BAR,
3041                 "ConnectivityService");
3042
3043         if (DBG) {
3044             int pid = getCallingPid();
3045             int uid = getCallingUid();
3046             String s = pid + "(" + uid + ") reports inet is " +
3047                 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3048                 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3049             mInetLog.add(s);
3050             while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3051                 mInetLog.remove(0);
3052             }
3053         }
3054         mHandler.sendMessage(mHandler.obtainMessage(
3055             EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3056     }
3057
3058     private void handleInetConditionChange(int netType, int condition) {
3059         if (mActiveDefaultNetwork == -1) {
3060             if (DBG) log("handleInetConditionChange: no active default network - ignore");
3061             return;
3062         }
3063         if (mActiveDefaultNetwork != netType) {
3064             if (DBG) log("handleInetConditionChange: net=" + netType +
3065                             " != default=" + mActiveDefaultNetwork + " - ignore");
3066             return;
3067         }
3068         if (VDBG) {
3069             log("handleInetConditionChange: net=" +
3070                     netType + ", condition=" + condition +
3071                     ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3072         }
3073         mDefaultInetCondition = condition;
3074         int delay;
3075         if (mInetConditionChangeInFlight == false) {
3076             if (VDBG) log("handleInetConditionChange: starting a change hold");
3077             // setup a new hold to debounce this
3078             if (mDefaultInetCondition > 50) {
3079                 delay = Settings.Global.getInt(mContext.getContentResolver(),
3080                         Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3081             } else {
3082                 delay = Settings.Global.getInt(mContext.getContentResolver(),
3083                         Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3084             }
3085             mInetConditionChangeInFlight = true;
3086             mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3087                     mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3088         } else {
3089             // we've set the new condition, when this hold ends that will get picked up
3090             if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3091         }
3092     }
3093
3094     private void handleInetConditionHoldEnd(int netType, int sequence) {
3095         if (DBG) {
3096             log("handleInetConditionHoldEnd: net=" + netType +
3097                     ", condition=" + mDefaultInetCondition +
3098                     ", published condition=" + mDefaultInetConditionPublished);
3099         }
3100         mInetConditionChangeInFlight = false;
3101
3102         if (mActiveDefaultNetwork == -1) {
3103             if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3104             return;
3105         }
3106         if (mDefaultConnectionSequence != sequence) {
3107             if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3108             return;
3109         }
3110         // TODO: Figure out why this optimization sometimes causes a
3111         //       change in mDefaultInetCondition to be missed and the
3112         //       UI to not be updated.
3113         //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3114         //    if (DBG) log("no change in condition - aborting");
3115         //    return;
3116         //}
3117         NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3118         if (networkInfo.isConnected() == false) {
3119             if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3120             return;
3121         }
3122         mDefaultInetConditionPublished = mDefaultInetCondition;
3123         sendInetConditionBroadcast(networkInfo);
3124         return;
3125     }
3126
3127     public ProxyProperties getProxy() {
3128         // this information is already available as a world read/writable jvm property
3129         // so this API change wouldn't have a benifit.  It also breaks the passing
3130         // of proxy info to all the JVMs.
3131         // enforceAccessPermission();
3132         synchronized (mProxyLock) {
3133             if (mGlobalProxy != null) return mGlobalProxy;
3134             return (mDefaultProxyDisabled ? null : mDefaultProxy);
3135         }
3136     }
3137
3138     public void setGlobalProxy(ProxyProperties proxyProperties) {
3139         enforceConnectivityInternalPermission();
3140         synchronized (mProxyLock) {
3141             if (proxyProperties == mGlobalProxy) return;
3142             if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3143             if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3144
3145             String host = "";
3146             int port = 0;
3147             String exclList = "";
3148             if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3149                 mGlobalProxy = new ProxyProperties(proxyProperties);
3150                 host = mGlobalProxy.getHost();
3151                 port = mGlobalProxy.getPort();
3152                 exclList = mGlobalProxy.getExclusionList();
3153             } else {
3154                 mGlobalProxy = null;
3155             }
3156             ContentResolver res = mContext.getContentResolver();
3157             final long token = Binder.clearCallingIdentity();
3158             try {
3159                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3160                 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3161                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3162                         exclList);
3163             } finally {
3164                 Binder.restoreCallingIdentity(token);
3165             }
3166         }
3167
3168         if (mGlobalProxy == null) {
3169             proxyProperties = mDefaultProxy;
3170         }
3171         sendProxyBroadcast(proxyProperties);
3172     }
3173
3174     private void loadGlobalProxy() {
3175         ContentResolver res = mContext.getContentResolver();
3176         String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3177         int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3178         String exclList = Settings.Global.getString(res,
3179                 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3180         if (!TextUtils.isEmpty(host)) {
3181             ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3182             synchronized (mProxyLock) {
3183                 mGlobalProxy = proxyProperties;
3184             }
3185         }
3186     }
3187
3188     public ProxyProperties getGlobalProxy() {
3189         // this information is already available as a world read/writable jvm property
3190         // so this API change wouldn't have a benifit.  It also breaks the passing
3191         // of proxy info to all the JVMs.
3192         // enforceAccessPermission();
3193         synchronized (mProxyLock) {
3194             return mGlobalProxy;
3195         }
3196     }
3197
3198     private void handleApplyDefaultProxy(ProxyProperties proxy) {
3199         if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3200             proxy = null;
3201         }
3202         synchronized (mProxyLock) {
3203             if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3204             if (mDefaultProxy == proxy) return; // catches repeated nulls
3205             mDefaultProxy = proxy;
3206
3207             if (mGlobalProxy != null) return;
3208             if (!mDefaultProxyDisabled) {
3209                 sendProxyBroadcast(proxy);
3210             }
3211         }
3212     }
3213
3214     private void handleDeprecatedGlobalHttpProxy() {
3215         String proxy = Settings.Global.getString(mContext.getContentResolver(),
3216                 Settings.Global.HTTP_PROXY);
3217         if (!TextUtils.isEmpty(proxy)) {
3218             String data[] = proxy.split(":");
3219             String proxyHost =  data[0];
3220             int proxyPort = 8080;
3221             if (data.length > 1) {
3222                 try {
3223                     proxyPort = Integer.parseInt(data[1]);
3224                 } catch (NumberFormatException e) {
3225                     return;
3226                 }
3227             }
3228             ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3229             setGlobalProxy(p);
3230         }
3231     }
3232
3233     private void sendProxyBroadcast(ProxyProperties proxy) {
3234         if (proxy == null) proxy = new ProxyProperties("", 0, "");
3235         if (DBG) log("sending Proxy Broadcast for " + proxy);
3236         Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3237         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3238             Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3239         intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3240         final long ident = Binder.clearCallingIdentity();
3241         try {
3242             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3243         } finally {
3244             Binder.restoreCallingIdentity(ident);
3245         }
3246     }
3247
3248     private static class SettingsObserver extends ContentObserver {
3249         private int mWhat;
3250         private Handler mHandler;
3251         SettingsObserver(Handler handler, int what) {
3252             super(handler);
3253             mHandler = handler;
3254             mWhat = what;
3255         }
3256
3257         void observe(Context context) {
3258             ContentResolver resolver = context.getContentResolver();
3259             resolver.registerContentObserver(Settings.Global.getUriFor(
3260                     Settings.Global.HTTP_PROXY), false, this);
3261         }
3262
3263         @Override
3264         public void onChange(boolean selfChange) {
3265             mHandler.obtainMessage(mWhat).sendToTarget();
3266         }
3267     }
3268
3269     private static void log(String s) {
3270         Slog.d(TAG, s);
3271     }
3272
3273     private static void loge(String s) {
3274         Slog.e(TAG, s);
3275     }
3276
3277     int convertFeatureToNetworkType(int networkType, String feature) {
3278         int usedNetworkType = networkType;
3279
3280         if(networkType == ConnectivityManager.TYPE_MOBILE) {
3281             if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3282                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3283             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3284                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3285             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3286                     TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3287                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3288             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3289                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3290             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3291                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3292             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3293                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3294             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3295                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3296             } else {
3297                 Slog.e(TAG, "Can't match any mobile netTracker!");
3298             }
3299         } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3300             if (TextUtils.equals(feature, "p2p")) {
3301                 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3302             } else {
3303                 Slog.e(TAG, "Can't match any wifi netTracker!");
3304             }
3305         } else {
3306             Slog.e(TAG, "Unexpected network type");
3307         }
3308         return usedNetworkType;
3309     }
3310
3311     private static <T> T checkNotNull(T value, String message) {
3312         if (value == null) {
3313             throw new NullPointerException(message);
3314         }
3315         return value;
3316     }
3317
3318     /**
3319      * Protect a socket from VPN routing rules. This method is used by
3320      * VpnBuilder and not available in ConnectivityManager. Permissions
3321      * are checked in Vpn class.
3322      * @hide
3323      */
3324     @Override
3325     public boolean protectVpn(ParcelFileDescriptor socket) {
3326         throwIfLockdownEnabled();
3327         try {
3328             int type = mActiveDefaultNetwork;
3329             if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3330                 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3331                 return true;
3332             }
3333         } catch (Exception e) {
3334             // ignore
3335         } finally {
3336             try {
3337                 socket.close();
3338             } catch (Exception e) {
3339                 // ignore
3340             }
3341         }
3342         return false;
3343     }
3344
3345     /**
3346      * Prepare for a VPN application. This method is used by VpnDialogs
3347      * and not available in ConnectivityManager. Permissions are checked
3348      * in Vpn class.
3349      * @hide
3350      */
3351     @Override
3352     public boolean prepareVpn(String oldPackage, String newPackage) {
3353         throwIfLockdownEnabled();
3354         return mVpn.prepare(oldPackage, newPackage);
3355     }
3356
3357     /**
3358      * Configure a TUN interface and return its file descriptor. Parameters
3359      * are encoded and opaque to this class. This method is used by VpnBuilder
3360      * and not available in ConnectivityManager. Permissions are checked in
3361      * Vpn class.
3362      * @hide
3363      */
3364     @Override
3365     public ParcelFileDescriptor establishVpn(VpnConfig config) {
3366         throwIfLockdownEnabled();
3367         return mVpn.establish(config);
3368     }
3369
3370     /**
3371      * Start legacy VPN, controlling native daemons as needed. Creates a
3372      * secondary thread to perform connection work, returning quickly.
3373      */
3374     @Override
3375     public void startLegacyVpn(VpnProfile profile) {
3376         throwIfLockdownEnabled();
3377         final LinkProperties egress = getActiveLinkProperties();
3378         if (egress == null) {
3379             throw new IllegalStateException("Missing active network connection");
3380         }
3381         mVpn.startLegacyVpn(profile, mKeyStore, egress);
3382     }
3383
3384     /**
3385      * Return the information of the ongoing legacy VPN. This method is used
3386      * by VpnSettings and not available in ConnectivityManager. Permissions
3387      * are checked in Vpn class.
3388      * @hide
3389      */
3390     @Override
3391     public LegacyVpnInfo getLegacyVpnInfo() {
3392         throwIfLockdownEnabled();
3393         return mVpn.getLegacyVpnInfo();
3394     }
3395
3396     /**
3397      * Callback for VPN subsystem. Currently VPN is not adapted to the service
3398      * through NetworkStateTracker since it works differently. For example, it
3399      * needs to override DNS servers but never takes the default routes. It
3400      * relies on another data network, and it could keep existing connections
3401      * alive after reconnecting, switching between networks, or even resuming
3402      * from deep sleep. Calls from applications should be done synchronously
3403      * to avoid race conditions. As these are all hidden APIs, refactoring can
3404      * be done whenever a better abstraction is developed.
3405      */
3406     public class VpnCallback {
3407         private VpnCallback() {
3408         }
3409
3410         public void onStateChanged(NetworkInfo info) {
3411             mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3412         }
3413
3414         public void override(List<String> dnsServers, List<String> searchDomains) {
3415             if (dnsServers == null) {
3416                 restore();
3417                 return;
3418             }
3419
3420             // Convert DNS servers into addresses.
3421             List<InetAddress> addresses = new ArrayList<InetAddress>();
3422             for (String address : dnsServers) {
3423                 // Double check the addresses and remove invalid ones.
3424                 try {
3425                     addresses.add(InetAddress.parseNumericAddress(address));
3426                 } catch (Exception e) {
3427                     // ignore
3428                 }
3429             }
3430             if (addresses.isEmpty()) {
3431                 restore();
3432                 return;
3433             }
3434
3435             // Concatenate search domains into a string.
3436             StringBuilder buffer = new StringBuilder();
3437             if (searchDomains != null) {
3438                 for (String domain : searchDomains) {
3439                     buffer.append(domain).append(' ');
3440                 }
3441             }
3442             String domains = buffer.toString().trim();
3443
3444             // Apply DNS changes.
3445             synchronized (mDnsLock) {
3446                 updateDnsLocked("VPN", "VPN", addresses, domains);
3447                 mDnsOverridden = true;
3448             }
3449
3450             // Temporarily disable the default proxy (not global).
3451             synchronized (mProxyLock) {
3452                 mDefaultProxyDisabled = true;
3453                 if (mGlobalProxy == null && mDefaultProxy != null) {
3454                     sendProxyBroadcast(null);
3455                 }
3456             }
3457
3458             // TODO: support proxy per network.
3459         }
3460
3461         public void restore() {
3462             synchronized (mDnsLock) {
3463                 if (mDnsOverridden) {
3464                     mDnsOverridden = false;
3465                     mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3466                 }
3467             }
3468             synchronized (mProxyLock) {
3469                 mDefaultProxyDisabled = false;
3470                 if (mGlobalProxy == null && mDefaultProxy != null) {
3471                     sendProxyBroadcast(mDefaultProxy);
3472                 }
3473             }
3474         }
3475     }
3476
3477     @Override
3478     public boolean updateLockdownVpn() {
3479         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3480             Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3481             return false;
3482         }
3483
3484         // Tear down existing lockdown if profile was removed
3485         mLockdownEnabled = LockdownVpnTracker.isEnabled();
3486         if (mLockdownEnabled) {
3487             if (!mKeyStore.isUnlocked()) {
3488                 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3489                 return false;
3490             }
3491
3492             final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3493             final VpnProfile profile = VpnProfile.decode(
3494                     profileName, mKeyStore.get(Credentials.VPN + profileName));
3495             setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3496         } else {
3497             setLockdownTracker(null);
3498         }
3499
3500         return true;
3501     }
3502
3503     /**
3504      * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3505      * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3506      */
3507     private void setLockdownTracker(LockdownVpnTracker tracker) {
3508         // Shutdown any existing tracker
3509         final LockdownVpnTracker existing = mLockdownTracker;
3510         mLockdownTracker = null;
3511         if (existing != null) {
3512             existing.shutdown();
3513         }
3514
3515         try {
3516             if (tracker != null) {
3517                 mNetd.setFirewallEnabled(true);
3518                 mNetd.setFirewallInterfaceRule("lo", true);
3519                 mLockdownTracker = tracker;
3520                 mLockdownTracker.init();
3521             } else {
3522                 mNetd.setFirewallEnabled(false);
3523             }
3524         } catch (RemoteException e) {
3525             // ignored; NMS lives inside system_server
3526         }
3527     }
3528
3529     private void throwIfLockdownEnabled() {
3530         if (mLockdownEnabled) {
3531             throw new IllegalStateException("Unavailable in lockdown mode");
3532         }
3533     }
3534
3535     public void supplyMessenger(int networkType, Messenger messenger) {
3536         enforceConnectivityInternalPermission();
3537
3538         if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3539             mNetTrackers[networkType].supplyMessenger(messenger);
3540         }
3541     }
3542
3543     public int findConnectionTypeForIface(String iface) {
3544         enforceConnectivityInternalPermission();
3545
3546         if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3547         for (NetworkStateTracker tracker : mNetTrackers) {
3548             if (tracker != null) {
3549                 LinkProperties lp = tracker.getLinkProperties();
3550                 if (lp != null && iface.equals(lp.getInterfaceName())) {
3551                     return tracker.getNetworkInfo().getType();
3552                 }
3553             }
3554         }
3555         return ConnectivityManager.TYPE_NONE;
3556     }
3557
3558     /**
3559      * Have mobile data fail fast if enabled.
3560      *
3561      * @param enabled DctConstants.ENABLED/DISABLED
3562      */
3563     private void setEnableFailFastMobileData(int enabled) {
3564         int tag;
3565
3566         if (enabled == DctConstants.ENABLED) {
3567             tag = mEnableFailFastMobileDataTag.incrementAndGet();
3568         } else {
3569             tag = mEnableFailFastMobileDataTag.get();
3570         }
3571         mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3572                          enabled));
3573     }
3574
3575     private boolean isMobileDataStateTrackerReady() {
3576         MobileDataStateTracker mdst =
3577                 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3578         return (mdst != null) && (mdst.isReady());
3579     }
3580
3581     @Override
3582     public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3583             final ResultReceiver resultReceiver) {
3584         log("checkMobileProvisioning: E sendNotification=" + sendNotification
3585                 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3586                 + " resultReceiver=" + resultReceiver);
3587         enforceChangePermission();
3588
3589         mFirstProvisioningCheckStarted = true;
3590
3591         int timeOutMs = suggestedTimeOutMs;
3592         if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3593             timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3594         }
3595
3596         // Check that mobile networks are supported
3597         if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3598                 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3599             log("checkMobileProvisioning: X no mobile network");
3600             if (resultReceiver != null) {
3601                 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3602             }
3603             return timeOutMs;
3604         }
3605
3606         final long token = Binder.clearCallingIdentity();
3607         try {
3608             CheckMp checkMp = new CheckMp(mContext, this);
3609             CheckMp.CallBack cb = new CheckMp.CallBack() {
3610                 @Override
3611                 void onComplete(Integer result) {
3612                     log("CheckMp.onComplete: result=" + result);
3613                     if (resultReceiver != null) {
3614                         log("CheckMp.onComplete: send result");
3615                         resultReceiver.send(result, null);
3616                     }
3617                     NetworkInfo ni =
3618                             mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3619                     switch(result) {
3620                         case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3621                         case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3622                             log("CheckMp.onComplete: ignore, connected or no connection");
3623                             break;
3624                         }
3625                         case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3626                             log("CheckMp.onComplete: warm sim");
3627                             String url = getMobileProvisioningUrl();
3628                             if (TextUtils.isEmpty(url)) {
3629                                 url = getMobileRedirectedProvisioningUrl();
3630                             }
3631                             if (TextUtils.isEmpty(url) == false) {
3632                                 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3633                                 setNotificationVisible(true, ni, url);
3634                             } else {
3635                                 log("CheckMp.onComplete: warm sim (redirected), no url");
3636                             }
3637                             break;
3638                         }
3639                         case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3640                         case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3641                             String url = getMobileProvisioningUrl();
3642                             if (TextUtils.isEmpty(url) == false) {
3643                                 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3644                                 setNotificationVisible(true, ni, url);
3645                             } else {
3646                                 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3647                             }
3648                             break;
3649                         }
3650                         default: {
3651                             loge("CheckMp.onComplete: ignore unexpected result=" + result);
3652                             break;
3653                         }
3654                     }
3655                 }
3656             };
3657             CheckMp.Params params =
3658                     new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3659             log("checkMobileProvisioning: params=" + params);
3660             setNotificationVisible(false, null, null);
3661             checkMp.execute(params);
3662         } finally {
3663             Binder.restoreCallingIdentity(token);
3664             log("checkMobileProvisioning: X");
3665         }
3666         return timeOutMs;
3667     }
3668
3669     static class CheckMp extends
3670             AsyncTask<CheckMp.Params, Void, Integer> {
3671         private static final String CHECKMP_TAG = "CheckMp";
3672         public static final int MAX_TIMEOUT_MS =  60000;
3673         private static final int SOCKET_TIMEOUT_MS = 5000;
3674         private Context mContext;
3675         private ConnectivityService mCs;
3676         private TelephonyManager mTm;
3677         private Params mParams;
3678
3679         /**
3680          * Parameters for AsyncTask.execute
3681          */
3682         static class Params {
3683             private String mUrl;
3684             private long mTimeOutMs;
3685             private CallBack mCb;
3686
3687             Params(String url, long timeOutMs, CallBack cb) {
3688                 mUrl = url;
3689                 mTimeOutMs = timeOutMs;
3690                 mCb = cb;
3691             }
3692
3693             @Override
3694             public String toString() {
3695                 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3696             }
3697         }
3698
3699         /**
3700          * The call back object passed in Params. onComplete will be called
3701          * on the main thread.
3702          */
3703         abstract static class CallBack {
3704             // Called on the main thread.
3705             abstract void onComplete(Integer result);
3706         }
3707
3708         public CheckMp(Context context, ConnectivityService cs) {
3709             mContext = context;
3710             mCs = cs;
3711
3712             // Setup access to TelephonyService we'll be using.
3713             mTm = (TelephonyManager) mContext.getSystemService(
3714                     Context.TELEPHONY_SERVICE);
3715         }
3716
3717         /**
3718          * Get the default url to use for the test.
3719          */
3720         public String getDefaultUrl() {
3721             // See http://go/clientsdns for usage approval
3722             String server = Settings.Global.getString(mContext.getContentResolver(),
3723                     Settings.Global.CAPTIVE_PORTAL_SERVER);
3724             if (server == null) {
3725                 server = "clients3.google.com";
3726             }
3727             return "http://" + server + "/generate_204";
3728         }
3729
3730         /**
3731          * Detect if its possible to connect to the http url. DNS based detection techniques
3732          * do not work at all hotspots. The best way to check is to perform a request to
3733          * a known address that fetches the data we expect.
3734          */
3735         private synchronized Integer isMobileOk(Params params) {
3736             Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3737             Uri orgUri = Uri.parse(params.mUrl);
3738             Random rand = new Random();
3739             mParams = params;
3740
3741             if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3742                 log("isMobileOk: not mobile capable");
3743                 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3744                 return result;
3745             }
3746
3747             try {
3748                 // Continue trying to connect until time has run out
3749                 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3750
3751                 if (!mCs.isMobileDataStateTrackerReady()) {
3752                     // Wait for MobileDataStateTracker to be ready.
3753                     if (DBG) log("isMobileOk: mdst is not ready");
3754                     while(SystemClock.elapsedRealtime() < endTime) {
3755                         if (mCs.isMobileDataStateTrackerReady()) {
3756                             // Enable fail fast as we'll do retries here and use a
3757                             // hipri connection so the default connection stays active.
3758                             if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3759                             mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3760                             break;
3761                         }
3762                         sleep(1);
3763                     }
3764                 }
3765
3766                 log("isMobileOk: start hipri url=" + params.mUrl);
3767
3768                 // First wait until we can start using hipri
3769                 Binder binder = new Binder();
3770                 while(SystemClock.elapsedRealtime() < endTime) {
3771                     int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3772                             Phone.FEATURE_ENABLE_HIPRI, binder);
3773                     if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3774                         || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3775                             log("isMobileOk: hipri started");
3776                             break;
3777                     }
3778                     if (VDBG) log("isMobileOk: hipri not started yet");
3779                     result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3780                     sleep(1);
3781                 }
3782
3783                 // Continue trying to connect until time has run out
3784                 while(SystemClock.elapsedRealtime() < endTime) {
3785                     try {
3786                         // Wait for hipri to connect.
3787                         // TODO: Don't poll and handle situation where hipri fails
3788                         // because default is retrying. See b/9569540
3789                         NetworkInfo.State state = mCs
3790                                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3791                         if (state != NetworkInfo.State.CONNECTED) {
3792                             if (VDBG) {
3793                                 log("isMobileOk: not connected ni=" +
3794                                     mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3795                             }
3796                             sleep(1);
3797                             result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3798                             continue;
3799                         }
3800
3801                         // Get of the addresses associated with the url host. We need to use the
3802                         // address otherwise HttpURLConnection object will use the name to get
3803                         // the addresses and is will try every address but that will bypass the
3804                         // route to host we setup and the connection could succeed as the default
3805                         // interface might be connected to the internet via wifi or other interface.
3806                         InetAddress[] addresses;
3807                         try {
3808                             addresses = InetAddress.getAllByName(orgUri.getHost());
3809                         } catch (UnknownHostException e) {
3810                             log("isMobileOk: UnknownHostException");
3811                             result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3812                             return result;
3813                         }
3814                         log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3815
3816                         // Get the type of addresses supported by this link
3817                         LinkProperties lp = mCs.getLinkProperties(
3818                                 ConnectivityManager.TYPE_MOBILE_HIPRI);
3819                         boolean linkHasIpv4 = hasIPv4Address(lp);
3820                         boolean linkHasIpv6 = hasIPv6Address(lp);
3821                         log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3822                                 + " linkHasIpv6=" + linkHasIpv6);
3823
3824                         // Loop through at most 3 valid addresses or all of the address or until
3825                         // we run out of time
3826                         int loops = Math.min(3, addresses.length);
3827                         for(int validAddr=0, addrTried=0;
3828                                     (validAddr < loops) && (addrTried < addresses.length)
3829                                       && (SystemClock.elapsedRealtime() < endTime);
3830                                 addrTried ++) {
3831
3832                             // Choose the address at random but make sure its type is supported
3833                             InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3834                             if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3835                                     || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3836                                 // Valid address, so use it
3837                                 validAddr += 1;
3838                             } else {
3839                                 // Invalid address so try next address
3840                                 continue;
3841                             }
3842
3843                             // Make a route to host so we check the specific interface.
3844                             if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3845                                     hostAddr.getAddress())) {
3846                                 // Wait a short time to be sure the route is established ??
3847                                 log("isMobileOk:"
3848                                         + " wait to establish route to hostAddr=" + hostAddr);
3849                                 sleep(3);
3850                             } else {
3851                                 log("isMobileOk:"
3852                                         + " could not establish route to hostAddr=" + hostAddr);
3853                                 continue;
3854                             }
3855
3856                             // Rewrite the url to have numeric address to use the specific route.
3857                             // I also set the "Connection" to "Close" as by default "Keep-Alive"
3858                             // is used which is useless in this case.
3859                             URL newUrl = new URL(orgUri.getScheme() + "://"
3860                                     + hostAddr.getHostAddress() + orgUri.getPath());
3861                             log("isMobileOk: newUrl=" + newUrl);
3862
3863                             HttpURLConnection urlConn = null;
3864                             try {
3865                                 // Open the connection set the request header and get the response
3866                                 urlConn = (HttpURLConnection) newUrl.openConnection(
3867                                         java.net.Proxy.NO_PROXY);
3868                                 urlConn.setInstanceFollowRedirects(false);
3869                                 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3870                                 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3871                                 urlConn.setUseCaches(false);
3872                                 urlConn.setAllowUserInteraction(false);
3873                                 urlConn.setRequestProperty("Connection", "close");
3874                                 int responseCode = urlConn.getResponseCode();
3875                                 if (responseCode == 204) {
3876                                     result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3877                                 } else {
3878                                     result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3879                                 }
3880                                 log("isMobileOk: connected responseCode=" + responseCode);
3881                                 urlConn.disconnect();
3882                                 urlConn = null;
3883                                 return result;
3884                             } catch (Exception e) {
3885                                 log("isMobileOk: HttpURLConnection Exception e=" + e);
3886                                 if (urlConn != null) {
3887                                     urlConn.disconnect();
3888                                     urlConn = null;
3889                                 }
3890                             }
3891                         }
3892                         result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3893                         log("isMobileOk: loops|timed out");
3894                         return result;
3895                     } catch (Exception e) {
3896                         log("isMobileOk: Exception e=" + e);
3897                         continue;
3898                     }
3899                 }
3900                 log("isMobileOk: timed out");
3901             } finally {
3902                 log("isMobileOk: F stop hipri");
3903                 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3904                 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3905                         Phone.FEATURE_ENABLE_HIPRI);
3906                 log("isMobileOk: X result=" + result);
3907             }
3908             return result;
3909         }
3910
3911         @Override
3912         protected Integer doInBackground(Params... params) {
3913             return isMobileOk(params[0]);
3914         }
3915
3916         @Override
3917         protected void onPostExecute(Integer result) {
3918             log("onPostExecute: result=" + result);
3919             if ((mParams != null) && (mParams.mCb != null)) {
3920                 mParams.mCb.onComplete(result);
3921             }
3922         }
3923
3924         private String inetAddressesToString(InetAddress[] addresses) {
3925             StringBuffer sb = new StringBuffer();
3926             boolean firstTime = true;
3927             for(InetAddress addr : addresses) {
3928                 if (firstTime) {
3929                     firstTime = false;
3930                 } else {
3931                     sb.append(",");
3932                 }
3933                 sb.append(addr);
3934             }
3935             return sb.toString();
3936         }
3937
3938         private void printNetworkInfo() {
3939             boolean hasIccCard = mTm.hasIccCard();
3940             int simState = mTm.getSimState();
3941             log("hasIccCard=" + hasIccCard
3942                     + " simState=" + simState);
3943             NetworkInfo[] ni = mCs.getAllNetworkInfo();
3944             if (ni != null) {
3945                 log("ni.length=" + ni.length);
3946                 for (NetworkInfo netInfo: ni) {
3947                     log("netInfo=" + netInfo.toString());
3948                 }
3949             } else {
3950                 log("no network info ni=null");
3951             }
3952         }
3953
3954         /**
3955          * Sleep for a few seconds then return.
3956          * @param seconds
3957          */
3958         private static void sleep(int seconds) {
3959             try {
3960                 Thread.sleep(seconds * 1000);
3961             } catch (InterruptedException e) {
3962                 e.printStackTrace();
3963             }
3964         }
3965
3966         public boolean hasIPv4Address(LinkProperties lp) {
3967             return lp.hasIPv4Address();
3968         }
3969
3970         // Not implemented in LinkProperties, do it here.
3971         public boolean hasIPv6Address(LinkProperties lp) {
3972             for (LinkAddress address : lp.getLinkAddresses()) {
3973               if (address.getAddress() instanceof Inet6Address) {
3974                 return true;
3975               }
3976             }
3977             return false;
3978         }
3979
3980         private void log(String s) {
3981             Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3982         }
3983     }
3984
3985     private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3986
3987     private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3988         log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3989
3990         Resources r = Resources.getSystem();
3991         NotificationManager notificationManager = (NotificationManager) mContext
3992             .getSystemService(Context.NOTIFICATION_SERVICE);
3993
3994         if (visible) {
3995             CharSequence title;
3996             CharSequence details;
3997             int icon;
3998             switch (networkInfo.getType()) {
3999                 case ConnectivityManager.TYPE_WIFI:
4000                     log("setNotificationVisible: TYPE_WIFI");
4001                     title = r.getString(R.string.wifi_available_sign_in, 0);
4002                     details = r.getString(R.string.network_available_sign_in_detailed,
4003                             networkInfo.getExtraInfo());
4004                     icon = R.drawable.stat_notify_wifi_in_range;
4005                     break;
4006                 case ConnectivityManager.TYPE_MOBILE:
4007                 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4008                     log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4009                     title = r.getString(R.string.network_available_sign_in, 0);
4010                     // TODO: Change this to pull from NetworkInfo once a printable
4011                     // name has been added to it
4012                     details = mTelephonyManager.getNetworkOperatorName();
4013                     icon = R.drawable.stat_notify_rssi_in_range;
4014                     break;
4015                 default:
4016                     log("setNotificationVisible: other type=" + networkInfo.getType());
4017                     title = r.getString(R.string.network_available_sign_in, 0);
4018                     details = r.getString(R.string.network_available_sign_in_detailed,
4019                             networkInfo.getExtraInfo());
4020                     icon = R.drawable.stat_notify_rssi_in_range;
4021                     break;
4022             }
4023
4024             Notification notification = new Notification();
4025             notification.when = 0;
4026             notification.icon = icon;
4027             notification.flags = Notification.FLAG_AUTO_CANCEL;
4028             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4029             intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4030                     Intent.FLAG_ACTIVITY_NEW_TASK);
4031             notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4032             notification.tickerText = title;
4033             notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4034
4035             log("setNotificaitionVisible: notify notificaiton=" + notification);
4036             notificationManager.notify(NOTIFICATION_ID, 1, notification);
4037         } else {
4038             log("setNotificaitionVisible: cancel");
4039             notificationManager.cancel(NOTIFICATION_ID, 1);
4040         }
4041         log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4042     }
4043
4044     /** Location to an updatable file listing carrier provisioning urls.
4045      *  An example:
4046      *
4047      * <?xml version="1.0" encoding="utf-8"?>
4048      *  <provisioningUrls>
4049      *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4050      *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4051      *  </provisioningUrls>
4052      */
4053     private static final String PROVISIONING_URL_PATH =
4054             "/data/misc/radio/provisioning_urls.xml";
4055     private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4056
4057     /** XML tag for root element. */
4058     private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4059     /** XML tag for individual url */
4060     private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4061     /** XML tag for redirected url */
4062     private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4063     /** XML attribute for mcc */
4064     private static final String ATTR_MCC = "mcc";
4065     /** XML attribute for mnc */
4066     private static final String ATTR_MNC = "mnc";
4067
4068     private static final int REDIRECTED_PROVISIONING = 1;
4069     private static final int PROVISIONING = 2;
4070
4071     private String getProvisioningUrlBaseFromFile(int type) {
4072         FileReader fileReader = null;
4073         XmlPullParser parser = null;
4074         Configuration config = mContext.getResources().getConfiguration();
4075         String tagType;
4076
4077         switch (type) {
4078             case PROVISIONING:
4079                 tagType = TAG_PROVISIONING_URL;
4080                 break;
4081             case REDIRECTED_PROVISIONING:
4082                 tagType = TAG_REDIRECTED_URL;
4083                 break;
4084             default:
4085                 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4086                         type);
4087         }
4088
4089         try {
4090             fileReader = new FileReader(mProvisioningUrlFile);
4091             parser = Xml.newPullParser();
4092             parser.setInput(fileReader);
4093             XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4094
4095             while (true) {
4096                 XmlUtils.nextElement(parser);
4097
4098                 String element = parser.getName();
4099                 if (element == null) break;
4100
4101                 if (element.equals(tagType)) {
4102                     String mcc = parser.getAttributeValue(null, ATTR_MCC);
4103                     try {
4104                         if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4105                             String mnc = parser.getAttributeValue(null, ATTR_MNC);
4106                             if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4107                                 parser.next();
4108                                 if (parser.getEventType() == XmlPullParser.TEXT) {
4109                                     return parser.getText();
4110                                 }
4111                             }
4112                         }
4113                     } catch (NumberFormatException e) {
4114                         loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4115                     }
4116                 }
4117             }
4118             return null;
4119         } catch (FileNotFoundException e) {
4120             loge("Carrier Provisioning Urls file not found");
4121         } catch (XmlPullParserException e) {
4122             loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4123         } catch (IOException e) {
4124             loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4125         } finally {
4126             if (fileReader != null) {
4127                 try {
4128                     fileReader.close();
4129                 } catch (IOException e) {}
4130             }
4131         }
4132         return null;
4133     }
4134
4135     @Override
4136     public String getMobileRedirectedProvisioningUrl() {
4137         enforceConnectivityInternalPermission();
4138         String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4139         if (TextUtils.isEmpty(url)) {
4140             url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4141         }
4142         return url;
4143     }
4144
4145     @Override
4146     public String getMobileProvisioningUrl() {
4147         enforceConnectivityInternalPermission();
4148         String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4149         if (TextUtils.isEmpty(url)) {
4150             url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4151             log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
4152         } else {
4153             log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
4154         }
4155         // populate the iccid, imei and phone number in the provisioning url.
4156         if (!TextUtils.isEmpty(url)) {
4157             String phoneNumber = mTelephonyManager.getLine1Number();
4158             if (TextUtils.isEmpty(phoneNumber)) {
4159                 phoneNumber = "0000000000";
4160             }
4161             url = String.format(url,
4162                     mTelephonyManager.getSimSerialNumber() /* ICCID */,
4163                     mTelephonyManager.getDeviceId() /* IMEI */,
4164                     phoneNumber /* Phone numer */);
4165         }
4166
4167         return url;
4168     }
4169 }