ConnectivityService.java revision 9158825f9c41869689d6b1786d7c7aa8bdd524ce
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
17package com.android.server;
18
19import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
20import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
23import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
30import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
32import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
33
34import android.app.AlarmManager;
35import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
38import android.bluetooth.BluetoothTetheringDataTracker;
39import android.content.ActivityNotFoundException;
40import android.content.BroadcastReceiver;
41import android.content.ContentResolver;
42import android.content.Context;
43import android.content.ContextWrapper;
44import android.content.Intent;
45import android.content.IntentFilter;
46import android.content.pm.PackageManager;
47import android.content.res.Configuration;
48import android.content.res.Resources;
49import android.database.ContentObserver;
50import android.net.CaptivePortalTracker;
51import android.net.ConnectivityManager;
52import android.net.DummyDataStateTracker;
53import android.net.EthernetDataTracker;
54import android.net.IConnectivityManager;
55import android.net.INetworkManagementEventObserver;
56import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
58import android.net.INetworkStatsService;
59import android.net.LinkAddress;
60import android.net.LinkProperties;
61import android.net.LinkProperties.CompareResult;
62import android.net.LinkQualityInfo;
63import android.net.MobileDataStateTracker;
64import android.net.NetworkConfig;
65import android.net.NetworkInfo;
66import android.net.NetworkInfo.DetailedState;
67import android.net.NetworkQuotaInfo;
68import android.net.NetworkState;
69import android.net.NetworkStateTracker;
70import android.net.NetworkUtils;
71import android.net.Proxy;
72import android.net.ProxyProperties;
73import android.net.RouteInfo;
74import android.net.SamplingDataTracker;
75import android.net.Uri;
76import android.net.wifi.WifiStateTracker;
77import android.net.wimax.WimaxManagerConstants;
78import android.os.AsyncTask;
79import android.os.Binder;
80import android.os.Build;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.HandlerThread;
84import android.os.IBinder;
85import android.os.INetworkManagementService;
86import android.os.Looper;
87import android.os.Message;
88import android.os.Messenger;
89import android.os.ParcelFileDescriptor;
90import android.os.PowerManager;
91import android.os.Process;
92import android.os.RemoteException;
93import android.os.ServiceManager;
94import android.os.SystemClock;
95import android.os.SystemProperties;
96import android.os.UserHandle;
97import android.provider.Settings;
98import android.security.Credentials;
99import android.security.KeyStore;
100import android.telephony.TelephonyManager;
101import android.text.TextUtils;
102import android.util.Slog;
103import android.util.SparseArray;
104import android.util.SparseIntArray;
105import android.util.Xml;
106
107import com.android.internal.R;
108import com.android.internal.annotations.GuardedBy;
109import com.android.internal.net.LegacyVpnInfo;
110import com.android.internal.net.VpnConfig;
111import com.android.internal.net.VpnProfile;
112import com.android.internal.telephony.DctConstants;
113import com.android.internal.telephony.Phone;
114import com.android.internal.telephony.PhoneConstants;
115import com.android.internal.util.IndentingPrintWriter;
116import com.android.internal.util.XmlUtils;
117import com.android.server.am.BatteryStatsService;
118import com.android.server.connectivity.DataConnectionStats;
119import com.android.server.connectivity.Nat464Xlat;
120import com.android.server.connectivity.PacManager;
121import com.android.server.connectivity.Tethering;
122import com.android.server.connectivity.Vpn;
123import com.android.server.net.BaseNetworkObserver;
124import com.android.server.net.LockdownVpnTracker;
125import com.google.android.collect.Lists;
126import com.google.android.collect.Sets;
127
128import dalvik.system.DexClassLoader;
129
130import org.xmlpull.v1.XmlPullParser;
131import org.xmlpull.v1.XmlPullParserException;
132
133import java.io.File;
134import java.io.FileDescriptor;
135import java.io.FileNotFoundException;
136import java.io.FileReader;
137import java.io.IOException;
138import java.io.PrintWriter;
139import java.lang.reflect.Constructor;
140import java.net.HttpURLConnection;
141import java.net.Inet4Address;
142import java.net.Inet6Address;
143import java.net.InetAddress;
144import java.net.URL;
145import java.net.URLConnection;
146import java.net.UnknownHostException;
147import java.util.ArrayList;
148import java.util.Arrays;
149import java.util.Collection;
150import java.util.GregorianCalendar;
151import java.util.HashMap;
152import java.util.HashSet;
153import java.util.List;
154import java.util.Map;
155import java.util.Random;
156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicInteger;
158
159import javax.net.ssl.HostnameVerifier;
160import javax.net.ssl.HttpsURLConnection;
161import javax.net.ssl.SSLSession;
162
163/**
164 * @hide
165 */
166public class ConnectivityService extends IConnectivityManager.Stub {
167    private static final String TAG = "ConnectivityService";
168
169    private static final boolean DBG = true;
170    private static final boolean VDBG = false;
171
172    private static final boolean LOGD_RULES = false;
173
174    // TODO: create better separation between radio types and network types
175
176    // how long to wait before switching back to a radio's default network
177    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178    // system property that can override the above value
179    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180            "android.telephony.apn-restore";
181
182    // Default value if FAIL_FAST_TIME_MS is not set
183    private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
184    // system property that can override DEFAULT_FAIL_FAST_TIME_MS
185    private static final String FAIL_FAST_TIME_MS =
186            "persist.radio.fail_fast_time_ms";
187
188    private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
189            "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
190
191    private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
192
193    private PendingIntent mSampleIntervalElapsedIntent;
194
195    // Set network sampling interval at 12 minutes, this way, even if the timers get
196    // aggregated, it will fire at around 15 minutes, which should allow us to
197    // aggregate this timer with other timers (specially the socket keep alive timers)
198    private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
199
200    // start network sampling a minute after booting ...
201    private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
202
203    AlarmManager mAlarmManager;
204
205    // used in recursive route setting to add gateways for the host for which
206    // a host route was requested.
207    private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
208
209    private Tethering mTethering;
210
211    private KeyStore mKeyStore;
212
213    @GuardedBy("mVpns")
214    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
215    private VpnCallback mVpnCallback = new VpnCallback();
216
217    private boolean mLockdownEnabled;
218    private LockdownVpnTracker mLockdownTracker;
219
220    private Nat464Xlat mClat;
221
222    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
223    private Object mRulesLock = new Object();
224    /** Currently active network rules by UID. */
225    private SparseIntArray mUidRules = new SparseIntArray();
226    /** Set of ifaces that are costly. */
227    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
228
229    /**
230     * Sometimes we want to refer to the individual network state
231     * trackers separately, and sometimes we just want to treat them
232     * abstractly.
233     */
234    private NetworkStateTracker mNetTrackers[];
235
236    /* Handles captive portal check on a network */
237    private CaptivePortalTracker mCaptivePortalTracker;
238
239    /**
240     * The link properties that define the current links
241     */
242    private LinkProperties mCurrentLinkProperties[];
243
244    /**
245     * A per Net list of the PID's that requested access to the net
246     * used both as a refcount and for per-PID DNS selection
247     */
248    private List<Integer> mNetRequestersPids[];
249
250    // priority order of the nettrackers
251    // (excluding dynamically set mNetworkPreference)
252    // TODO - move mNetworkTypePreference into this
253    private int[] mPriorityList;
254
255    private Context mContext;
256    private int mNetworkPreference;
257    private int mActiveDefaultNetwork = -1;
258    // 0 is full bad, 100 is full good
259    private int mDefaultInetCondition = 0;
260    private int mDefaultInetConditionPublished = 0;
261    private boolean mInetConditionChangeInFlight = false;
262    private int mDefaultConnectionSequence = 0;
263
264    private Object mDnsLock = new Object();
265    private int mNumDnsEntries;
266
267    private boolean mTestMode;
268    private static ConnectivityService sServiceInstance;
269
270    private INetworkManagementService mNetd;
271    private INetworkPolicyManager mPolicyManager;
272
273    private static final int ENABLED  = 1;
274    private static final int DISABLED = 0;
275
276    private static final boolean ADD = true;
277    private static final boolean REMOVE = false;
278
279    private static final boolean TO_DEFAULT_TABLE = true;
280    private static final boolean TO_SECONDARY_TABLE = false;
281
282    private static final boolean EXEMPT = true;
283    private static final boolean UNEXEMPT = false;
284
285    /**
286     * used internally as a delayed event to make us switch back to the
287     * default network
288     */
289    private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
290
291    /**
292     * used internally to change our mobile data enabled flag
293     */
294    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
295
296    /**
297     * used internally to change our network preference setting
298     * arg1 = networkType to prefer
299     */
300    private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
301
302    /**
303     * used internally to synchronize inet condition reports
304     * arg1 = networkType
305     * arg2 = condition (0 bad, 100 good)
306     */
307    private static final int EVENT_INET_CONDITION_CHANGE = 4;
308
309    /**
310     * used internally to mark the end of inet condition hold periods
311     * arg1 = networkType
312     */
313    private static final int EVENT_INET_CONDITION_HOLD_END = 5;
314
315    /**
316     * used internally to set enable/disable cellular data
317     * arg1 = ENBALED or DISABLED
318     */
319    private static final int EVENT_SET_MOBILE_DATA = 7;
320
321    /**
322     * used internally to clear a wakelock when transitioning
323     * from one net to another
324     */
325    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
326
327    /**
328     * used internally to reload global proxy settings
329     */
330    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
331
332    /**
333     * used internally to set external dependency met/unmet
334     * arg1 = ENABLED (met) or DISABLED (unmet)
335     * arg2 = NetworkType
336     */
337    private static final int EVENT_SET_DEPENDENCY_MET = 10;
338
339    /**
340     * used internally to send a sticky broadcast delayed.
341     */
342    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
343
344    /**
345     * Used internally to
346     * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
347     */
348    private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
349
350    private static final int EVENT_VPN_STATE_CHANGED = 13;
351
352    /**
353     * Used internally to disable fail fast of mobile data
354     */
355    private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
356
357    /**
358     * user internally to indicate that data sampling interval is up
359     */
360    private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
361
362    /**
363     * PAC manager has received new port.
364     */
365    private static final int EVENT_PROXY_HAS_CHANGED = 16;
366
367    /** Handler used for internal events. */
368    private InternalHandler mHandler;
369    /** Handler used for incoming {@link NetworkStateTracker} events. */
370    private NetworkStateTrackerHandler mTrackerHandler;
371
372    // list of DeathRecipients used to make sure features are turned off when
373    // a process dies
374    private List<FeatureUser> mFeatureUsers;
375
376    private boolean mSystemReady;
377    private Intent mInitialBroadcast;
378
379    private PowerManager.WakeLock mNetTransitionWakeLock;
380    private String mNetTransitionWakeLockCausedBy = "";
381    private int mNetTransitionWakeLockSerialNumber;
382    private int mNetTransitionWakeLockTimeout;
383
384    private InetAddress mDefaultDns;
385
386    // Lock for protecting access to mAddedRoutes and mExemptAddresses
387    private final Object mRoutesLock = new Object();
388
389    // this collection is used to refcount the added routes - if there are none left
390    // it's time to remove the route from the route table
391    @GuardedBy("mRoutesLock")
392    private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
393
394    // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
395    // used to handle cleanup of exempt rules
396    @GuardedBy("mRoutesLock")
397    private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
398
399    // used in DBG mode to track inet condition reports
400    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
401    private ArrayList mInetLog;
402
403    // track the current default http proxy - tell the world if we get a new one (real change)
404    private ProxyProperties mDefaultProxy = null;
405    private Object mProxyLock = new Object();
406    private boolean mDefaultProxyDisabled = false;
407
408    // track the global proxy.
409    private ProxyProperties mGlobalProxy = null;
410
411    private PacManager mPacManager = null;
412
413    private SettingsObserver mSettingsObserver;
414
415    NetworkConfig[] mNetConfigs;
416    int mNetworksDefined;
417
418    private static class RadioAttributes {
419        public int mSimultaneity;
420        public int mType;
421        public RadioAttributes(String init) {
422            String fragments[] = init.split(",");
423            mType = Integer.parseInt(fragments[0]);
424            mSimultaneity = Integer.parseInt(fragments[1]);
425        }
426    }
427    RadioAttributes[] mRadioAttributes;
428
429    // the set of network types that can only be enabled by system/sig apps
430    List mProtectedNetworks;
431
432    private DataConnectionStats mDataConnectionStats;
433
434    private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
435
436    TelephonyManager mTelephonyManager;
437
438    public ConnectivityService(Context context, INetworkManagementService netd,
439            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
440        // Currently, omitting a NetworkFactory will create one internally
441        // TODO: create here when we have cleaner WiMAX support
442        this(context, netd, statsService, policyManager, null);
443    }
444
445    public ConnectivityService(Context context, INetworkManagementService netManager,
446            INetworkStatsService statsService, INetworkPolicyManager policyManager,
447            NetworkFactory netFactory) {
448        if (DBG) log("ConnectivityService starting up");
449
450        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
451        handlerThread.start();
452        mHandler = new InternalHandler(handlerThread.getLooper());
453        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
454
455        if (netFactory == null) {
456            netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
457        }
458
459        // setup our unique device name
460        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
461            String id = Settings.Secure.getString(context.getContentResolver(),
462                    Settings.Secure.ANDROID_ID);
463            if (id != null && id.length() > 0) {
464                String name = new String("android-").concat(id);
465                SystemProperties.set("net.hostname", name);
466            }
467        }
468
469        // read our default dns server ip
470        String dns = Settings.Global.getString(context.getContentResolver(),
471                Settings.Global.DEFAULT_DNS_SERVER);
472        if (dns == null || dns.length() == 0) {
473            dns = context.getResources().getString(
474                    com.android.internal.R.string.config_default_dns_server);
475        }
476        try {
477            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
478        } catch (IllegalArgumentException e) {
479            loge("Error setting defaultDns using " + dns);
480        }
481
482        mContext = checkNotNull(context, "missing Context");
483        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
484        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
485        mKeyStore = KeyStore.getInstance();
486        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
487
488        try {
489            mPolicyManager.registerListener(mPolicyListener);
490        } catch (RemoteException e) {
491            // ouch, no rules updates means some processes may never get network
492            loge("unable to register INetworkPolicyListener" + e.toString());
493        }
494
495        final PowerManager powerManager = (PowerManager) context.getSystemService(
496                Context.POWER_SERVICE);
497        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
498        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
499                com.android.internal.R.integer.config_networkTransitionTimeout);
500
501        mNetTrackers = new NetworkStateTracker[
502                ConnectivityManager.MAX_NETWORK_TYPE+1];
503        mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
504
505        mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
506        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
507
508        // Load device network attributes from resources
509        String[] raStrings = context.getResources().getStringArray(
510                com.android.internal.R.array.radioAttributes);
511        for (String raString : raStrings) {
512            RadioAttributes r = new RadioAttributes(raString);
513            if (VDBG) log("raString=" + raString + " r=" + r);
514            if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
515                loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
516                continue;
517            }
518            if (mRadioAttributes[r.mType] != null) {
519                loge("Error in radioAttributes - ignoring attempt to redefine type " +
520                        r.mType);
521                continue;
522            }
523            mRadioAttributes[r.mType] = r;
524        }
525
526        // TODO: What is the "correct" way to do determine if this is a wifi only device?
527        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
528        log("wifiOnly=" + wifiOnly);
529        String[] naStrings = context.getResources().getStringArray(
530                com.android.internal.R.array.networkAttributes);
531        for (String naString : naStrings) {
532            try {
533                NetworkConfig n = new NetworkConfig(naString);
534                if (VDBG) log("naString=" + naString + " config=" + n);
535                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
536                    loge("Error in networkAttributes - ignoring attempt to define type " +
537                            n.type);
538                    continue;
539                }
540                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
541                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
542                            n.type);
543                    continue;
544                }
545                if (mNetConfigs[n.type] != null) {
546                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
547                            n.type);
548                    continue;
549                }
550                if (mRadioAttributes[n.radio] == null) {
551                    loge("Error in networkAttributes - ignoring attempt to use undefined " +
552                            "radio " + n.radio + " in network type " + n.type);
553                    continue;
554                }
555                mNetConfigs[n.type] = n;
556                mNetworksDefined++;
557            } catch(Exception e) {
558                // ignore it - leave the entry null
559            }
560        }
561        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
562
563        mProtectedNetworks = new ArrayList<Integer>();
564        int[] protectedNetworks = context.getResources().getIntArray(
565                com.android.internal.R.array.config_protectedNetworks);
566        for (int p : protectedNetworks) {
567            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
568                mProtectedNetworks.add(p);
569            } else {
570                if (DBG) loge("Ignoring protectedNetwork " + p);
571            }
572        }
573
574        // high priority first
575        mPriorityList = new int[mNetworksDefined];
576        {
577            int insertionPoint = mNetworksDefined-1;
578            int currentLowest = 0;
579            int nextLowest = 0;
580            while (insertionPoint > -1) {
581                for (NetworkConfig na : mNetConfigs) {
582                    if (na == null) continue;
583                    if (na.priority < currentLowest) continue;
584                    if (na.priority > currentLowest) {
585                        if (na.priority < nextLowest || nextLowest == 0) {
586                            nextLowest = na.priority;
587                        }
588                        continue;
589                    }
590                    mPriorityList[insertionPoint--] = na.type;
591                }
592                currentLowest = nextLowest;
593                nextLowest = 0;
594            }
595        }
596
597        // Update mNetworkPreference according to user mannually first then overlay config.xml
598        mNetworkPreference = getPersistedNetworkPreference();
599        if (mNetworkPreference == -1) {
600            for (int n : mPriorityList) {
601                if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
602                    mNetworkPreference = n;
603                    break;
604                }
605            }
606            if (mNetworkPreference == -1) {
607                throw new IllegalStateException(
608                        "You should set at least one default Network in config.xml!");
609            }
610        }
611
612        mNetRequestersPids =
613                (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
614        for (int i : mPriorityList) {
615            mNetRequestersPids[i] = new ArrayList<Integer>();
616        }
617
618        mFeatureUsers = new ArrayList<FeatureUser>();
619
620        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
621                && SystemProperties.get("ro.build.type").equals("eng");
622
623        // Create and start trackers for hard-coded networks
624        for (int targetNetworkType : mPriorityList) {
625            final NetworkConfig config = mNetConfigs[targetNetworkType];
626            final NetworkStateTracker tracker;
627            try {
628                tracker = netFactory.createTracker(targetNetworkType, config);
629                mNetTrackers[targetNetworkType] = tracker;
630            } catch (IllegalArgumentException e) {
631                Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
632                        + " tracker: " + e);
633                continue;
634            }
635
636            tracker.startMonitoring(context, mTrackerHandler);
637            if (config.isDefault()) {
638                tracker.reconnect();
639            }
640        }
641
642        mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
643
644        //set up the listener for user state for creating user VPNs
645        IntentFilter intentFilter = new IntentFilter();
646        intentFilter.addAction(Intent.ACTION_USER_STARTING);
647        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
648        mContext.registerReceiverAsUser(
649                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
650        mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
651
652        try {
653            mNetd.registerObserver(mTethering);
654            mNetd.registerObserver(mDataActivityObserver);
655            mNetd.registerObserver(mClat);
656        } catch (RemoteException e) {
657            loge("Error registering observer :" + e);
658        }
659
660        if (DBG) {
661            mInetLog = new ArrayList();
662        }
663
664        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
665        mSettingsObserver.observe(mContext);
666
667        mDataConnectionStats = new DataConnectionStats(mContext);
668        mDataConnectionStats.startMonitoring();
669
670        // start network sampling ..
671        Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
672        mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
673                SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
674
675        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
676        setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
677
678        IntentFilter filter = new IntentFilter();
679        filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
680        mContext.registerReceiver(
681                new BroadcastReceiver() {
682                    @Override
683                    public void onReceive(Context context, Intent intent) {
684                        String action = intent.getAction();
685                        if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
686                            mHandler.sendMessage(mHandler.obtainMessage
687                                    (EVENT_SAMPLE_INTERVAL_ELAPSED));
688                        }
689                    }
690                },
691                new IntentFilter(filter));
692
693        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
694
695        filter = new IntentFilter();
696        filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
697        mContext.registerReceiver(mProvisioningReceiver, filter);
698    }
699
700    /**
701     * Factory that creates {@link NetworkStateTracker} instances using given
702     * {@link NetworkConfig}.
703     */
704    public interface NetworkFactory {
705        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
706    }
707
708    private static class DefaultNetworkFactory implements NetworkFactory {
709        private final Context mContext;
710        private final Handler mTrackerHandler;
711
712        public DefaultNetworkFactory(Context context, Handler trackerHandler) {
713            mContext = context;
714            mTrackerHandler = trackerHandler;
715        }
716
717        @Override
718        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
719            switch (config.radio) {
720                case TYPE_WIFI:
721                    return new WifiStateTracker(targetNetworkType, config.name);
722                case TYPE_MOBILE:
723                    return new MobileDataStateTracker(targetNetworkType, config.name);
724                case TYPE_DUMMY:
725                    return new DummyDataStateTracker(targetNetworkType, config.name);
726                case TYPE_BLUETOOTH:
727                    return BluetoothTetheringDataTracker.getInstance();
728                case TYPE_WIMAX:
729                    return makeWimaxStateTracker(mContext, mTrackerHandler);
730                case TYPE_ETHERNET:
731                    return EthernetDataTracker.getInstance();
732                default:
733                    throw new IllegalArgumentException(
734                            "Trying to create a NetworkStateTracker for an unknown radio type: "
735                            + config.radio);
736            }
737        }
738    }
739
740    /**
741     * Loads external WiMAX library and registers as system service, returning a
742     * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
743     * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
744     */
745    private static NetworkStateTracker makeWimaxStateTracker(
746            Context context, Handler trackerHandler) {
747        // Initialize Wimax
748        DexClassLoader wimaxClassLoader;
749        Class wimaxStateTrackerClass = null;
750        Class wimaxServiceClass = null;
751        Class wimaxManagerClass;
752        String wimaxJarLocation;
753        String wimaxLibLocation;
754        String wimaxManagerClassName;
755        String wimaxServiceClassName;
756        String wimaxStateTrackerClassName;
757
758        NetworkStateTracker wimaxStateTracker = null;
759
760        boolean isWimaxEnabled = context.getResources().getBoolean(
761                com.android.internal.R.bool.config_wimaxEnabled);
762
763        if (isWimaxEnabled) {
764            try {
765                wimaxJarLocation = context.getResources().getString(
766                        com.android.internal.R.string.config_wimaxServiceJarLocation);
767                wimaxLibLocation = context.getResources().getString(
768                        com.android.internal.R.string.config_wimaxNativeLibLocation);
769                wimaxManagerClassName = context.getResources().getString(
770                        com.android.internal.R.string.config_wimaxManagerClassname);
771                wimaxServiceClassName = context.getResources().getString(
772                        com.android.internal.R.string.config_wimaxServiceClassname);
773                wimaxStateTrackerClassName = context.getResources().getString(
774                        com.android.internal.R.string.config_wimaxStateTrackerClassname);
775
776                if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
777                wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
778                        new ContextWrapper(context).getCacheDir().getAbsolutePath(),
779                        wimaxLibLocation, ClassLoader.getSystemClassLoader());
780
781                try {
782                    wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
783                    wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
784                    wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
785                } catch (ClassNotFoundException ex) {
786                    loge("Exception finding Wimax classes: " + ex.toString());
787                    return null;
788                }
789            } catch(Resources.NotFoundException ex) {
790                loge("Wimax Resources does not exist!!! ");
791                return null;
792            }
793
794            try {
795                if (DBG) log("Starting Wimax Service... ");
796
797                Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
798                        (new Class[] {Context.class, Handler.class});
799                wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
800                        context, trackerHandler);
801
802                Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
803                        (new Class[] {Context.class, wimaxStateTrackerClass});
804                wmxSrvConst.setAccessible(true);
805                IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
806                wmxSrvConst.setAccessible(false);
807
808                ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
809
810            } catch(Exception ex) {
811                loge("Exception creating Wimax classes: " + ex.toString());
812                return null;
813            }
814        } else {
815            loge("Wimax is not enabled or not added to the network attributes!!! ");
816            return null;
817        }
818
819        return wimaxStateTracker;
820    }
821
822    /**
823     * Sets the preferred network.
824     * @param preference the new preference
825     */
826    public void setNetworkPreference(int preference) {
827        enforceChangePermission();
828
829        mHandler.sendMessage(
830                mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
831    }
832
833    public int getNetworkPreference() {
834        enforceAccessPermission();
835        int preference;
836        synchronized(this) {
837            preference = mNetworkPreference;
838        }
839        return preference;
840    }
841
842    private void handleSetNetworkPreference(int preference) {
843        if (ConnectivityManager.isNetworkTypeValid(preference) &&
844                mNetConfigs[preference] != null &&
845                mNetConfigs[preference].isDefault()) {
846            if (mNetworkPreference != preference) {
847                final ContentResolver cr = mContext.getContentResolver();
848                Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
849                synchronized(this) {
850                    mNetworkPreference = preference;
851                }
852                enforcePreference();
853            }
854        }
855    }
856
857    private int getConnectivityChangeDelay() {
858        final ContentResolver cr = mContext.getContentResolver();
859
860        /** Check system properties for the default value then use secure settings value, if any. */
861        int defaultDelay = SystemProperties.getInt(
862                "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
863                ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
864        return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
865                defaultDelay);
866    }
867
868    private int getPersistedNetworkPreference() {
869        final ContentResolver cr = mContext.getContentResolver();
870
871        final int networkPrefSetting = Settings.Global
872                .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
873
874        return networkPrefSetting;
875    }
876
877    /**
878     * Make the state of network connectivity conform to the preference settings
879     * In this method, we only tear down a non-preferred network. Establishing
880     * a connection to the preferred network is taken care of when we handle
881     * the disconnect event from the non-preferred network
882     * (see {@link #handleDisconnect(NetworkInfo)}).
883     */
884    private void enforcePreference() {
885        if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
886            return;
887
888        if (!mNetTrackers[mNetworkPreference].isAvailable())
889            return;
890
891        for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
892            if (t != mNetworkPreference && mNetTrackers[t] != null &&
893                    mNetTrackers[t].getNetworkInfo().isConnected()) {
894                if (DBG) {
895                    log("tearing down " + mNetTrackers[t].getNetworkInfo() +
896                            " in enforcePreference");
897                }
898                teardown(mNetTrackers[t]);
899            }
900        }
901    }
902
903    private boolean teardown(NetworkStateTracker netTracker) {
904        if (netTracker.teardown()) {
905            netTracker.setTeardownRequested(true);
906            return true;
907        } else {
908            return false;
909        }
910    }
911
912    /**
913     * Check if UID should be blocked from using the network represented by the
914     * given {@link NetworkStateTracker}.
915     */
916    private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
917        final String iface = tracker.getLinkProperties().getInterfaceName();
918
919        final boolean networkCostly;
920        final int uidRules;
921        synchronized (mRulesLock) {
922            networkCostly = mMeteredIfaces.contains(iface);
923            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
924        }
925
926        if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
927            return true;
928        }
929
930        // no restrictive rules; network is visible
931        return false;
932    }
933
934    /**
935     * Return a filtered {@link NetworkInfo}, potentially marked
936     * {@link DetailedState#BLOCKED} based on
937     * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
938     */
939    private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
940        NetworkInfo info = tracker.getNetworkInfo();
941        if (isNetworkBlocked(tracker, uid)) {
942            // network is blocked; clone and override state
943            info = new NetworkInfo(info);
944            info.setDetailedState(DetailedState.BLOCKED, null, null);
945        }
946        if (mLockdownTracker != null) {
947            info = mLockdownTracker.augmentNetworkInfo(info);
948        }
949        return info;
950    }
951
952    /**
953     * Return NetworkInfo for the active (i.e., connected) network interface.
954     * It is assumed that at most one network is active at a time. If more
955     * than one is active, it is indeterminate which will be returned.
956     * @return the info for the active network, or {@code null} if none is
957     * active
958     */
959    @Override
960    public NetworkInfo getActiveNetworkInfo() {
961        enforceAccessPermission();
962        final int uid = Binder.getCallingUid();
963        return getNetworkInfo(mActiveDefaultNetwork, uid);
964    }
965
966    /**
967     * Find the first Provisioning network.
968     *
969     * @return NetworkInfo or null if none.
970     */
971    private NetworkInfo getProvisioningNetworkInfo() {
972        enforceAccessPermission();
973
974        // Find the first Provisioning Network
975        NetworkInfo provNi = null;
976        for (NetworkInfo ni : getAllNetworkInfo()) {
977            if (ni.isConnectedToProvisioningNetwork()) {
978                provNi = ni;
979                break;
980            }
981        }
982        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
983        return provNi;
984    }
985
986    /**
987     * Find the first Provisioning network or the ActiveDefaultNetwork
988     * if there is no Provisioning network
989     *
990     * @return NetworkInfo or null if none.
991     */
992    @Override
993    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
994        enforceAccessPermission();
995
996        NetworkInfo provNi = getProvisioningNetworkInfo();
997        if (provNi == null) {
998            final int uid = Binder.getCallingUid();
999            provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1000        }
1001        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1002        return provNi;
1003    }
1004
1005    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1006        enforceAccessPermission();
1007        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1008            final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1009            if (tracker != null) {
1010                return tracker.getNetworkInfo();
1011            }
1012        }
1013        return null;
1014    }
1015
1016    @Override
1017    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1018        enforceConnectivityInternalPermission();
1019        return getNetworkInfo(mActiveDefaultNetwork, uid);
1020    }
1021
1022    @Override
1023    public NetworkInfo getNetworkInfo(int networkType) {
1024        enforceAccessPermission();
1025        final int uid = Binder.getCallingUid();
1026        return getNetworkInfo(networkType, uid);
1027    }
1028
1029    private NetworkInfo getNetworkInfo(int networkType, int uid) {
1030        NetworkInfo info = null;
1031        if (isNetworkTypeValid(networkType)) {
1032            final NetworkStateTracker tracker = mNetTrackers[networkType];
1033            if (tracker != null) {
1034                info = getFilteredNetworkInfo(tracker, uid);
1035            }
1036        }
1037        return info;
1038    }
1039
1040    @Override
1041    public NetworkInfo[] getAllNetworkInfo() {
1042        enforceAccessPermission();
1043        final int uid = Binder.getCallingUid();
1044        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1045        synchronized (mRulesLock) {
1046            for (NetworkStateTracker tracker : mNetTrackers) {
1047                if (tracker != null) {
1048                    result.add(getFilteredNetworkInfo(tracker, uid));
1049                }
1050            }
1051        }
1052        return result.toArray(new NetworkInfo[result.size()]);
1053    }
1054
1055    @Override
1056    public boolean isNetworkSupported(int networkType) {
1057        enforceAccessPermission();
1058        return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1059    }
1060
1061    /**
1062     * Return LinkProperties for the active (i.e., connected) default
1063     * network interface.  It is assumed that at most one default network
1064     * is active at a time. If more than one is active, it is indeterminate
1065     * which will be returned.
1066     * @return the ip properties for the active network, or {@code null} if
1067     * none is active
1068     */
1069    @Override
1070    public LinkProperties getActiveLinkProperties() {
1071        return getLinkProperties(mActiveDefaultNetwork);
1072    }
1073
1074    @Override
1075    public LinkProperties getLinkProperties(int networkType) {
1076        enforceAccessPermission();
1077        if (isNetworkTypeValid(networkType)) {
1078            final NetworkStateTracker tracker = mNetTrackers[networkType];
1079            if (tracker != null) {
1080                return tracker.getLinkProperties();
1081            }
1082        }
1083        return null;
1084    }
1085
1086    @Override
1087    public NetworkState[] getAllNetworkState() {
1088        enforceAccessPermission();
1089        final int uid = Binder.getCallingUid();
1090        final ArrayList<NetworkState> result = Lists.newArrayList();
1091        synchronized (mRulesLock) {
1092            for (NetworkStateTracker tracker : mNetTrackers) {
1093                if (tracker != null) {
1094                    final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
1095                    result.add(new NetworkState(
1096                            info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1097                }
1098            }
1099        }
1100        return result.toArray(new NetworkState[result.size()]);
1101    }
1102
1103    private NetworkState getNetworkStateUnchecked(int networkType) {
1104        if (isNetworkTypeValid(networkType)) {
1105            final NetworkStateTracker tracker = mNetTrackers[networkType];
1106            if (tracker != null) {
1107                return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1108                        tracker.getLinkCapabilities());
1109            }
1110        }
1111        return null;
1112    }
1113
1114    @Override
1115    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1116        enforceAccessPermission();
1117
1118        final long token = Binder.clearCallingIdentity();
1119        try {
1120            final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1121            if (state != null) {
1122                try {
1123                    return mPolicyManager.getNetworkQuotaInfo(state);
1124                } catch (RemoteException e) {
1125                }
1126            }
1127            return null;
1128        } finally {
1129            Binder.restoreCallingIdentity(token);
1130        }
1131    }
1132
1133    @Override
1134    public boolean isActiveNetworkMetered() {
1135        enforceAccessPermission();
1136        final long token = Binder.clearCallingIdentity();
1137        try {
1138            return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1139        } finally {
1140            Binder.restoreCallingIdentity(token);
1141        }
1142    }
1143
1144    private boolean isNetworkMeteredUnchecked(int networkType) {
1145        final NetworkState state = getNetworkStateUnchecked(networkType);
1146        if (state != null) {
1147            try {
1148                return mPolicyManager.isNetworkMetered(state);
1149            } catch (RemoteException e) {
1150            }
1151        }
1152        return false;
1153    }
1154
1155    public boolean setRadios(boolean turnOn) {
1156        boolean result = true;
1157        enforceChangePermission();
1158        for (NetworkStateTracker t : mNetTrackers) {
1159            if (t != null) result = t.setRadio(turnOn) && result;
1160        }
1161        return result;
1162    }
1163
1164    public boolean setRadio(int netType, boolean turnOn) {
1165        enforceChangePermission();
1166        if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1167            return false;
1168        }
1169        NetworkStateTracker tracker = mNetTrackers[netType];
1170        return tracker != null && tracker.setRadio(turnOn);
1171    }
1172
1173    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1174        @Override
1175        public void interfaceClassDataActivityChanged(String label, boolean active) {
1176            int deviceType = Integer.parseInt(label);
1177            sendDataActivityBroadcast(deviceType, active);
1178        }
1179    };
1180
1181    /**
1182     * Used to notice when the calling process dies so we can self-expire
1183     *
1184     * Also used to know if the process has cleaned up after itself when
1185     * our auto-expire timer goes off.  The timer has a link to an object.
1186     *
1187     */
1188    private class FeatureUser implements IBinder.DeathRecipient {
1189        int mNetworkType;
1190        String mFeature;
1191        IBinder mBinder;
1192        int mPid;
1193        int mUid;
1194        long mCreateTime;
1195
1196        FeatureUser(int type, String feature, IBinder binder) {
1197            super();
1198            mNetworkType = type;
1199            mFeature = feature;
1200            mBinder = binder;
1201            mPid = getCallingPid();
1202            mUid = getCallingUid();
1203            mCreateTime = System.currentTimeMillis();
1204
1205            try {
1206                mBinder.linkToDeath(this, 0);
1207            } catch (RemoteException e) {
1208                binderDied();
1209            }
1210        }
1211
1212        void unlinkDeathRecipient() {
1213            mBinder.unlinkToDeath(this, 0);
1214        }
1215
1216        public void binderDied() {
1217            log("ConnectivityService FeatureUser binderDied(" +
1218                    mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1219                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1220            stopUsingNetworkFeature(this, false);
1221        }
1222
1223        public void expire() {
1224            if (VDBG) {
1225                log("ConnectivityService FeatureUser expire(" +
1226                        mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1227                        (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1228            }
1229            stopUsingNetworkFeature(this, false);
1230        }
1231
1232        public boolean isSameUser(FeatureUser u) {
1233            if (u == null) return false;
1234
1235            return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1236        }
1237
1238        public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1239            if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1240                TextUtils.equals(mFeature, feature)) {
1241                return true;
1242            }
1243            return false;
1244        }
1245
1246        public String toString() {
1247            return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1248                    (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1249        }
1250    }
1251
1252    // javadoc from interface
1253    public int startUsingNetworkFeature(int networkType, String feature,
1254            IBinder binder) {
1255        long startTime = 0;
1256        if (DBG) {
1257            startTime = SystemClock.elapsedRealtime();
1258        }
1259        if (VDBG) {
1260            log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1261                    + Binder.getCallingUid());
1262        }
1263        enforceChangePermission();
1264        try {
1265            if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1266                    mNetConfigs[networkType] == null) {
1267                return PhoneConstants.APN_REQUEST_FAILED;
1268            }
1269
1270            FeatureUser f = new FeatureUser(networkType, feature, binder);
1271
1272            // TODO - move this into individual networktrackers
1273            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1274
1275            if (mLockdownEnabled) {
1276                // Since carrier APNs usually aren't available from VPN
1277                // endpoint, mark them as unavailable.
1278                return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1279            }
1280
1281            if (mProtectedNetworks.contains(usedNetworkType)) {
1282                enforceConnectivityInternalPermission();
1283            }
1284
1285            // if UID is restricted, don't allow them to bring up metered APNs
1286            final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1287            final int uidRules;
1288            synchronized (mRulesLock) {
1289                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1290            }
1291            if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1292                return PhoneConstants.APN_REQUEST_FAILED;
1293            }
1294
1295            NetworkStateTracker network = mNetTrackers[usedNetworkType];
1296            if (network != null) {
1297                Integer currentPid = new Integer(getCallingPid());
1298                if (usedNetworkType != networkType) {
1299                    NetworkInfo ni = network.getNetworkInfo();
1300
1301                    if (ni.isAvailable() == false) {
1302                        if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1303                            if (DBG) log("special network not available ni=" + ni.getTypeName());
1304                            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1305                        } else {
1306                            // else make the attempt anyway - probably giving REQUEST_STARTED below
1307                            if (DBG) {
1308                                log("special network not available, but try anyway ni=" +
1309                                        ni.getTypeName());
1310                            }
1311                        }
1312                    }
1313
1314                    int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1315
1316                    synchronized(this) {
1317                        boolean addToList = true;
1318                        if (restoreTimer < 0) {
1319                            // In case there is no timer is specified for the feature,
1320                            // make sure we don't add duplicate entry with the same request.
1321                            for (FeatureUser u : mFeatureUsers) {
1322                                if (u.isSameUser(f)) {
1323                                    // Duplicate user is found. Do not add.
1324                                    addToList = false;
1325                                    break;
1326                                }
1327                            }
1328                        }
1329
1330                        if (addToList) mFeatureUsers.add(f);
1331                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1332                            // this gets used for per-pid dns when connected
1333                            mNetRequestersPids[usedNetworkType].add(currentPid);
1334                        }
1335                    }
1336
1337                    if (restoreTimer >= 0) {
1338                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
1339                                EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1340                    }
1341
1342                    if ((ni.isConnectedOrConnecting() == true) &&
1343                            !network.isTeardownRequested()) {
1344                        if (ni.isConnected() == true) {
1345                            final long token = Binder.clearCallingIdentity();
1346                            try {
1347                                // add the pid-specific dns
1348                                handleDnsConfigurationChange(usedNetworkType);
1349                                if (VDBG) log("special network already active");
1350                            } finally {
1351                                Binder.restoreCallingIdentity(token);
1352                            }
1353                            return PhoneConstants.APN_ALREADY_ACTIVE;
1354                        }
1355                        if (VDBG) log("special network already connecting");
1356                        return PhoneConstants.APN_REQUEST_STARTED;
1357                    }
1358
1359                    // check if the radio in play can make another contact
1360                    // assume if cannot for now
1361
1362                    if (DBG) {
1363                        log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1364                                feature);
1365                    }
1366                    if (network.reconnect()) {
1367                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
1368                        return PhoneConstants.APN_REQUEST_STARTED;
1369                    } else {
1370                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
1371                        return PhoneConstants.APN_REQUEST_FAILED;
1372                    }
1373                } else {
1374                    // need to remember this unsupported request so we respond appropriately on stop
1375                    synchronized(this) {
1376                        mFeatureUsers.add(f);
1377                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1378                            // this gets used for per-pid dns when connected
1379                            mNetRequestersPids[usedNetworkType].add(currentPid);
1380                        }
1381                    }
1382                    if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
1383                    return -1;
1384                }
1385            }
1386            if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
1387            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1388         } finally {
1389            if (DBG) {
1390                final long execTime = SystemClock.elapsedRealtime() - startTime;
1391                if (execTime > 250) {
1392                    loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1393                } else {
1394                    if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1395                }
1396            }
1397         }
1398    }
1399
1400    // javadoc from interface
1401    public int stopUsingNetworkFeature(int networkType, String feature) {
1402        enforceChangePermission();
1403
1404        int pid = getCallingPid();
1405        int uid = getCallingUid();
1406
1407        FeatureUser u = null;
1408        boolean found = false;
1409
1410        synchronized(this) {
1411            for (FeatureUser x : mFeatureUsers) {
1412                if (x.isSameUser(pid, uid, networkType, feature)) {
1413                    u = x;
1414                    found = true;
1415                    break;
1416                }
1417            }
1418        }
1419        if (found && u != null) {
1420            if (VDBG) log("stopUsingNetworkFeature: X");
1421            // stop regardless of how many other time this proc had called start
1422            return stopUsingNetworkFeature(u, true);
1423        } else {
1424            // none found!
1425            if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
1426            return 1;
1427        }
1428    }
1429
1430    private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1431        int networkType = u.mNetworkType;
1432        String feature = u.mFeature;
1433        int pid = u.mPid;
1434        int uid = u.mUid;
1435
1436        NetworkStateTracker tracker = null;
1437        boolean callTeardown = false;  // used to carry our decision outside of sync block
1438
1439        if (VDBG) {
1440            log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1441        }
1442
1443        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1444            if (DBG) {
1445                log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1446                        ", net is invalid");
1447            }
1448            return -1;
1449        }
1450
1451        // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1452        // sync block
1453        synchronized(this) {
1454            // check if this process still has an outstanding start request
1455            if (!mFeatureUsers.contains(u)) {
1456                if (VDBG) {
1457                    log("stopUsingNetworkFeature: this process has no outstanding requests" +
1458                        ", ignoring");
1459                }
1460                return 1;
1461            }
1462            u.unlinkDeathRecipient();
1463            mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1464            // If we care about duplicate requests, check for that here.
1465            //
1466            // This is done to support the extension of a request - the app
1467            // can request we start the network feature again and renew the
1468            // auto-shutoff delay.  Normal "stop" calls from the app though
1469            // do not pay attention to duplicate requests - in effect the
1470            // API does not refcount and a single stop will counter multiple starts.
1471            if (ignoreDups == false) {
1472                for (FeatureUser x : mFeatureUsers) {
1473                    if (x.isSameUser(u)) {
1474                        if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1475                        return 1;
1476                    }
1477                }
1478            }
1479
1480            // TODO - move to individual network trackers
1481            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1482
1483            tracker =  mNetTrackers[usedNetworkType];
1484            if (tracker == null) {
1485                if (DBG) {
1486                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1487                            " no known tracker for used net type " + usedNetworkType);
1488                }
1489                return -1;
1490            }
1491            if (usedNetworkType != networkType) {
1492                Integer currentPid = new Integer(pid);
1493                mNetRequestersPids[usedNetworkType].remove(currentPid);
1494
1495                final long token = Binder.clearCallingIdentity();
1496                try {
1497                    reassessPidDns(pid, true);
1498                } finally {
1499                    Binder.restoreCallingIdentity(token);
1500                }
1501                flushVmDnsCache();
1502                if (mNetRequestersPids[usedNetworkType].size() != 0) {
1503                    if (VDBG) {
1504                        log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1505                                " others still using it");
1506                    }
1507                    return 1;
1508                }
1509                callTeardown = true;
1510            } else {
1511                if (DBG) {
1512                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1513                            " not a known feature - dropping");
1514                }
1515            }
1516        }
1517
1518        if (callTeardown) {
1519            if (DBG) {
1520                log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1521            }
1522            tracker.teardown();
1523            return 1;
1524        } else {
1525            return -1;
1526        }
1527    }
1528
1529    /**
1530     * @deprecated use requestRouteToHostAddress instead
1531     *
1532     * Ensure that a network route exists to deliver traffic to the specified
1533     * host via the specified network interface.
1534     * @param networkType the type of the network over which traffic to the
1535     * specified host is to be routed
1536     * @param hostAddress the IP address of the host to which the route is
1537     * desired
1538     * @return {@code true} on success, {@code false} on failure
1539     */
1540    public boolean requestRouteToHost(int networkType, int hostAddress) {
1541        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1542
1543        if (inetAddress == null) {
1544            return false;
1545        }
1546
1547        return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1548    }
1549
1550    /**
1551     * Ensure that a network route exists to deliver traffic to the specified
1552     * host via the specified network interface.
1553     * @param networkType the type of the network over which traffic to the
1554     * specified host is to be routed
1555     * @param hostAddress the IP address of the host to which the route is
1556     * desired
1557     * @return {@code true} on success, {@code false} on failure
1558     */
1559    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1560        enforceChangePermission();
1561        if (mProtectedNetworks.contains(networkType)) {
1562            enforceConnectivityInternalPermission();
1563        }
1564
1565        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1566            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1567            return false;
1568        }
1569        NetworkStateTracker tracker = mNetTrackers[networkType];
1570        DetailedState netState = DetailedState.DISCONNECTED;
1571        if (tracker != null) {
1572            netState = tracker.getNetworkInfo().getDetailedState();
1573        }
1574
1575        if ((netState != DetailedState.CONNECTED &&
1576                netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1577                tracker.isTeardownRequested()) {
1578            if (VDBG) {
1579                log("requestRouteToHostAddress on down network "
1580                        + "(" + networkType + ") - dropped"
1581                        + " tracker=" + tracker
1582                        + " netState=" + netState
1583                        + " isTeardownRequested="
1584                            + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
1585            }
1586            return false;
1587        }
1588        final long token = Binder.clearCallingIdentity();
1589        try {
1590            InetAddress addr = InetAddress.getByAddress(hostAddress);
1591            LinkProperties lp = tracker.getLinkProperties();
1592            boolean ok = addRouteToAddress(lp, addr, EXEMPT);
1593            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1594            return ok;
1595        } catch (UnknownHostException e) {
1596            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1597        } finally {
1598            Binder.restoreCallingIdentity(token);
1599        }
1600        if (DBG) log("requestRouteToHostAddress X bottom return false");
1601        return false;
1602    }
1603
1604    private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1605            boolean exempt) {
1606        return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
1607    }
1608
1609    private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1610        return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
1611    }
1612
1613    private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1614        return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
1615    }
1616
1617    private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1618        return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
1619    }
1620
1621    private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1622            boolean toDefaultTable, boolean exempt) {
1623        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1624        if (bestRoute == null) {
1625            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1626        } else {
1627            String iface = bestRoute.getInterface();
1628            if (bestRoute.getGateway().equals(addr)) {
1629                // if there is no better route, add the implied hostroute for our gateway
1630                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1631            } else {
1632                // if we will connect to this through another route, add a direct route
1633                // to it's gateway
1634                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1635            }
1636        }
1637        return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
1638    }
1639
1640    private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1641            boolean toDefaultTable, boolean exempt) {
1642        if ((lp == null) || (r == null)) {
1643            if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1644            return false;
1645        }
1646
1647        if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1648            loge("Error modifying route - too much recursion");
1649            return false;
1650        }
1651
1652        String ifaceName = r.getInterface();
1653        if(ifaceName == null) {
1654            loge("Error modifying route - no interface name");
1655            return false;
1656        }
1657        if (r.hasGateway()) {
1658            RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1659            if (bestRoute != null) {
1660                if (bestRoute.getGateway().equals(r.getGateway())) {
1661                    // if there is no better route, add the implied hostroute for our gateway
1662                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1663                } else {
1664                    // if we will connect to our gateway through another route, add a direct
1665                    // route to it's gateway
1666                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1667                                                        bestRoute.getGateway(),
1668                                                        ifaceName);
1669                }
1670                modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
1671            }
1672        }
1673        if (doAdd) {
1674            if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1675            try {
1676                if (toDefaultTable) {
1677                    synchronized (mRoutesLock) {
1678                        // only track default table - only one apps can effect
1679                        mAddedRoutes.add(r);
1680                        mNetd.addRoute(ifaceName, r);
1681                        if (exempt) {
1682                            LinkAddress dest = r.getDestination();
1683                            if (!mExemptAddresses.contains(dest)) {
1684                                mNetd.setHostExemption(dest);
1685                                mExemptAddresses.add(dest);
1686                            }
1687                        }
1688                    }
1689                } else {
1690                    mNetd.addSecondaryRoute(ifaceName, r);
1691                }
1692            } catch (Exception e) {
1693                // never crash - catch them all
1694                if (DBG) loge("Exception trying to add a route: " + e);
1695                return false;
1696            }
1697        } else {
1698            // if we remove this one and there are no more like it, then refcount==0 and
1699            // we can remove it from the table
1700            if (toDefaultTable) {
1701                synchronized (mRoutesLock) {
1702                    mAddedRoutes.remove(r);
1703                    if (mAddedRoutes.contains(r) == false) {
1704                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1705                        try {
1706                            mNetd.removeRoute(ifaceName, r);
1707                            LinkAddress dest = r.getDestination();
1708                            if (mExemptAddresses.contains(dest)) {
1709                                mNetd.clearHostExemption(dest);
1710                                mExemptAddresses.remove(dest);
1711                            }
1712                        } catch (Exception e) {
1713                            // never crash - catch them all
1714                            if (VDBG) loge("Exception trying to remove a route: " + e);
1715                            return false;
1716                        }
1717                    } else {
1718                        if (VDBG) log("not removing " + r + " as it's still in use");
1719                    }
1720                }
1721            } else {
1722                if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1723                try {
1724                    mNetd.removeSecondaryRoute(ifaceName, r);
1725                } catch (Exception e) {
1726                    // never crash - catch them all
1727                    if (VDBG) loge("Exception trying to remove a route: " + e);
1728                    return false;
1729                }
1730            }
1731        }
1732        return true;
1733    }
1734
1735    /**
1736     * @see ConnectivityManager#getMobileDataEnabled()
1737     */
1738    public boolean getMobileDataEnabled() {
1739        // TODO: This detail should probably be in DataConnectionTracker's
1740        //       which is where we store the value and maybe make this
1741        //       asynchronous.
1742        enforceAccessPermission();
1743        boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1744                Settings.Global.MOBILE_DATA, 1) == 1;
1745        if (VDBG) log("getMobileDataEnabled returning " + retVal);
1746        return retVal;
1747    }
1748
1749    public void setDataDependency(int networkType, boolean met) {
1750        enforceConnectivityInternalPermission();
1751
1752        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1753                (met ? ENABLED : DISABLED), networkType));
1754    }
1755
1756    private void handleSetDependencyMet(int networkType, boolean met) {
1757        if (mNetTrackers[networkType] != null) {
1758            if (DBG) {
1759                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1760            }
1761            mNetTrackers[networkType].setDependencyMet(met);
1762        }
1763    }
1764
1765    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1766        @Override
1767        public void onUidRulesChanged(int uid, int uidRules) {
1768            // caller is NPMS, since we only register with them
1769            if (LOGD_RULES) {
1770                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1771            }
1772
1773            synchronized (mRulesLock) {
1774                // skip update when we've already applied rules
1775                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1776                if (oldRules == uidRules) return;
1777
1778                mUidRules.put(uid, uidRules);
1779            }
1780
1781            // TODO: notify UID when it has requested targeted updates
1782        }
1783
1784        @Override
1785        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1786            // caller is NPMS, since we only register with them
1787            if (LOGD_RULES) {
1788                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1789            }
1790
1791            synchronized (mRulesLock) {
1792                mMeteredIfaces.clear();
1793                for (String iface : meteredIfaces) {
1794                    mMeteredIfaces.add(iface);
1795                }
1796            }
1797        }
1798
1799        @Override
1800        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1801            // caller is NPMS, since we only register with them
1802            if (LOGD_RULES) {
1803                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1804            }
1805
1806            // kick off connectivity change broadcast for active network, since
1807            // global background policy change is radical.
1808            final int networkType = mActiveDefaultNetwork;
1809            if (isNetworkTypeValid(networkType)) {
1810                final NetworkStateTracker tracker = mNetTrackers[networkType];
1811                if (tracker != null) {
1812                    final NetworkInfo info = tracker.getNetworkInfo();
1813                    if (info != null && info.isConnected()) {
1814                        sendConnectedBroadcast(info);
1815                    }
1816                }
1817            }
1818        }
1819    };
1820
1821    /**
1822     * @see ConnectivityManager#setMobileDataEnabled(boolean)
1823     */
1824    public void setMobileDataEnabled(boolean enabled) {
1825        enforceChangePermission();
1826        if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1827
1828        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1829                (enabled ? ENABLED : DISABLED), 0));
1830    }
1831
1832    private void handleSetMobileData(boolean enabled) {
1833        if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1834            if (VDBG) {
1835                log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1836            }
1837            mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1838        }
1839        if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1840            if (VDBG) {
1841                log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1842            }
1843            mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1844        }
1845    }
1846
1847    @Override
1848    public void setPolicyDataEnable(int networkType, boolean enabled) {
1849        // only someone like NPMS should only be calling us
1850        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1851
1852        mHandler.sendMessage(mHandler.obtainMessage(
1853                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1854    }
1855
1856    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1857        if (isNetworkTypeValid(networkType)) {
1858            final NetworkStateTracker tracker = mNetTrackers[networkType];
1859            if (tracker != null) {
1860                tracker.setPolicyDataEnable(enabled);
1861            }
1862        }
1863    }
1864
1865    private void enforceAccessPermission() {
1866        mContext.enforceCallingOrSelfPermission(
1867                android.Manifest.permission.ACCESS_NETWORK_STATE,
1868                "ConnectivityService");
1869    }
1870
1871    private void enforceChangePermission() {
1872        mContext.enforceCallingOrSelfPermission(
1873                android.Manifest.permission.CHANGE_NETWORK_STATE,
1874                "ConnectivityService");
1875    }
1876
1877    // TODO Make this a special check when it goes public
1878    private void enforceTetherChangePermission() {
1879        mContext.enforceCallingOrSelfPermission(
1880                android.Manifest.permission.CHANGE_NETWORK_STATE,
1881                "ConnectivityService");
1882    }
1883
1884    private void enforceTetherAccessPermission() {
1885        mContext.enforceCallingOrSelfPermission(
1886                android.Manifest.permission.ACCESS_NETWORK_STATE,
1887                "ConnectivityService");
1888    }
1889
1890    private void enforceConnectivityInternalPermission() {
1891        mContext.enforceCallingOrSelfPermission(
1892                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1893                "ConnectivityService");
1894    }
1895
1896    private void enforceMarkNetworkSocketPermission() {
1897        //Media server special case
1898        if (Binder.getCallingUid() == Process.MEDIA_UID) {
1899            return;
1900        }
1901        mContext.enforceCallingOrSelfPermission(
1902                android.Manifest.permission.MARK_NETWORK_SOCKET,
1903                "ConnectivityService");
1904    }
1905
1906    /**
1907     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1908     * network, we ignore it. If it is for the active network, we send out a
1909     * broadcast. But first, we check whether it might be possible to connect
1910     * to a different network.
1911     * @param info the {@code NetworkInfo} for the network
1912     */
1913    private void handleDisconnect(NetworkInfo info) {
1914
1915        int prevNetType = info.getType();
1916
1917        mNetTrackers[prevNetType].setTeardownRequested(false);
1918
1919        // Remove idletimer previously setup in {@code handleConnect}
1920        removeDataActivityTracking(prevNetType);
1921
1922        /*
1923         * If the disconnected network is not the active one, then don't report
1924         * this as a loss of connectivity. What probably happened is that we're
1925         * getting the disconnect for a network that we explicitly disabled
1926         * in accordance with network preference policies.
1927         */
1928        if (!mNetConfigs[prevNetType].isDefault()) {
1929            List<Integer> pids = mNetRequestersPids[prevNetType];
1930            for (Integer pid : pids) {
1931                // will remove them because the net's no longer connected
1932                // need to do this now as only now do we know the pids and
1933                // can properly null things that are no longer referenced.
1934                reassessPidDns(pid.intValue(), false);
1935            }
1936        }
1937
1938        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1939        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1940        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1941        if (info.isFailover()) {
1942            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1943            info.setFailover(false);
1944        }
1945        if (info.getReason() != null) {
1946            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1947        }
1948        if (info.getExtraInfo() != null) {
1949            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1950                    info.getExtraInfo());
1951        }
1952
1953        if (mNetConfigs[prevNetType].isDefault()) {
1954            tryFailover(prevNetType);
1955            if (mActiveDefaultNetwork != -1) {
1956                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1957                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1958            } else {
1959                mDefaultInetConditionPublished = 0; // we're not connected anymore
1960                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1961            }
1962        }
1963        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1964
1965        // Reset interface if no other connections are using the same interface
1966        boolean doReset = true;
1967        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1968        if (linkProperties != null) {
1969            String oldIface = linkProperties.getInterfaceName();
1970            if (TextUtils.isEmpty(oldIface) == false) {
1971                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1972                    if (networkStateTracker == null) continue;
1973                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1974                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1975                        LinkProperties l = networkStateTracker.getLinkProperties();
1976                        if (l == null) continue;
1977                        if (oldIface.equals(l.getInterfaceName())) {
1978                            doReset = false;
1979                            break;
1980                        }
1981                    }
1982                }
1983            }
1984        }
1985
1986        // do this before we broadcast the change
1987        handleConnectivityChange(prevNetType, doReset);
1988
1989        final Intent immediateIntent = new Intent(intent);
1990        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1991        sendStickyBroadcast(immediateIntent);
1992        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1993        /*
1994         * If the failover network is already connected, then immediately send
1995         * out a followup broadcast indicating successful failover
1996         */
1997        if (mActiveDefaultNetwork != -1) {
1998            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1999                    getConnectivityChangeDelay());
2000        }
2001    }
2002
2003    private void tryFailover(int prevNetType) {
2004        /*
2005         * If this is a default network, check if other defaults are available.
2006         * Try to reconnect on all available and let them hash it out when
2007         * more than one connects.
2008         */
2009        if (mNetConfigs[prevNetType].isDefault()) {
2010            if (mActiveDefaultNetwork == prevNetType) {
2011                if (DBG) {
2012                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2013                }
2014                mActiveDefaultNetwork = -1;
2015            }
2016
2017            // don't signal a reconnect for anything lower or equal priority than our
2018            // current connected default
2019            // TODO - don't filter by priority now - nice optimization but risky
2020//            int currentPriority = -1;
2021//            if (mActiveDefaultNetwork != -1) {
2022//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
2023//            }
2024
2025            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
2026                if (checkType == prevNetType) continue;
2027                if (mNetConfigs[checkType] == null) continue;
2028                if (!mNetConfigs[checkType].isDefault()) continue;
2029                if (mNetTrackers[checkType] == null) continue;
2030
2031// Enabling the isAvailable() optimization caused mobile to not get
2032// selected if it was in the middle of error handling. Specifically
2033// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2034// would not be available and we wouldn't get connected to anything.
2035// So removing the isAvailable() optimization below for now. TODO: This
2036// optimization should work and we need to investigate why it doesn't work.
2037// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2038// complete before it is really complete.
2039
2040//                if (!mNetTrackers[checkType].isAvailable()) continue;
2041
2042//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
2043
2044                NetworkStateTracker checkTracker = mNetTrackers[checkType];
2045                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2046                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2047                    checkInfo.setFailover(true);
2048                    checkTracker.reconnect();
2049                }
2050                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
2051            }
2052        }
2053    }
2054
2055    public void sendConnectedBroadcast(NetworkInfo info) {
2056        enforceConnectivityInternalPermission();
2057        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2058        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2059    }
2060
2061    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
2062        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2063        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
2064    }
2065
2066    private void sendInetConditionBroadcast(NetworkInfo info) {
2067        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2068    }
2069
2070    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2071        if (mLockdownTracker != null) {
2072            info = mLockdownTracker.augmentNetworkInfo(info);
2073        }
2074
2075        Intent intent = new Intent(bcastType);
2076        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2077        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2078        if (info.isFailover()) {
2079            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2080            info.setFailover(false);
2081        }
2082        if (info.getReason() != null) {
2083            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2084        }
2085        if (info.getExtraInfo() != null) {
2086            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2087                    info.getExtraInfo());
2088        }
2089        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2090        return intent;
2091    }
2092
2093    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2094        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2095    }
2096
2097    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2098        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
2099    }
2100
2101    private void sendDataActivityBroadcast(int deviceType, boolean active) {
2102        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2103        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2104        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
2105        final long ident = Binder.clearCallingIdentity();
2106        try {
2107            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2108                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2109        } finally {
2110            Binder.restoreCallingIdentity(ident);
2111        }
2112    }
2113
2114    /**
2115     * Called when an attempt to fail over to another network has failed.
2116     * @param info the {@link NetworkInfo} for the failed network
2117     */
2118    private void handleConnectionFailure(NetworkInfo info) {
2119        mNetTrackers[info.getType()].setTeardownRequested(false);
2120
2121        String reason = info.getReason();
2122        String extraInfo = info.getExtraInfo();
2123
2124        String reasonText;
2125        if (reason == null) {
2126            reasonText = ".";
2127        } else {
2128            reasonText = " (" + reason + ").";
2129        }
2130        loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
2131
2132        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
2133        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2134        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2135        if (getActiveNetworkInfo() == null) {
2136            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2137        }
2138        if (reason != null) {
2139            intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2140        }
2141        if (extraInfo != null) {
2142            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2143        }
2144        if (info.isFailover()) {
2145            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2146            info.setFailover(false);
2147        }
2148
2149        if (mNetConfigs[info.getType()].isDefault()) {
2150            tryFailover(info.getType());
2151            if (mActiveDefaultNetwork != -1) {
2152                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2153                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2154            } else {
2155                mDefaultInetConditionPublished = 0;
2156                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2157            }
2158        }
2159
2160        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2161
2162        final Intent immediateIntent = new Intent(intent);
2163        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2164        sendStickyBroadcast(immediateIntent);
2165        sendStickyBroadcast(intent);
2166        /*
2167         * If the failover network is already connected, then immediately send
2168         * out a followup broadcast indicating successful failover
2169         */
2170        if (mActiveDefaultNetwork != -1) {
2171            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
2172        }
2173    }
2174
2175    private void sendStickyBroadcast(Intent intent) {
2176        synchronized(this) {
2177            if (!mSystemReady) {
2178                mInitialBroadcast = new Intent(intent);
2179            }
2180            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2181            if (VDBG) {
2182                log("sendStickyBroadcast: action=" + intent.getAction());
2183            }
2184
2185            final long ident = Binder.clearCallingIdentity();
2186            try {
2187                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2188            } finally {
2189                Binder.restoreCallingIdentity(ident);
2190            }
2191        }
2192    }
2193
2194    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2195        if (delayMs <= 0) {
2196            sendStickyBroadcast(intent);
2197        } else {
2198            if (VDBG) {
2199                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2200                        + intent.getAction());
2201            }
2202            mHandler.sendMessageDelayed(mHandler.obtainMessage(
2203                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2204        }
2205    }
2206
2207    void systemReady() {
2208        mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2209        loadGlobalProxy();
2210
2211        synchronized(this) {
2212            mSystemReady = true;
2213            if (mInitialBroadcast != null) {
2214                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2215                mInitialBroadcast = null;
2216            }
2217        }
2218        // load the global proxy at startup
2219        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2220
2221        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2222        // for user to unlock device.
2223        if (!updateLockdownVpn()) {
2224            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2225            mContext.registerReceiver(mUserPresentReceiver, filter);
2226        }
2227    }
2228
2229    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2230        @Override
2231        public void onReceive(Context context, Intent intent) {
2232            // Try creating lockdown tracker, since user present usually means
2233            // unlocked keystore.
2234            if (updateLockdownVpn()) {
2235                mContext.unregisterReceiver(this);
2236            }
2237        }
2238    };
2239
2240    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2241        if (((type != mNetworkPreference)
2242                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2243                   || (mNetworkPreference == mActiveDefaultNetwork)) {
2244            return false;
2245        }
2246        return true;
2247    }
2248
2249    private void handleConnect(NetworkInfo info) {
2250        final int newNetType = info.getType();
2251
2252        setupDataActivityTracking(newNetType);
2253
2254        // snapshot isFailover, because sendConnectedBroadcast() resets it
2255        boolean isFailover = info.isFailover();
2256        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2257        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2258
2259        if (VDBG) {
2260            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2261                    + " isFailover" + isFailover);
2262        }
2263
2264        // if this is a default net and other default is running
2265        // kill the one not preferred
2266        if (mNetConfigs[newNetType].isDefault()) {
2267            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2268                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2269                    // tear down the other
2270                    NetworkStateTracker otherNet =
2271                            mNetTrackers[mActiveDefaultNetwork];
2272                    if (DBG) {
2273                        log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2274                            " teardown");
2275                    }
2276                    if (!teardown(otherNet)) {
2277                        loge("Network declined teardown request");
2278                        teardown(thisNet);
2279                        return;
2280                    }
2281                } else {
2282                       // don't accept this one
2283                        if (VDBG) {
2284                            log("Not broadcasting CONNECT_ACTION " +
2285                                "to torn down network " + info.getTypeName());
2286                        }
2287                        teardown(thisNet);
2288                        return;
2289                }
2290            }
2291            synchronized (ConnectivityService.this) {
2292                // have a new default network, release the transition wakelock in a second
2293                // if it's held.  The second pause is to allow apps to reconnect over the
2294                // new network
2295                if (mNetTransitionWakeLock.isHeld()) {
2296                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
2297                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2298                            mNetTransitionWakeLockSerialNumber, 0),
2299                            1000);
2300                }
2301            }
2302            mActiveDefaultNetwork = newNetType;
2303            // this will cause us to come up initially as unconnected and switching
2304            // to connected after our normal pause unless somebody reports us as reall
2305            // disconnected
2306            mDefaultInetConditionPublished = 0;
2307            mDefaultConnectionSequence++;
2308            mInetConditionChangeInFlight = false;
2309            // Don't do this - if we never sign in stay, grey
2310            //reportNetworkCondition(mActiveDefaultNetwork, 100);
2311        }
2312        thisNet.setTeardownRequested(false);
2313        updateNetworkSettings(thisNet);
2314        updateMtuSizeSettings(thisNet);
2315        handleConnectivityChange(newNetType, false);
2316        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2317
2318        // notify battery stats service about this network
2319        if (thisIface != null) {
2320            try {
2321                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2322            } catch (RemoteException e) {
2323                // ignored; service lives in system_server
2324            }
2325        }
2326    }
2327
2328    private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2329        if (DBG) log("Captive portal check " + info);
2330        int type = info.getType();
2331        final NetworkStateTracker thisNet = mNetTrackers[type];
2332        if (mNetConfigs[type].isDefault()) {
2333            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2334                if (isNewNetTypePreferredOverCurrentNetType(type)) {
2335                    if (DBG) log("Captive check on " + info.getTypeName());
2336                    mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
2337                    return;
2338                } else {
2339                    if (DBG) log("Tear down low priority net " + info.getTypeName());
2340                    teardown(thisNet);
2341                    return;
2342                }
2343            }
2344        }
2345
2346        if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
2347        thisNet.captivePortalCheckComplete();
2348    }
2349
2350    /** @hide */
2351    @Override
2352    public void captivePortalCheckComplete(NetworkInfo info) {
2353        enforceConnectivityInternalPermission();
2354        if (DBG) log("captivePortalCheckComplete: ni=" + info);
2355        mNetTrackers[info.getType()].captivePortalCheckComplete();
2356    }
2357
2358    /** @hide */
2359    @Override
2360    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2361        enforceConnectivityInternalPermission();
2362        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2363        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2364    }
2365
2366    /**
2367     * Setup data activity tracking for the given network interface.
2368     *
2369     * Every {@code setupDataActivityTracking} should be paired with a
2370     * {@link removeDataActivityTracking} for cleanup.
2371     */
2372    private void setupDataActivityTracking(int type) {
2373        final NetworkStateTracker thisNet = mNetTrackers[type];
2374        final String iface = thisNet.getLinkProperties().getInterfaceName();
2375
2376        final int timeout;
2377
2378        if (ConnectivityManager.isNetworkTypeMobile(type)) {
2379            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2380                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2381                                             0);
2382            // Canonicalize mobile network type
2383            type = ConnectivityManager.TYPE_MOBILE;
2384        } else if (ConnectivityManager.TYPE_WIFI == type) {
2385            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2386                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2387                                             0);
2388        } else {
2389            // do not track any other networks
2390            timeout = 0;
2391        }
2392
2393        if (timeout > 0 && iface != null) {
2394            try {
2395                mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2396            } catch (RemoteException e) {
2397            }
2398        }
2399    }
2400
2401    /**
2402     * Remove data activity tracking when network disconnects.
2403     */
2404    private void removeDataActivityTracking(int type) {
2405        final NetworkStateTracker net = mNetTrackers[type];
2406        final String iface = net.getLinkProperties().getInterfaceName();
2407
2408        if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2409                              ConnectivityManager.TYPE_WIFI == type)) {
2410            try {
2411                // the call fails silently if no idletimer setup for this interface
2412                mNetd.removeIdleTimer(iface);
2413            } catch (RemoteException e) {
2414            }
2415        }
2416    }
2417
2418    /**
2419     * After a change in the connectivity state of a network. We're mainly
2420     * concerned with making sure that the list of DNS servers is set up
2421     * according to which networks are connected, and ensuring that the
2422     * right routing table entries exist.
2423     */
2424    private void handleConnectivityChange(int netType, boolean doReset) {
2425        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2426        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
2427        if (VDBG) {
2428            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2429                    + " resetMask=" + resetMask);
2430        }
2431
2432        /*
2433         * If a non-default network is enabled, add the host routes that
2434         * will allow it's DNS servers to be accessed.
2435         */
2436        handleDnsConfigurationChange(netType);
2437
2438        LinkProperties curLp = mCurrentLinkProperties[netType];
2439        LinkProperties newLp = null;
2440
2441        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2442            newLp = mNetTrackers[netType].getLinkProperties();
2443            if (VDBG) {
2444                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2445                        " doReset=" + doReset + " resetMask=" + resetMask +
2446                        "\n   curLp=" + curLp +
2447                        "\n   newLp=" + newLp);
2448            }
2449
2450            if (curLp != null) {
2451                if (curLp.isIdenticalInterfaceName(newLp)) {
2452                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2453                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2454                        for (LinkAddress linkAddr : car.removed) {
2455                            if (linkAddr.getAddress() instanceof Inet4Address) {
2456                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2457                            }
2458                            if (linkAddr.getAddress() instanceof Inet6Address) {
2459                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2460                            }
2461                        }
2462                        if (DBG) {
2463                            log("handleConnectivityChange: addresses changed" +
2464                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2465                                    "\n   car=" + car);
2466                        }
2467                    } else {
2468                        if (DBG) {
2469                            log("handleConnectivityChange: address are the same reset per doReset" +
2470                                   " linkProperty[" + netType + "]:" +
2471                                   " resetMask=" + resetMask);
2472                        }
2473                    }
2474                } else {
2475                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2476                    if (DBG) {
2477                        log("handleConnectivityChange: interface not not equivalent reset both" +
2478                                " linkProperty[" + netType + "]:" +
2479                                " resetMask=" + resetMask);
2480                    }
2481                }
2482            }
2483            if (mNetConfigs[netType].isDefault()) {
2484                handleApplyDefaultProxy(newLp.getHttpProxy());
2485            }
2486        } else {
2487            if (VDBG) {
2488                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2489                        " doReset=" + doReset + " resetMask=" + resetMask +
2490                        "\n  curLp=" + curLp +
2491                        "\n  newLp= null");
2492            }
2493        }
2494        mCurrentLinkProperties[netType] = newLp;
2495        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
2496
2497        if (resetMask != 0 || resetDns) {
2498            if (VDBG) log("handleConnectivityChange: resetting");
2499            if (curLp != null) {
2500                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
2501                for (String iface : curLp.getAllInterfaceNames()) {
2502                    if (TextUtils.isEmpty(iface) == false) {
2503                        if (resetMask != 0) {
2504                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2505                            NetworkUtils.resetConnections(iface, resetMask);
2506
2507                            // Tell VPN the interface is down. It is a temporary
2508                            // but effective fix to make VPN aware of the change.
2509                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2510                                synchronized(mVpns) {
2511                                    for (int i = 0; i < mVpns.size(); i++) {
2512                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2513                                    }
2514                                }
2515                            }
2516                        }
2517                        if (resetDns) {
2518                            flushVmDnsCache();
2519                            if (VDBG) log("resetting DNS cache for " + iface);
2520                            try {
2521                                mNetd.flushInterfaceDnsCache(iface);
2522                            } catch (Exception e) {
2523                                // never crash - catch them all
2524                                if (DBG) loge("Exception resetting dns cache: " + e);
2525                            }
2526                        }
2527                    } else {
2528                        loge("Can't reset connection for type "+netType);
2529                    }
2530                }
2531            }
2532        }
2533
2534        // Update 464xlat state.
2535        NetworkStateTracker tracker = mNetTrackers[netType];
2536        if (mClat.requiresClat(netType, tracker)) {
2537
2538            // If the connection was previously using clat, but is not using it now, stop the clat
2539            // daemon. Normally, this happens automatically when the connection disconnects, but if
2540            // the disconnect is not reported, or if the connection's LinkProperties changed for
2541            // some other reason (e.g., handoff changes the IP addresses on the link), it would
2542            // still be running. If it's not running, then stopping it is a no-op.
2543            if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2544                mClat.stopClat();
2545            }
2546            // If the link requires clat to be running, then start the daemon now.
2547            if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2548                mClat.startClat(tracker);
2549            } else {
2550                mClat.stopClat();
2551            }
2552        }
2553
2554        // TODO: Temporary notifying upstread change to Tethering.
2555        //       @see bug/4455071
2556        /** Notify TetheringService if interface name has been changed. */
2557        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2558                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2559            if (isTetheringSupported()) {
2560                mTethering.handleTetherIfaceChange();
2561            }
2562        }
2563    }
2564
2565    /**
2566     * Add and remove routes using the old properties (null if not previously connected),
2567     * new properties (null if becoming disconnected).  May even be double null, which
2568     * is a noop.
2569     * Uses isLinkDefault to determine if default routes should be set or conversely if
2570     * host routes should be set to the dns servers
2571     * returns a boolean indicating the routes changed
2572     */
2573    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2574            boolean isLinkDefault, boolean exempt) {
2575        Collection<RouteInfo> routesToAdd = null;
2576        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2577        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2578        if (curLp != null) {
2579            // check for the delta between the current set and the new
2580            routeDiff = curLp.compareAllRoutes(newLp);
2581            dnsDiff = curLp.compareDnses(newLp);
2582        } else if (newLp != null) {
2583            routeDiff.added = newLp.getAllRoutes();
2584            dnsDiff.added = newLp.getDnses();
2585        }
2586
2587        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2588
2589        for (RouteInfo r : routeDiff.removed) {
2590            if (isLinkDefault || ! r.isDefaultRoute()) {
2591                if (VDBG) log("updateRoutes: default remove route r=" + r);
2592                removeRoute(curLp, r, TO_DEFAULT_TABLE);
2593            }
2594            if (isLinkDefault == false) {
2595                // remove from a secondary route table
2596                removeRoute(curLp, r, TO_SECONDARY_TABLE);
2597            }
2598        }
2599
2600        if (!isLinkDefault) {
2601            // handle DNS routes
2602            if (routesChanged) {
2603                // routes changed - remove all old dns entries and add new
2604                if (curLp != null) {
2605                    for (InetAddress oldDns : curLp.getDnses()) {
2606                        removeRouteToAddress(curLp, oldDns);
2607                    }
2608                }
2609                if (newLp != null) {
2610                    for (InetAddress newDns : newLp.getDnses()) {
2611                        addRouteToAddress(newLp, newDns, exempt);
2612                    }
2613                }
2614            } else {
2615                // no change in routes, check for change in dns themselves
2616                for (InetAddress oldDns : dnsDiff.removed) {
2617                    removeRouteToAddress(curLp, oldDns);
2618                }
2619                for (InetAddress newDns : dnsDiff.added) {
2620                    addRouteToAddress(newLp, newDns, exempt);
2621                }
2622            }
2623        }
2624
2625        for (RouteInfo r :  routeDiff.added) {
2626            if (isLinkDefault || ! r.isDefaultRoute()) {
2627                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
2628            } else {
2629                // add to a secondary route table
2630                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
2631
2632                // many radios add a default route even when we don't want one.
2633                // remove the default route unless somebody else has asked for it
2634                String ifaceName = newLp.getInterfaceName();
2635                synchronized (mRoutesLock) {
2636                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2637                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2638                        try {
2639                            mNetd.removeRoute(ifaceName, r);
2640                        } catch (Exception e) {
2641                            // never crash - catch them all
2642                            if (DBG) loge("Exception trying to remove a route: " + e);
2643                        }
2644                    }
2645                }
2646            }
2647        }
2648
2649        return routesChanged;
2650    }
2651
2652   /**
2653     * Reads the network specific MTU size from reources.
2654     * and set it on it's iface.
2655     */
2656   private void updateMtuSizeSettings(NetworkStateTracker nt) {
2657       final String iface = nt.getLinkProperties().getInterfaceName();
2658       final int mtu = nt.getLinkProperties().getMtu();
2659
2660       if (mtu < 68 || mtu > 10000) {
2661           loge("Unexpected mtu value: " + nt);
2662           return;
2663       }
2664
2665       try {
2666           if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2667           mNetd.setMtu(iface, mtu);
2668       } catch (Exception e) {
2669           Slog.e(TAG, "exception in setMtu()" + e);
2670       }
2671   }
2672
2673    /**
2674     * Reads the network specific TCP buffer sizes from SystemProperties
2675     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2676     * wide use
2677     */
2678    private void updateNetworkSettings(NetworkStateTracker nt) {
2679        String key = nt.getTcpBufferSizesPropName();
2680        String bufferSizes = key == null ? null : SystemProperties.get(key);
2681
2682        if (TextUtils.isEmpty(bufferSizes)) {
2683            if (VDBG) log(key + " not found in system properties. Using defaults");
2684
2685            // Setting to default values so we won't be stuck to previous values
2686            key = "net.tcp.buffersize.default";
2687            bufferSizes = SystemProperties.get(key);
2688        }
2689
2690        // Set values in kernel
2691        if (bufferSizes.length() != 0) {
2692            if (VDBG) {
2693                log("Setting TCP values: [" + bufferSizes
2694                        + "] which comes from [" + key + "]");
2695            }
2696            setBufferSize(bufferSizes);
2697        }
2698    }
2699
2700    /**
2701     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2702     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2703     *
2704     * @param bufferSizes in the format of "readMin, readInitial, readMax,
2705     *        writeMin, writeInitial, writeMax"
2706     */
2707    private void setBufferSize(String bufferSizes) {
2708        try {
2709            String[] values = bufferSizes.split(",");
2710
2711            if (values.length == 6) {
2712              final String prefix = "/sys/kernel/ipv4/tcp_";
2713                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2714                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2715                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2716                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2717                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2718                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2719            } else {
2720                loge("Invalid buffersize string: " + bufferSizes);
2721            }
2722        } catch (IOException e) {
2723            loge("Can't set tcp buffer sizes:" + e);
2724        }
2725    }
2726
2727    /**
2728     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2729     * on the highest priority active net which this process requested.
2730     * If there aren't any, clear it out
2731     */
2732    private void reassessPidDns(int pid, boolean doBump)
2733    {
2734        if (VDBG) log("reassessPidDns for pid " + pid);
2735        Integer myPid = new Integer(pid);
2736        for(int i : mPriorityList) {
2737            if (mNetConfigs[i].isDefault()) {
2738                continue;
2739            }
2740            NetworkStateTracker nt = mNetTrackers[i];
2741            if (nt.getNetworkInfo().isConnected() &&
2742                    !nt.isTeardownRequested()) {
2743                LinkProperties p = nt.getLinkProperties();
2744                if (p == null) continue;
2745                if (mNetRequestersPids[i].contains(myPid)) {
2746                    try {
2747                        mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2748                    } catch (Exception e) {
2749                        Slog.e(TAG, "exception reasseses pid dns: " + e);
2750                    }
2751                    return;
2752                }
2753           }
2754        }
2755        // nothing found - delete
2756        try {
2757            mNetd.clearDnsInterfaceForPid(pid);
2758        } catch (Exception e) {
2759            Slog.e(TAG, "exception clear interface from pid: " + e);
2760        }
2761    }
2762
2763    private void flushVmDnsCache() {
2764        /*
2765         * Tell the VMs to toss their DNS caches
2766         */
2767        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2768        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2769        /*
2770         * Connectivity events can happen before boot has completed ...
2771         */
2772        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2773        final long ident = Binder.clearCallingIdentity();
2774        try {
2775            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2776        } finally {
2777            Binder.restoreCallingIdentity(ident);
2778        }
2779    }
2780
2781    // Caller must grab mDnsLock.
2782    private void updateDnsLocked(String network, String iface,
2783            Collection<InetAddress> dnses, String domains, boolean defaultDns) {
2784        int last = 0;
2785        if (dnses.size() == 0 && mDefaultDns != null) {
2786            dnses = new ArrayList();
2787            dnses.add(mDefaultDns);
2788            if (DBG) {
2789                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2790            }
2791        }
2792
2793        try {
2794            mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2795            if (defaultDns) {
2796                mNetd.setDefaultInterfaceForDns(iface);
2797            }
2798
2799            for (InetAddress dns : dnses) {
2800                ++last;
2801                String key = "net.dns" + last;
2802                String value = dns.getHostAddress();
2803                SystemProperties.set(key, value);
2804            }
2805            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2806                String key = "net.dns" + i;
2807                SystemProperties.set(key, "");
2808            }
2809            mNumDnsEntries = last;
2810        } catch (Exception e) {
2811            loge("exception setting default dns interface: " + e);
2812        }
2813    }
2814
2815    private void handleDnsConfigurationChange(int netType) {
2816        // add default net's dns entries
2817        NetworkStateTracker nt = mNetTrackers[netType];
2818        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2819            LinkProperties p = nt.getLinkProperties();
2820            if (p == null) return;
2821            Collection<InetAddress> dnses = p.getDnses();
2822            if (mNetConfigs[netType].isDefault()) {
2823                String network = nt.getNetworkInfo().getTypeName();
2824                synchronized (mDnsLock) {
2825                    updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
2826                }
2827            } else {
2828                try {
2829                    mNetd.setDnsServersForInterface(p.getInterfaceName(),
2830                            NetworkUtils.makeStrings(dnses), p.getDomains());
2831                } catch (Exception e) {
2832                    if (DBG) loge("exception setting dns servers: " + e);
2833                }
2834                // set per-pid dns for attached secondary nets
2835                List<Integer> pids = mNetRequestersPids[netType];
2836                for (Integer pid : pids) {
2837                    try {
2838                        mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2839                    } catch (Exception e) {
2840                        Slog.e(TAG, "exception setting interface for pid: " + e);
2841                    }
2842                }
2843            }
2844            flushVmDnsCache();
2845        }
2846    }
2847
2848    private int getRestoreDefaultNetworkDelay(int networkType) {
2849        String restoreDefaultNetworkDelayStr = SystemProperties.get(
2850                NETWORK_RESTORE_DELAY_PROP_NAME);
2851        if(restoreDefaultNetworkDelayStr != null &&
2852                restoreDefaultNetworkDelayStr.length() != 0) {
2853            try {
2854                return Integer.valueOf(restoreDefaultNetworkDelayStr);
2855            } catch (NumberFormatException e) {
2856            }
2857        }
2858        // if the system property isn't set, use the value for the apn type
2859        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2860
2861        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2862                (mNetConfigs[networkType] != null)) {
2863            ret = mNetConfigs[networkType].restoreTime;
2864        }
2865        return ret;
2866    }
2867
2868    @Override
2869    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2870        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2871        if (mContext.checkCallingOrSelfPermission(
2872                android.Manifest.permission.DUMP)
2873                != PackageManager.PERMISSION_GRANTED) {
2874            pw.println("Permission Denial: can't dump ConnectivityService " +
2875                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
2876                    Binder.getCallingUid());
2877            return;
2878        }
2879
2880        // TODO: add locking to get atomic snapshot
2881        pw.println();
2882        for (int i = 0; i < mNetTrackers.length; i++) {
2883            final NetworkStateTracker nst = mNetTrackers[i];
2884            if (nst != null) {
2885                pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2886                pw.increaseIndent();
2887                if (nst.getNetworkInfo().isConnected()) {
2888                    pw.println("Active network: " + nst.getNetworkInfo().
2889                            getTypeName());
2890                }
2891                pw.println(nst.getNetworkInfo());
2892                pw.println(nst.getLinkProperties());
2893                pw.println(nst);
2894                pw.println();
2895                pw.decreaseIndent();
2896            }
2897        }
2898
2899        pw.println("Network Requester Pids:");
2900        pw.increaseIndent();
2901        for (int net : mPriorityList) {
2902            String pidString = net + ": ";
2903            for (Integer pid : mNetRequestersPids[net]) {
2904                pidString = pidString + pid.toString() + ", ";
2905            }
2906            pw.println(pidString);
2907        }
2908        pw.println();
2909        pw.decreaseIndent();
2910
2911        pw.println("FeatureUsers:");
2912        pw.increaseIndent();
2913        for (Object requester : mFeatureUsers) {
2914            pw.println(requester.toString());
2915        }
2916        pw.println();
2917        pw.decreaseIndent();
2918
2919        synchronized (this) {
2920            pw.println("NetworkTranstionWakeLock is currently " +
2921                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2922            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2923        }
2924        pw.println();
2925
2926        mTethering.dump(fd, pw, args);
2927
2928        if (mInetLog != null) {
2929            pw.println();
2930            pw.println("Inet condition reports:");
2931            pw.increaseIndent();
2932            for(int i = 0; i < mInetLog.size(); i++) {
2933                pw.println(mInetLog.get(i));
2934            }
2935            pw.decreaseIndent();
2936        }
2937    }
2938
2939    // must be stateless - things change under us.
2940    private class NetworkStateTrackerHandler extends Handler {
2941        public NetworkStateTrackerHandler(Looper looper) {
2942            super(looper);
2943        }
2944
2945        @Override
2946        public void handleMessage(Message msg) {
2947            NetworkInfo info;
2948            switch (msg.what) {
2949                case NetworkStateTracker.EVENT_STATE_CHANGED: {
2950                    info = (NetworkInfo) msg.obj;
2951                    NetworkInfo.State state = info.getState();
2952
2953                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2954                            (state == NetworkInfo.State.DISCONNECTED) ||
2955                            (state == NetworkInfo.State.SUSPENDED)) {
2956                        log("ConnectivityChange for " +
2957                            info.getTypeName() + ": " +
2958                            state + "/" + info.getDetailedState());
2959                    }
2960
2961                    // Since mobile has the notion of a network/apn that can be used for
2962                    // provisioning we need to check every time we're connected as
2963                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
2964                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2965                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2966                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
2967                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
2968                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2969                                        Settings.Global.DEVICE_PROVISIONED, 0))
2970                            && (((state == NetworkInfo.State.CONNECTED)
2971                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2972                                || info.isConnectedToProvisioningNetwork())) {
2973                        log("ConnectivityChange checkMobileProvisioning for"
2974                                + " TYPE_MOBILE or ProvisioningNetwork");
2975                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
2976                    }
2977
2978                    EventLogTags.writeConnectivityStateChanged(
2979                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2980
2981                    if (info.getDetailedState() ==
2982                            NetworkInfo.DetailedState.FAILED) {
2983                        handleConnectionFailure(info);
2984                    } else if (info.getDetailedState() ==
2985                            DetailedState.CAPTIVE_PORTAL_CHECK) {
2986                        handleCaptivePortalTrackerCheck(info);
2987                    } else if (info.isConnectedToProvisioningNetwork()) {
2988                        /**
2989                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2990                         * for now its an in between network, its a network that
2991                         * is actually a default network but we don't want it to be
2992                         * announced as such to keep background applications from
2993                         * trying to use it. It turns out that some still try so we
2994                         * take the additional step of clearing any default routes
2995                         * to the link that may have incorrectly setup by the lower
2996                         * levels.
2997                         */
2998                        LinkProperties lp = getLinkProperties(info.getType());
2999                        if (DBG) {
3000                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3001                        }
3002
3003                        // Clear any default routes setup by the radio so
3004                        // any activity by applications trying to use this
3005                        // connection will fail until the provisioning network
3006                        // is enabled.
3007                        for (RouteInfo r : lp.getRoutes()) {
3008                            removeRoute(lp, r, TO_DEFAULT_TABLE);
3009                        }
3010                    } else if (state == NetworkInfo.State.DISCONNECTED) {
3011                        handleDisconnect(info);
3012                    } else if (state == NetworkInfo.State.SUSPENDED) {
3013                        // TODO: need to think this over.
3014                        // the logic here is, handle SUSPENDED the same as
3015                        // DISCONNECTED. The only difference being we are
3016                        // broadcasting an intent with NetworkInfo that's
3017                        // suspended. This allows the applications an
3018                        // opportunity to handle DISCONNECTED and SUSPENDED
3019                        // differently, or not.
3020                        handleDisconnect(info);
3021                    } else if (state == NetworkInfo.State.CONNECTED) {
3022                        handleConnect(info);
3023                    }
3024                    if (mLockdownTracker != null) {
3025                        mLockdownTracker.onNetworkInfoChanged(info);
3026                    }
3027                    break;
3028                }
3029                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
3030                    info = (NetworkInfo) msg.obj;
3031                    // TODO: Temporary allowing network configuration
3032                    //       change not resetting sockets.
3033                    //       @see bug/4455071
3034                    handleConnectivityChange(info.getType(), false);
3035                    break;
3036                }
3037                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
3038                    info = (NetworkInfo) msg.obj;
3039                    int type = info.getType();
3040                    updateNetworkSettings(mNetTrackers[type]);
3041                    break;
3042                }
3043            }
3044        }
3045    }
3046
3047    private class InternalHandler extends Handler {
3048        public InternalHandler(Looper looper) {
3049            super(looper);
3050        }
3051
3052        @Override
3053        public void handleMessage(Message msg) {
3054            NetworkInfo info;
3055            switch (msg.what) {
3056                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
3057                    String causedBy = null;
3058                    synchronized (ConnectivityService.this) {
3059                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3060                                mNetTransitionWakeLock.isHeld()) {
3061                            mNetTransitionWakeLock.release();
3062                            causedBy = mNetTransitionWakeLockCausedBy;
3063                        }
3064                    }
3065                    if (causedBy != null) {
3066                        log("NetTransition Wakelock for " + causedBy + " released by timeout");
3067                    }
3068                    break;
3069                }
3070                case EVENT_RESTORE_DEFAULT_NETWORK: {
3071                    FeatureUser u = (FeatureUser)msg.obj;
3072                    u.expire();
3073                    break;
3074                }
3075                case EVENT_INET_CONDITION_CHANGE: {
3076                    int netType = msg.arg1;
3077                    int condition = msg.arg2;
3078                    handleInetConditionChange(netType, condition);
3079                    break;
3080                }
3081                case EVENT_INET_CONDITION_HOLD_END: {
3082                    int netType = msg.arg1;
3083                    int sequence = msg.arg2;
3084                    handleInetConditionHoldEnd(netType, sequence);
3085                    break;
3086                }
3087                case EVENT_SET_NETWORK_PREFERENCE: {
3088                    int preference = msg.arg1;
3089                    handleSetNetworkPreference(preference);
3090                    break;
3091                }
3092                case EVENT_SET_MOBILE_DATA: {
3093                    boolean enabled = (msg.arg1 == ENABLED);
3094                    handleSetMobileData(enabled);
3095                    break;
3096                }
3097                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
3098                    handleDeprecatedGlobalHttpProxy();
3099                    break;
3100                }
3101                case EVENT_SET_DEPENDENCY_MET: {
3102                    boolean met = (msg.arg1 == ENABLED);
3103                    handleSetDependencyMet(msg.arg2, met);
3104                    break;
3105                }
3106                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
3107                    Intent intent = (Intent)msg.obj;
3108                    sendStickyBroadcast(intent);
3109                    break;
3110                }
3111                case EVENT_SET_POLICY_DATA_ENABLE: {
3112                    final int networkType = msg.arg1;
3113                    final boolean enabled = msg.arg2 == ENABLED;
3114                    handleSetPolicyDataEnable(networkType, enabled);
3115                    break;
3116                }
3117                case EVENT_VPN_STATE_CHANGED: {
3118                    if (mLockdownTracker != null) {
3119                        mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3120                    }
3121                    break;
3122                }
3123                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3124                    int tag = mEnableFailFastMobileDataTag.get();
3125                    if (msg.arg1 == tag) {
3126                        MobileDataStateTracker mobileDst =
3127                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3128                        if (mobileDst != null) {
3129                            mobileDst.setEnableFailFastMobileData(msg.arg2);
3130                        }
3131                    } else {
3132                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3133                                + " != tag:" + tag);
3134                    }
3135                    break;
3136                }
3137                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
3138                    handleNetworkSamplingTimeout();
3139                    break;
3140                }
3141                case EVENT_PROXY_HAS_CHANGED: {
3142                    handleApplyDefaultProxy((ProxyProperties)msg.obj);
3143                    break;
3144                }
3145            }
3146        }
3147    }
3148
3149    // javadoc from interface
3150    public int tether(String iface) {
3151        enforceTetherChangePermission();
3152
3153        if (isTetheringSupported()) {
3154            return mTethering.tether(iface);
3155        } else {
3156            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3157        }
3158    }
3159
3160    // javadoc from interface
3161    public int untether(String iface) {
3162        enforceTetherChangePermission();
3163
3164        if (isTetheringSupported()) {
3165            return mTethering.untether(iface);
3166        } else {
3167            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3168        }
3169    }
3170
3171    // javadoc from interface
3172    public int getLastTetherError(String iface) {
3173        enforceTetherAccessPermission();
3174
3175        if (isTetheringSupported()) {
3176            return mTethering.getLastTetherError(iface);
3177        } else {
3178            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3179        }
3180    }
3181
3182    // TODO - proper iface API for selection by property, inspection, etc
3183    public String[] getTetherableUsbRegexs() {
3184        enforceTetherAccessPermission();
3185        if (isTetheringSupported()) {
3186            return mTethering.getTetherableUsbRegexs();
3187        } else {
3188            return new String[0];
3189        }
3190    }
3191
3192    public String[] getTetherableWifiRegexs() {
3193        enforceTetherAccessPermission();
3194        if (isTetheringSupported()) {
3195            return mTethering.getTetherableWifiRegexs();
3196        } else {
3197            return new String[0];
3198        }
3199    }
3200
3201    public String[] getTetherableBluetoothRegexs() {
3202        enforceTetherAccessPermission();
3203        if (isTetheringSupported()) {
3204            return mTethering.getTetherableBluetoothRegexs();
3205        } else {
3206            return new String[0];
3207        }
3208    }
3209
3210    public int setUsbTethering(boolean enable) {
3211        enforceTetherChangePermission();
3212        if (isTetheringSupported()) {
3213            return mTethering.setUsbTethering(enable);
3214        } else {
3215            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3216        }
3217    }
3218
3219    // TODO - move iface listing, queries, etc to new module
3220    // javadoc from interface
3221    public String[] getTetherableIfaces() {
3222        enforceTetherAccessPermission();
3223        return mTethering.getTetherableIfaces();
3224    }
3225
3226    public String[] getTetheredIfaces() {
3227        enforceTetherAccessPermission();
3228        return mTethering.getTetheredIfaces();
3229    }
3230
3231    public String[] getTetheringErroredIfaces() {
3232        enforceTetherAccessPermission();
3233        return mTethering.getErroredIfaces();
3234    }
3235
3236    // if ro.tether.denied = true we default to no tethering
3237    // gservices could set the secure setting to 1 though to enable it on a build where it
3238    // had previously been turned off.
3239    public boolean isTetheringSupported() {
3240        enforceTetherAccessPermission();
3241        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3242        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3243                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3244        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3245                mTethering.getTetherableWifiRegexs().length != 0 ||
3246                mTethering.getTetherableBluetoothRegexs().length != 0) &&
3247                mTethering.getUpstreamIfaceTypes().length != 0);
3248    }
3249
3250    // An API NetworkStateTrackers can call when they lose their network.
3251    // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3252    // whichever happens first.  The timer is started by the first caller and not
3253    // restarted by subsequent callers.
3254    public void requestNetworkTransitionWakelock(String forWhom) {
3255        enforceConnectivityInternalPermission();
3256        synchronized (this) {
3257            if (mNetTransitionWakeLock.isHeld()) return;
3258            mNetTransitionWakeLockSerialNumber++;
3259            mNetTransitionWakeLock.acquire();
3260            mNetTransitionWakeLockCausedBy = forWhom;
3261        }
3262        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3263                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3264                mNetTransitionWakeLockSerialNumber, 0),
3265                mNetTransitionWakeLockTimeout);
3266        return;
3267    }
3268
3269    // 100 percent is full good, 0 is full bad.
3270    public void reportInetCondition(int networkType, int percentage) {
3271        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3272        mContext.enforceCallingOrSelfPermission(
3273                android.Manifest.permission.STATUS_BAR,
3274                "ConnectivityService");
3275
3276        if (DBG) {
3277            int pid = getCallingPid();
3278            int uid = getCallingUid();
3279            String s = pid + "(" + uid + ") reports inet is " +
3280                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3281                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3282            mInetLog.add(s);
3283            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3284                mInetLog.remove(0);
3285            }
3286        }
3287        mHandler.sendMessage(mHandler.obtainMessage(
3288            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3289    }
3290
3291    private void handleInetConditionChange(int netType, int condition) {
3292        if (mActiveDefaultNetwork == -1) {
3293            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3294            return;
3295        }
3296        if (mActiveDefaultNetwork != netType) {
3297            if (DBG) log("handleInetConditionChange: net=" + netType +
3298                            " != default=" + mActiveDefaultNetwork + " - ignore");
3299            return;
3300        }
3301        if (VDBG) {
3302            log("handleInetConditionChange: net=" +
3303                    netType + ", condition=" + condition +
3304                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3305        }
3306        mDefaultInetCondition = condition;
3307        int delay;
3308        if (mInetConditionChangeInFlight == false) {
3309            if (VDBG) log("handleInetConditionChange: starting a change hold");
3310            // setup a new hold to debounce this
3311            if (mDefaultInetCondition > 50) {
3312                delay = Settings.Global.getInt(mContext.getContentResolver(),
3313                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3314            } else {
3315                delay = Settings.Global.getInt(mContext.getContentResolver(),
3316                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3317            }
3318            mInetConditionChangeInFlight = true;
3319            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3320                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3321        } else {
3322            // we've set the new condition, when this hold ends that will get picked up
3323            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3324        }
3325    }
3326
3327    private void handleInetConditionHoldEnd(int netType, int sequence) {
3328        if (DBG) {
3329            log("handleInetConditionHoldEnd: net=" + netType +
3330                    ", condition=" + mDefaultInetCondition +
3331                    ", published condition=" + mDefaultInetConditionPublished);
3332        }
3333        mInetConditionChangeInFlight = false;
3334
3335        if (mActiveDefaultNetwork == -1) {
3336            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3337            return;
3338        }
3339        if (mDefaultConnectionSequence != sequence) {
3340            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3341            return;
3342        }
3343        // TODO: Figure out why this optimization sometimes causes a
3344        //       change in mDefaultInetCondition to be missed and the
3345        //       UI to not be updated.
3346        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3347        //    if (DBG) log("no change in condition - aborting");
3348        //    return;
3349        //}
3350        NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3351        if (networkInfo.isConnected() == false) {
3352            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3353            return;
3354        }
3355        mDefaultInetConditionPublished = mDefaultInetCondition;
3356        sendInetConditionBroadcast(networkInfo);
3357        return;
3358    }
3359
3360    public ProxyProperties getProxy() {
3361        // this information is already available as a world read/writable jvm property
3362        // so this API change wouldn't have a benifit.  It also breaks the passing
3363        // of proxy info to all the JVMs.
3364        // enforceAccessPermission();
3365        synchronized (mProxyLock) {
3366            ProxyProperties ret = mGlobalProxy;
3367            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3368            return ret;
3369        }
3370    }
3371
3372    public void setGlobalProxy(ProxyProperties proxyProperties) {
3373        enforceConnectivityInternalPermission();
3374
3375        synchronized (mProxyLock) {
3376            if (proxyProperties == mGlobalProxy) return;
3377            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3378            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3379
3380            String host = "";
3381            int port = 0;
3382            String exclList = "";
3383            String pacFileUrl = "";
3384            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3385                    !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
3386                if (!proxyProperties.isValid()) {
3387                    if (DBG)
3388                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3389                    return;
3390                }
3391                mGlobalProxy = new ProxyProperties(proxyProperties);
3392                host = mGlobalProxy.getHost();
3393                port = mGlobalProxy.getPort();
3394                exclList = mGlobalProxy.getExclusionList();
3395                if (proxyProperties.getPacFileUrl() != null) {
3396                    pacFileUrl = proxyProperties.getPacFileUrl();
3397                }
3398            } else {
3399                mGlobalProxy = null;
3400            }
3401            ContentResolver res = mContext.getContentResolver();
3402            final long token = Binder.clearCallingIdentity();
3403            try {
3404                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3405                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3406                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3407                        exclList);
3408                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3409            } finally {
3410                Binder.restoreCallingIdentity(token);
3411            }
3412        }
3413
3414        if (mGlobalProxy == null) {
3415            proxyProperties = mDefaultProxy;
3416        }
3417        sendProxyBroadcast(proxyProperties);
3418    }
3419
3420    private void loadGlobalProxy() {
3421        ContentResolver res = mContext.getContentResolver();
3422        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3423        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3424        String exclList = Settings.Global.getString(res,
3425                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3426        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3427        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3428            ProxyProperties proxyProperties;
3429            if (!TextUtils.isEmpty(pacFileUrl)) {
3430                proxyProperties = new ProxyProperties(pacFileUrl);
3431            } else {
3432                proxyProperties = new ProxyProperties(host, port, exclList);
3433            }
3434            if (!proxyProperties.isValid()) {
3435                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3436                return;
3437            }
3438
3439            synchronized (mProxyLock) {
3440                mGlobalProxy = proxyProperties;
3441            }
3442        }
3443    }
3444
3445    public ProxyProperties getGlobalProxy() {
3446        // this information is already available as a world read/writable jvm property
3447        // so this API change wouldn't have a benifit.  It also breaks the passing
3448        // of proxy info to all the JVMs.
3449        // enforceAccessPermission();
3450        synchronized (mProxyLock) {
3451            return mGlobalProxy;
3452        }
3453    }
3454
3455    private void handleApplyDefaultProxy(ProxyProperties proxy) {
3456        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3457                && TextUtils.isEmpty(proxy.getPacFileUrl())) {
3458            proxy = null;
3459        }
3460        synchronized (mProxyLock) {
3461            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3462            if (mDefaultProxy == proxy) return; // catches repeated nulls
3463            if (proxy != null &&  !proxy.isValid()) {
3464                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3465                return;
3466            }
3467            mDefaultProxy = proxy;
3468
3469            if (mGlobalProxy != null) return;
3470            if (!mDefaultProxyDisabled) {
3471                sendProxyBroadcast(proxy);
3472            }
3473        }
3474    }
3475
3476    private void handleDeprecatedGlobalHttpProxy() {
3477        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3478                Settings.Global.HTTP_PROXY);
3479        if (!TextUtils.isEmpty(proxy)) {
3480            String data[] = proxy.split(":");
3481            if (data.length == 0) {
3482                return;
3483            }
3484
3485            String proxyHost =  data[0];
3486            int proxyPort = 8080;
3487            if (data.length > 1) {
3488                try {
3489                    proxyPort = Integer.parseInt(data[1]);
3490                } catch (NumberFormatException e) {
3491                    return;
3492                }
3493            }
3494            ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3495            setGlobalProxy(p);
3496        }
3497    }
3498
3499    private void sendProxyBroadcast(ProxyProperties proxy) {
3500        if (proxy == null) proxy = new ProxyProperties("", 0, "");
3501        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3502        if (DBG) log("sending Proxy Broadcast for " + proxy);
3503        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3504        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3505            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3506        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3507        final long ident = Binder.clearCallingIdentity();
3508        try {
3509            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3510        } finally {
3511            Binder.restoreCallingIdentity(ident);
3512        }
3513    }
3514
3515    private static class SettingsObserver extends ContentObserver {
3516        private int mWhat;
3517        private Handler mHandler;
3518        SettingsObserver(Handler handler, int what) {
3519            super(handler);
3520            mHandler = handler;
3521            mWhat = what;
3522        }
3523
3524        void observe(Context context) {
3525            ContentResolver resolver = context.getContentResolver();
3526            resolver.registerContentObserver(Settings.Global.getUriFor(
3527                    Settings.Global.HTTP_PROXY), false, this);
3528        }
3529
3530        @Override
3531        public void onChange(boolean selfChange) {
3532            mHandler.obtainMessage(mWhat).sendToTarget();
3533        }
3534    }
3535
3536    private static void log(String s) {
3537        Slog.d(TAG, s);
3538    }
3539
3540    private static void loge(String s) {
3541        Slog.e(TAG, s);
3542    }
3543
3544    int convertFeatureToNetworkType(int networkType, String feature) {
3545        int usedNetworkType = networkType;
3546
3547        if(networkType == ConnectivityManager.TYPE_MOBILE) {
3548            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3549                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3550            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3551                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3552            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3553                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3554                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3555            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3556                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3557            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3558                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3559            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3560                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3561            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3562                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3563            } else {
3564                Slog.e(TAG, "Can't match any mobile netTracker!");
3565            }
3566        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3567            if (TextUtils.equals(feature, "p2p")) {
3568                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3569            } else {
3570                Slog.e(TAG, "Can't match any wifi netTracker!");
3571            }
3572        } else {
3573            Slog.e(TAG, "Unexpected network type");
3574        }
3575        return usedNetworkType;
3576    }
3577
3578    private static <T> T checkNotNull(T value, String message) {
3579        if (value == null) {
3580            throw new NullPointerException(message);
3581        }
3582        return value;
3583    }
3584
3585    /**
3586     * Protect a socket from VPN routing rules. This method is used by
3587     * VpnBuilder and not available in ConnectivityManager. Permissions
3588     * are checked in Vpn class.
3589     * @hide
3590     */
3591    @Override
3592    public boolean protectVpn(ParcelFileDescriptor socket) {
3593        throwIfLockdownEnabled();
3594        try {
3595            int type = mActiveDefaultNetwork;
3596            int user = UserHandle.getUserId(Binder.getCallingUid());
3597            if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3598                synchronized(mVpns) {
3599                    mVpns.get(user).protect(socket,
3600                            mNetTrackers[type].getLinkProperties().getInterfaceName());
3601                }
3602                return true;
3603            }
3604        } catch (Exception e) {
3605            // ignore
3606        } finally {
3607            try {
3608                socket.close();
3609            } catch (Exception e) {
3610                // ignore
3611            }
3612        }
3613        return false;
3614    }
3615
3616    /**
3617     * Prepare for a VPN application. This method is used by VpnDialogs
3618     * and not available in ConnectivityManager. Permissions are checked
3619     * in Vpn class.
3620     * @hide
3621     */
3622    @Override
3623    public boolean prepareVpn(String oldPackage, String newPackage) {
3624        throwIfLockdownEnabled();
3625        int user = UserHandle.getUserId(Binder.getCallingUid());
3626        synchronized(mVpns) {
3627            return mVpns.get(user).prepare(oldPackage, newPackage);
3628        }
3629    }
3630
3631    @Override
3632    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3633        enforceMarkNetworkSocketPermission();
3634        final long token = Binder.clearCallingIdentity();
3635        try {
3636            int mark = mNetd.getMarkForUid(uid);
3637            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3638            if (mark == -1) {
3639                mark = 0;
3640            }
3641            NetworkUtils.markSocket(socket.getFd(), mark);
3642        } catch (RemoteException e) {
3643        } finally {
3644            Binder.restoreCallingIdentity(token);
3645        }
3646    }
3647
3648    /**
3649     * Configure a TUN interface and return its file descriptor. Parameters
3650     * are encoded and opaque to this class. This method is used by VpnBuilder
3651     * and not available in ConnectivityManager. Permissions are checked in
3652     * Vpn class.
3653     * @hide
3654     */
3655    @Override
3656    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3657        throwIfLockdownEnabled();
3658        int user = UserHandle.getUserId(Binder.getCallingUid());
3659        synchronized(mVpns) {
3660            return mVpns.get(user).establish(config);
3661        }
3662    }
3663
3664    /**
3665     * Start legacy VPN, controlling native daemons as needed. Creates a
3666     * secondary thread to perform connection work, returning quickly.
3667     */
3668    @Override
3669    public void startLegacyVpn(VpnProfile profile) {
3670        throwIfLockdownEnabled();
3671        final LinkProperties egress = getActiveLinkProperties();
3672        if (egress == null) {
3673            throw new IllegalStateException("Missing active network connection");
3674        }
3675        int user = UserHandle.getUserId(Binder.getCallingUid());
3676        synchronized(mVpns) {
3677            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3678        }
3679    }
3680
3681    /**
3682     * Return the information of the ongoing legacy VPN. This method is used
3683     * by VpnSettings and not available in ConnectivityManager. Permissions
3684     * are checked in Vpn class.
3685     * @hide
3686     */
3687    @Override
3688    public LegacyVpnInfo getLegacyVpnInfo() {
3689        throwIfLockdownEnabled();
3690        int user = UserHandle.getUserId(Binder.getCallingUid());
3691        synchronized(mVpns) {
3692            return mVpns.get(user).getLegacyVpnInfo();
3693        }
3694    }
3695
3696    /**
3697     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3698     * not available in ConnectivityManager.
3699     * Permissions are checked in Vpn class.
3700     * @hide
3701     */
3702    @Override
3703    public VpnConfig getVpnConfig() {
3704        int user = UserHandle.getUserId(Binder.getCallingUid());
3705        synchronized(mVpns) {
3706            return mVpns.get(user).getVpnConfig();
3707        }
3708    }
3709
3710    /**
3711     * Callback for VPN subsystem. Currently VPN is not adapted to the service
3712     * through NetworkStateTracker since it works differently. For example, it
3713     * needs to override DNS servers but never takes the default routes. It
3714     * relies on another data network, and it could keep existing connections
3715     * alive after reconnecting, switching between networks, or even resuming
3716     * from deep sleep. Calls from applications should be done synchronously
3717     * to avoid race conditions. As these are all hidden APIs, refactoring can
3718     * be done whenever a better abstraction is developed.
3719     */
3720    public class VpnCallback {
3721        private VpnCallback() {
3722        }
3723
3724        public void onStateChanged(NetworkInfo info) {
3725            mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3726        }
3727
3728        public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
3729            if (dnsServers == null) {
3730                restore();
3731                return;
3732            }
3733
3734            // Convert DNS servers into addresses.
3735            List<InetAddress> addresses = new ArrayList<InetAddress>();
3736            for (String address : dnsServers) {
3737                // Double check the addresses and remove invalid ones.
3738                try {
3739                    addresses.add(InetAddress.parseNumericAddress(address));
3740                } catch (Exception e) {
3741                    // ignore
3742                }
3743            }
3744            if (addresses.isEmpty()) {
3745                restore();
3746                return;
3747            }
3748
3749            // Concatenate search domains into a string.
3750            StringBuilder buffer = new StringBuilder();
3751            if (searchDomains != null) {
3752                for (String domain : searchDomains) {
3753                    buffer.append(domain).append(' ');
3754                }
3755            }
3756            String domains = buffer.toString().trim();
3757
3758            // Apply DNS changes.
3759            synchronized (mDnsLock) {
3760                updateDnsLocked("VPN", iface, addresses, domains, false);
3761            }
3762
3763            // Temporarily disable the default proxy (not global).
3764            synchronized (mProxyLock) {
3765                mDefaultProxyDisabled = true;
3766                if (mGlobalProxy == null && mDefaultProxy != null) {
3767                    sendProxyBroadcast(null);
3768                }
3769            }
3770
3771            // TODO: support proxy per network.
3772        }
3773
3774        public void restore() {
3775            synchronized (mProxyLock) {
3776                mDefaultProxyDisabled = false;
3777                if (mGlobalProxy == null && mDefaultProxy != null) {
3778                    sendProxyBroadcast(mDefaultProxy);
3779                }
3780            }
3781        }
3782
3783        public void protect(ParcelFileDescriptor socket) {
3784            try {
3785                final int mark = mNetd.getMarkForProtect();
3786                NetworkUtils.markSocket(socket.getFd(), mark);
3787            } catch (RemoteException e) {
3788            }
3789        }
3790
3791        public void setRoutes(String interfaze, List<RouteInfo> routes) {
3792            for (RouteInfo route : routes) {
3793                try {
3794                    mNetd.setMarkedForwardingRoute(interfaze, route);
3795                } catch (RemoteException e) {
3796                }
3797            }
3798        }
3799
3800        public void setMarkedForwarding(String interfaze) {
3801            try {
3802                mNetd.setMarkedForwarding(interfaze);
3803            } catch (RemoteException e) {
3804            }
3805        }
3806
3807        public void clearMarkedForwarding(String interfaze) {
3808            try {
3809                mNetd.clearMarkedForwarding(interfaze);
3810            } catch (RemoteException e) {
3811            }
3812        }
3813
3814        public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
3815            int uidStart = uid * UserHandle.PER_USER_RANGE;
3816            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3817            addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
3818        }
3819
3820        public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
3821            int uidStart = uid * UserHandle.PER_USER_RANGE;
3822            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3823            clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
3824        }
3825
3826        public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3827                boolean forwardDns) {
3828            try {
3829                mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3830                if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3831            } catch (RemoteException e) {
3832            }
3833
3834        }
3835
3836        public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3837                boolean forwardDns) {
3838            try {
3839                mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3840                if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3841            } catch (RemoteException e) {
3842            }
3843
3844        }
3845    }
3846
3847    @Override
3848    public boolean updateLockdownVpn() {
3849        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3850            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3851            return false;
3852        }
3853
3854        // Tear down existing lockdown if profile was removed
3855        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3856        if (mLockdownEnabled) {
3857            if (!mKeyStore.isUnlocked()) {
3858                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3859                return false;
3860            }
3861
3862            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3863            final VpnProfile profile = VpnProfile.decode(
3864                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3865            int user = UserHandle.getUserId(Binder.getCallingUid());
3866            synchronized(mVpns) {
3867                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3868                            profile));
3869            }
3870        } else {
3871            setLockdownTracker(null);
3872        }
3873
3874        return true;
3875    }
3876
3877    /**
3878     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3879     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3880     */
3881    private void setLockdownTracker(LockdownVpnTracker tracker) {
3882        // Shutdown any existing tracker
3883        final LockdownVpnTracker existing = mLockdownTracker;
3884        mLockdownTracker = null;
3885        if (existing != null) {
3886            existing.shutdown();
3887        }
3888
3889        try {
3890            if (tracker != null) {
3891                mNetd.setFirewallEnabled(true);
3892                mNetd.setFirewallInterfaceRule("lo", true);
3893                mLockdownTracker = tracker;
3894                mLockdownTracker.init();
3895            } else {
3896                mNetd.setFirewallEnabled(false);
3897            }
3898        } catch (RemoteException e) {
3899            // ignored; NMS lives inside system_server
3900        }
3901    }
3902
3903    private void throwIfLockdownEnabled() {
3904        if (mLockdownEnabled) {
3905            throw new IllegalStateException("Unavailable in lockdown mode");
3906        }
3907    }
3908
3909    public void supplyMessenger(int networkType, Messenger messenger) {
3910        enforceConnectivityInternalPermission();
3911
3912        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3913            mNetTrackers[networkType].supplyMessenger(messenger);
3914        }
3915    }
3916
3917    public int findConnectionTypeForIface(String iface) {
3918        enforceConnectivityInternalPermission();
3919
3920        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3921        for (NetworkStateTracker tracker : mNetTrackers) {
3922            if (tracker != null) {
3923                LinkProperties lp = tracker.getLinkProperties();
3924                if (lp != null && iface.equals(lp.getInterfaceName())) {
3925                    return tracker.getNetworkInfo().getType();
3926                }
3927            }
3928        }
3929        return ConnectivityManager.TYPE_NONE;
3930    }
3931
3932    /**
3933     * Have mobile data fail fast if enabled.
3934     *
3935     * @param enabled DctConstants.ENABLED/DISABLED
3936     */
3937    private void setEnableFailFastMobileData(int enabled) {
3938        int tag;
3939
3940        if (enabled == DctConstants.ENABLED) {
3941            tag = mEnableFailFastMobileDataTag.incrementAndGet();
3942        } else {
3943            tag = mEnableFailFastMobileDataTag.get();
3944        }
3945        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3946                         enabled));
3947    }
3948
3949    private boolean isMobileDataStateTrackerReady() {
3950        MobileDataStateTracker mdst =
3951                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3952        return (mdst != null) && (mdst.isReady());
3953    }
3954
3955    /**
3956     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3957     */
3958
3959    /**
3960     * No connection was possible to the network.
3961     * This is NOT a warm sim.
3962     */
3963    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
3964
3965    /**
3966     * A connection was made to the internet, all is well.
3967     * This is NOT a warm sim.
3968     */
3969    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
3970
3971    /**
3972     * A connection was made but no dns server was available to resolve a name to address.
3973     * This is NOT a warm sim since provisioning network is supported.
3974     */
3975    private static final int CMP_RESULT_CODE_NO_DNS = 2;
3976
3977    /**
3978     * A connection was made but could not open a TCP connection.
3979     * This is NOT a warm sim since provisioning network is supported.
3980     */
3981    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3982
3983    /**
3984     * A connection was made but there was a redirection, we appear to be in walled garden.
3985     * This is an indication of a warm sim on a mobile network such as T-Mobile.
3986     */
3987    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
3988
3989    /**
3990     * The mobile network is a provisioning network.
3991     * This is an indication of a warm sim on a mobile network such as AT&T.
3992     */
3993    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
3994
3995    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
3996
3997    @Override
3998    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3999        int timeOutMs = -1;
4000        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4001        enforceConnectivityInternalPermission();
4002
4003        final long token = Binder.clearCallingIdentity();
4004        try {
4005            timeOutMs = suggestedTimeOutMs;
4006            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4007                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4008            }
4009
4010            // Check that mobile networks are supported
4011            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4012                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4013                if (DBG) log("checkMobileProvisioning: X no mobile network");
4014                return timeOutMs;
4015            }
4016
4017            // If we're already checking don't do it again
4018            // TODO: Add a queue of results...
4019            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4020                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4021                return timeOutMs;
4022            }
4023
4024            // Start off with mobile notification off
4025            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4026
4027            CheckMp checkMp = new CheckMp(mContext, this);
4028            CheckMp.CallBack cb = new CheckMp.CallBack() {
4029                @Override
4030                void onComplete(Integer result) {
4031                    if (DBG) log("CheckMp.onComplete: result=" + result);
4032                    NetworkInfo ni =
4033                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4034                    switch(result) {
4035                        case CMP_RESULT_CODE_CONNECTABLE:
4036                        case CMP_RESULT_CODE_NO_CONNECTION:
4037                        case CMP_RESULT_CODE_NO_DNS:
4038                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4039                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4040                            break;
4041                        }
4042                        case CMP_RESULT_CODE_REDIRECTED: {
4043                            if (DBG) log("CheckMp.onComplete: warm sim");
4044                            String url = getMobileProvisioningUrl();
4045                            if (TextUtils.isEmpty(url)) {
4046                                url = getMobileRedirectedProvisioningUrl();
4047                            }
4048                            if (TextUtils.isEmpty(url) == false) {
4049                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4050                                setProvNotificationVisible(true,
4051                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4052                                        url);
4053                            } else {
4054                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4055                            }
4056                            break;
4057                        }
4058                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4059                            String url = getMobileProvisioningUrl();
4060                            if (TextUtils.isEmpty(url) == false) {
4061                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4062                                setProvNotificationVisible(true,
4063                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4064                                        url);
4065                            } else {
4066                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4067                            }
4068                            break;
4069                        }
4070                        default: {
4071                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4072                            break;
4073                        }
4074                    }
4075                    mIsCheckingMobileProvisioning.set(false);
4076                }
4077            };
4078            CheckMp.Params params =
4079                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4080            if (DBG) log("checkMobileProvisioning: params=" + params);
4081            checkMp.execute(params);
4082        } finally {
4083            Binder.restoreCallingIdentity(token);
4084            if (DBG) log("checkMobileProvisioning: X");
4085        }
4086        return timeOutMs;
4087    }
4088
4089    static class CheckMp extends
4090            AsyncTask<CheckMp.Params, Void, Integer> {
4091        private static final String CHECKMP_TAG = "CheckMp";
4092
4093        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4094        private static boolean mTestingFailures;
4095
4096        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4097        private static final int MAX_LOOPS = 4;
4098
4099        // Number of milli-seconds to complete all of the retires
4100        public static final int MAX_TIMEOUT_MS =  60000;
4101
4102        // The socket should retry only 5 seconds, the default is longer
4103        private static final int SOCKET_TIMEOUT_MS = 5000;
4104
4105        // Sleep time for network errors
4106        private static final int NET_ERROR_SLEEP_SEC = 3;
4107
4108        // Sleep time for network route establishment
4109        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4110
4111        // Short sleep time for polling :(
4112        private static final int POLLING_SLEEP_SEC = 1;
4113
4114        private Context mContext;
4115        private ConnectivityService mCs;
4116        private TelephonyManager mTm;
4117        private Params mParams;
4118
4119        /**
4120         * Parameters for AsyncTask.execute
4121         */
4122        static class Params {
4123            private String mUrl;
4124            private long mTimeOutMs;
4125            private CallBack mCb;
4126
4127            Params(String url, long timeOutMs, CallBack cb) {
4128                mUrl = url;
4129                mTimeOutMs = timeOutMs;
4130                mCb = cb;
4131            }
4132
4133            @Override
4134            public String toString() {
4135                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4136            }
4137        }
4138
4139        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4140        // issued by name or ip address, for Google its by name so when we construct
4141        // this HostnameVerifier we'll pass the original Uri and use it to verify
4142        // the host. If the host name in the original uril fails we'll test the
4143        // hostname parameter just incase things change.
4144        static class CheckMpHostnameVerifier implements HostnameVerifier {
4145            Uri mOrgUri;
4146
4147            CheckMpHostnameVerifier(Uri orgUri) {
4148                mOrgUri = orgUri;
4149            }
4150
4151            @Override
4152            public boolean verify(String hostname, SSLSession session) {
4153                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4154                String orgUriHost = mOrgUri.getHost();
4155                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4156                if (DBG) {
4157                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4158                        + " orgUriHost=" + orgUriHost);
4159                }
4160                return retVal;
4161            }
4162        }
4163
4164        /**
4165         * The call back object passed in Params. onComplete will be called
4166         * on the main thread.
4167         */
4168        abstract static class CallBack {
4169            // Called on the main thread.
4170            abstract void onComplete(Integer result);
4171        }
4172
4173        public CheckMp(Context context, ConnectivityService cs) {
4174            if (Build.IS_DEBUGGABLE) {
4175                mTestingFailures =
4176                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4177            } else {
4178                mTestingFailures = false;
4179            }
4180
4181            mContext = context;
4182            mCs = cs;
4183
4184            // Setup access to TelephonyService we'll be using.
4185            mTm = (TelephonyManager) mContext.getSystemService(
4186                    Context.TELEPHONY_SERVICE);
4187        }
4188
4189        /**
4190         * Get the default url to use for the test.
4191         */
4192        public String getDefaultUrl() {
4193            // See http://go/clientsdns for usage approval
4194            String server = Settings.Global.getString(mContext.getContentResolver(),
4195                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4196            if (server == null) {
4197                server = "clients3.google.com";
4198            }
4199            return "http://" + server + "/generate_204";
4200        }
4201
4202        /**
4203         * Detect if its possible to connect to the http url. DNS based detection techniques
4204         * do not work at all hotspots. The best way to check is to perform a request to
4205         * a known address that fetches the data we expect.
4206         */
4207        private synchronized Integer isMobileOk(Params params) {
4208            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4209            Uri orgUri = Uri.parse(params.mUrl);
4210            Random rand = new Random();
4211            mParams = params;
4212
4213            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4214                result = CMP_RESULT_CODE_NO_CONNECTION;
4215                log("isMobileOk: X not mobile capable result=" + result);
4216                return result;
4217            }
4218
4219            // See if we've already determined we've got a provisioning connection,
4220            // if so we don't need to do anything active.
4221            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4222                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4223            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4224            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4225
4226            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4227                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4228            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4229            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4230
4231            if (isDefaultProvisioning || isHipriProvisioning) {
4232                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4233                log("isMobileOk: X default || hipri is provisioning result=" + result);
4234                return result;
4235            }
4236
4237            try {
4238                // Continue trying to connect until time has run out
4239                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4240
4241                if (!mCs.isMobileDataStateTrackerReady()) {
4242                    // Wait for MobileDataStateTracker to be ready.
4243                    if (DBG) log("isMobileOk: mdst is not ready");
4244                    while(SystemClock.elapsedRealtime() < endTime) {
4245                        if (mCs.isMobileDataStateTrackerReady()) {
4246                            // Enable fail fast as we'll do retries here and use a
4247                            // hipri connection so the default connection stays active.
4248                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4249                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4250                            break;
4251                        }
4252                        sleep(POLLING_SLEEP_SEC);
4253                    }
4254                }
4255
4256                log("isMobileOk: start hipri url=" + params.mUrl);
4257
4258                // First wait until we can start using hipri
4259                Binder binder = new Binder();
4260                while(SystemClock.elapsedRealtime() < endTime) {
4261                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4262                            Phone.FEATURE_ENABLE_HIPRI, binder);
4263                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4264                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4265                            log("isMobileOk: hipri started");
4266                            break;
4267                    }
4268                    if (VDBG) log("isMobileOk: hipri not started yet");
4269                    result = CMP_RESULT_CODE_NO_CONNECTION;
4270                    sleep(POLLING_SLEEP_SEC);
4271                }
4272
4273                // Continue trying to connect until time has run out
4274                while(SystemClock.elapsedRealtime() < endTime) {
4275                    try {
4276                        // Wait for hipri to connect.
4277                        // TODO: Don't poll and handle situation where hipri fails
4278                        // because default is retrying. See b/9569540
4279                        NetworkInfo.State state = mCs
4280                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4281                        if (state != NetworkInfo.State.CONNECTED) {
4282                            if (true/*VDBG*/) {
4283                                log("isMobileOk: not connected ni=" +
4284                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4285                            }
4286                            sleep(POLLING_SLEEP_SEC);
4287                            result = CMP_RESULT_CODE_NO_CONNECTION;
4288                            continue;
4289                        }
4290
4291                        // Hipri has started check if this is a provisioning url
4292                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4293                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4294                        if (mdst.isProvisioningNetwork()) {
4295                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4296                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4297                            return result;
4298                        } else {
4299                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4300                        }
4301
4302                        // Get of the addresses associated with the url host. We need to use the
4303                        // address otherwise HttpURLConnection object will use the name to get
4304                        // the addresses and will try every address but that will bypass the
4305                        // route to host we setup and the connection could succeed as the default
4306                        // interface might be connected to the internet via wifi or other interface.
4307                        InetAddress[] addresses;
4308                        try {
4309                            addresses = InetAddress.getAllByName(orgUri.getHost());
4310                        } catch (UnknownHostException e) {
4311                            result = CMP_RESULT_CODE_NO_DNS;
4312                            log("isMobileOk: X UnknownHostException result=" + result);
4313                            return result;
4314                        }
4315                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4316
4317                        // Get the type of addresses supported by this link
4318                        LinkProperties lp = mCs.getLinkProperties(
4319                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4320                        boolean linkHasIpv4 = lp.hasIPv4Address();
4321                        boolean linkHasIpv6 = lp.hasIPv6Address();
4322                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4323                                + " linkHasIpv6=" + linkHasIpv6);
4324
4325                        final ArrayList<InetAddress> validAddresses =
4326                                new ArrayList<InetAddress>(addresses.length);
4327
4328                        for (InetAddress addr : addresses) {
4329                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4330                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4331                                validAddresses.add(addr);
4332                            }
4333                        }
4334
4335                        if (validAddresses.size() == 0) {
4336                            return CMP_RESULT_CODE_NO_CONNECTION;
4337                        }
4338
4339                        int addrTried = 0;
4340                        while (true) {
4341                            // Loop through at most MAX_LOOPS valid addresses or until
4342                            // we run out of time
4343                            if (addrTried++ >= MAX_LOOPS) {
4344                                log("isMobileOk: too many loops tried - giving up");
4345                                break;
4346                            }
4347                            if (SystemClock.elapsedRealtime() >= endTime) {
4348                                log("isMobileOk: spend too much time - giving up");
4349                                break;
4350                            }
4351
4352                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4353                                    validAddresses.size()));
4354
4355                            // Make a route to host so we check the specific interface.
4356                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4357                                    hostAddr.getAddress())) {
4358                                // Wait a short time to be sure the route is established ??
4359                                log("isMobileOk:"
4360                                        + " wait to establish route to hostAddr=" + hostAddr);
4361                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4362                            } else {
4363                                log("isMobileOk:"
4364                                        + " could not establish route to hostAddr=" + hostAddr);
4365                                // Wait a short time before the next attempt
4366                                sleep(NET_ERROR_SLEEP_SEC);
4367                                continue;
4368                            }
4369
4370                            // Rewrite the url to have numeric address to use the specific route
4371                            // using http for half the attempts and https for the other half.
4372                            // Doing https first and http second as on a redirected walled garden
4373                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4374                            // handshake timed out" which we declare as
4375                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4376                            // having http second we will be using logic used for some time.
4377                            URL newUrl;
4378                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4379                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4380                                        orgUri.getPath());
4381                            log("isMobileOk: newUrl=" + newUrl);
4382
4383                            HttpURLConnection urlConn = null;
4384                            try {
4385                                // Open the connection set the request headers and get the response
4386                                urlConn = (HttpURLConnection)newUrl.openConnection(
4387                                        java.net.Proxy.NO_PROXY);
4388                                if (scheme.equals("https")) {
4389                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4390                                            new CheckMpHostnameVerifier(orgUri));
4391                                }
4392                                urlConn.setInstanceFollowRedirects(false);
4393                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4394                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4395                                urlConn.setUseCaches(false);
4396                                urlConn.setAllowUserInteraction(false);
4397                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4398                                // is used which is useless in this case.
4399                                urlConn.setRequestProperty("Connection", "close");
4400                                int responseCode = urlConn.getResponseCode();
4401
4402                                // For debug display the headers
4403                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4404                                log("isMobileOk: headers=" + headers);
4405
4406                                // Close the connection
4407                                urlConn.disconnect();
4408                                urlConn = null;
4409
4410                                if (mTestingFailures) {
4411                                    // Pretend no connection, this tests using http and https
4412                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4413                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4414                                    continue;
4415                                }
4416
4417                                if (responseCode == 204) {
4418                                    // Return
4419                                    result = CMP_RESULT_CODE_CONNECTABLE;
4420                                    log("isMobileOk: X got expected responseCode=" + responseCode
4421                                            + " result=" + result);
4422                                    return result;
4423                                } else {
4424                                    // Retry to be sure this was redirected, we've gotten
4425                                    // occasions where a server returned 200 even though
4426                                    // the device didn't have a "warm" sim.
4427                                    log("isMobileOk: not expected responseCode=" + responseCode);
4428                                    // TODO - it would be nice in the single-address case to do
4429                                    // another DNS resolve here, but flushing the cache is a bit
4430                                    // heavy-handed.
4431                                    result = CMP_RESULT_CODE_REDIRECTED;
4432                                }
4433                            } catch (Exception e) {
4434                                log("isMobileOk: HttpURLConnection Exception" + e);
4435                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4436                                if (urlConn != null) {
4437                                    urlConn.disconnect();
4438                                    urlConn = null;
4439                                }
4440                                sleep(NET_ERROR_SLEEP_SEC);
4441                                continue;
4442                            }
4443                        }
4444                        log("isMobileOk: X loops|timed out result=" + result);
4445                        return result;
4446                    } catch (Exception e) {
4447                        log("isMobileOk: Exception e=" + e);
4448                        continue;
4449                    }
4450                }
4451                log("isMobileOk: timed out");
4452            } finally {
4453                log("isMobileOk: F stop hipri");
4454                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4455                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4456                        Phone.FEATURE_ENABLE_HIPRI);
4457
4458                // Wait for hipri to disconnect.
4459                long endTime = SystemClock.elapsedRealtime() + 5000;
4460
4461                while(SystemClock.elapsedRealtime() < endTime) {
4462                    NetworkInfo.State state = mCs
4463                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4464                    if (state != NetworkInfo.State.DISCONNECTED) {
4465                        if (VDBG) {
4466                            log("isMobileOk: connected ni=" +
4467                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4468                        }
4469                        sleep(POLLING_SLEEP_SEC);
4470                        continue;
4471                    }
4472                }
4473
4474                log("isMobileOk: X result=" + result);
4475            }
4476            return result;
4477        }
4478
4479        @Override
4480        protected Integer doInBackground(Params... params) {
4481            return isMobileOk(params[0]);
4482        }
4483
4484        @Override
4485        protected void onPostExecute(Integer result) {
4486            log("onPostExecute: result=" + result);
4487            if ((mParams != null) && (mParams.mCb != null)) {
4488                mParams.mCb.onComplete(result);
4489            }
4490        }
4491
4492        private String inetAddressesToString(InetAddress[] addresses) {
4493            StringBuffer sb = new StringBuffer();
4494            boolean firstTime = true;
4495            for(InetAddress addr : addresses) {
4496                if (firstTime) {
4497                    firstTime = false;
4498                } else {
4499                    sb.append(",");
4500                }
4501                sb.append(addr);
4502            }
4503            return sb.toString();
4504        }
4505
4506        private void printNetworkInfo() {
4507            boolean hasIccCard = mTm.hasIccCard();
4508            int simState = mTm.getSimState();
4509            log("hasIccCard=" + hasIccCard
4510                    + " simState=" + simState);
4511            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4512            if (ni != null) {
4513                log("ni.length=" + ni.length);
4514                for (NetworkInfo netInfo: ni) {
4515                    log("netInfo=" + netInfo.toString());
4516                }
4517            } else {
4518                log("no network info ni=null");
4519            }
4520        }
4521
4522        /**
4523         * Sleep for a few seconds then return.
4524         * @param seconds
4525         */
4526        private static void sleep(int seconds) {
4527            try {
4528                Thread.sleep(seconds * 1000);
4529            } catch (InterruptedException e) {
4530                e.printStackTrace();
4531            }
4532        }
4533
4534        private static void log(String s) {
4535            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4536        }
4537    }
4538
4539    // TODO: Move to ConnectivityManager and make public?
4540    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4541            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4542
4543    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4544        @Override
4545        public void onReceive(Context context, Intent intent) {
4546            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4547                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4548            }
4549        }
4550    };
4551
4552    private void handleMobileProvisioningAction(String url) {
4553        // Notication mark notification as not visible
4554        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4555
4556        // If provisioning network handle as a special case,
4557        // otherwise launch browser with the intent directly.
4558        NetworkInfo ni = getProvisioningNetworkInfo();
4559        if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
4560            if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4561            MobileDataStateTracker mdst = (MobileDataStateTracker)
4562                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4563            mdst.enableMobileProvisioning(url);
4564        } else {
4565            if (DBG) log("handleMobileProvisioningAction: on default network");
4566            Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4567                    Intent.CATEGORY_APP_BROWSER);
4568            newIntent.setData(Uri.parse(url));
4569            newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4570                    Intent.FLAG_ACTIVITY_NEW_TASK);
4571            try {
4572                mContext.startActivity(newIntent);
4573            } catch (ActivityNotFoundException e) {
4574                loge("handleMobileProvisioningAction: startActivity failed" + e);
4575            }
4576        }
4577    }
4578
4579    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4580    private volatile boolean mIsNotificationVisible = false;
4581
4582    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4583            String url) {
4584        if (DBG) {
4585            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4586                + " extraInfo=" + extraInfo + " url=" + url);
4587        }
4588
4589        Resources r = Resources.getSystem();
4590        NotificationManager notificationManager = (NotificationManager) mContext
4591            .getSystemService(Context.NOTIFICATION_SERVICE);
4592
4593        if (visible) {
4594            CharSequence title;
4595            CharSequence details;
4596            int icon;
4597            Intent intent;
4598            Notification notification = new Notification();
4599            switch (networkType) {
4600                case ConnectivityManager.TYPE_WIFI:
4601                    title = r.getString(R.string.wifi_available_sign_in, 0);
4602                    details = r.getString(R.string.network_available_sign_in_detailed,
4603                            extraInfo);
4604                    icon = R.drawable.stat_notify_wifi_in_range;
4605                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4606                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4607                            Intent.FLAG_ACTIVITY_NEW_TASK);
4608                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4609                    break;
4610                case ConnectivityManager.TYPE_MOBILE:
4611                case ConnectivityManager.TYPE_MOBILE_HIPRI:
4612                    title = r.getString(R.string.network_available_sign_in, 0);
4613                    // TODO: Change this to pull from NetworkInfo once a printable
4614                    // name has been added to it
4615                    details = mTelephonyManager.getNetworkOperatorName();
4616                    icon = R.drawable.stat_notify_rssi_in_range;
4617                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4618                    intent.putExtra("EXTRA_URL", url);
4619                    intent.setFlags(0);
4620                    notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
4621                    break;
4622                default:
4623                    title = r.getString(R.string.network_available_sign_in, 0);
4624                    details = r.getString(R.string.network_available_sign_in_detailed,
4625                            extraInfo);
4626                    icon = R.drawable.stat_notify_rssi_in_range;
4627                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4628                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4629                            Intent.FLAG_ACTIVITY_NEW_TASK);
4630                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4631                    break;
4632            }
4633
4634            notification.when = 0;
4635            notification.icon = icon;
4636            notification.flags = Notification.FLAG_AUTO_CANCEL;
4637            notification.tickerText = title;
4638            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4639
4640            try {
4641                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
4642            } catch (NullPointerException npe) {
4643                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4644                npe.printStackTrace();
4645            }
4646        } else {
4647            try {
4648                notificationManager.cancel(NOTIFICATION_ID, networkType);
4649            } catch (NullPointerException npe) {
4650                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4651                npe.printStackTrace();
4652            }
4653        }
4654        mIsNotificationVisible = visible;
4655    }
4656
4657    /** Location to an updatable file listing carrier provisioning urls.
4658     *  An example:
4659     *
4660     * <?xml version="1.0" encoding="utf-8"?>
4661     *  <provisioningUrls>
4662     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
4663     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4664     *  </provisioningUrls>
4665     */
4666    private static final String PROVISIONING_URL_PATH =
4667            "/data/misc/radio/provisioning_urls.xml";
4668    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4669
4670    /** XML tag for root element. */
4671    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4672    /** XML tag for individual url */
4673    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4674    /** XML tag for redirected url */
4675    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4676    /** XML attribute for mcc */
4677    private static final String ATTR_MCC = "mcc";
4678    /** XML attribute for mnc */
4679    private static final String ATTR_MNC = "mnc";
4680
4681    private static final int REDIRECTED_PROVISIONING = 1;
4682    private static final int PROVISIONING = 2;
4683
4684    private String getProvisioningUrlBaseFromFile(int type) {
4685        FileReader fileReader = null;
4686        XmlPullParser parser = null;
4687        Configuration config = mContext.getResources().getConfiguration();
4688        String tagType;
4689
4690        switch (type) {
4691            case PROVISIONING:
4692                tagType = TAG_PROVISIONING_URL;
4693                break;
4694            case REDIRECTED_PROVISIONING:
4695                tagType = TAG_REDIRECTED_URL;
4696                break;
4697            default:
4698                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4699                        type);
4700        }
4701
4702        try {
4703            fileReader = new FileReader(mProvisioningUrlFile);
4704            parser = Xml.newPullParser();
4705            parser.setInput(fileReader);
4706            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4707
4708            while (true) {
4709                XmlUtils.nextElement(parser);
4710
4711                String element = parser.getName();
4712                if (element == null) break;
4713
4714                if (element.equals(tagType)) {
4715                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
4716                    try {
4717                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4718                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
4719                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4720                                parser.next();
4721                                if (parser.getEventType() == XmlPullParser.TEXT) {
4722                                    return parser.getText();
4723                                }
4724                            }
4725                        }
4726                    } catch (NumberFormatException e) {
4727                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4728                    }
4729                }
4730            }
4731            return null;
4732        } catch (FileNotFoundException e) {
4733            loge("Carrier Provisioning Urls file not found");
4734        } catch (XmlPullParserException e) {
4735            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4736        } catch (IOException e) {
4737            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4738        } finally {
4739            if (fileReader != null) {
4740                try {
4741                    fileReader.close();
4742                } catch (IOException e) {}
4743            }
4744        }
4745        return null;
4746    }
4747
4748    @Override
4749    public String getMobileRedirectedProvisioningUrl() {
4750        enforceConnectivityInternalPermission();
4751        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4752        if (TextUtils.isEmpty(url)) {
4753            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4754        }
4755        return url;
4756    }
4757
4758    @Override
4759    public String getMobileProvisioningUrl() {
4760        enforceConnectivityInternalPermission();
4761        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4762        if (TextUtils.isEmpty(url)) {
4763            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4764            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
4765        } else {
4766            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
4767        }
4768        // populate the iccid, imei and phone number in the provisioning url.
4769        if (!TextUtils.isEmpty(url)) {
4770            String phoneNumber = mTelephonyManager.getLine1Number();
4771            if (TextUtils.isEmpty(phoneNumber)) {
4772                phoneNumber = "0000000000";
4773            }
4774            url = String.format(url,
4775                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
4776                    mTelephonyManager.getDeviceId() /* IMEI */,
4777                    phoneNumber /* Phone numer */);
4778        }
4779
4780        return url;
4781    }
4782
4783    @Override
4784    public void setProvisioningNotificationVisible(boolean visible, int networkType,
4785            String extraInfo, String url) {
4786        enforceConnectivityInternalPermission();
4787        setProvNotificationVisible(visible, networkType, extraInfo, url);
4788    }
4789
4790    @Override
4791    public void setAirplaneMode(boolean enable) {
4792        enforceConnectivityInternalPermission();
4793        final long ident = Binder.clearCallingIdentity();
4794        try {
4795            final ContentResolver cr = mContext.getContentResolver();
4796            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4797            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4798            intent.putExtra("state", enable);
4799            mContext.sendBroadcast(intent);
4800        } finally {
4801            Binder.restoreCallingIdentity(ident);
4802        }
4803    }
4804
4805    private void onUserStart(int userId) {
4806        synchronized(mVpns) {
4807            Vpn userVpn = mVpns.get(userId);
4808            if (userVpn != null) {
4809                loge("Starting user already has a VPN");
4810                return;
4811            }
4812            userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4813            mVpns.put(userId, userVpn);
4814            userVpn.startMonitoring(mContext, mTrackerHandler);
4815        }
4816    }
4817
4818    private void onUserStop(int userId) {
4819        synchronized(mVpns) {
4820            Vpn userVpn = mVpns.get(userId);
4821            if (userVpn == null) {
4822                loge("Stopping user has no VPN");
4823                return;
4824            }
4825            mVpns.delete(userId);
4826        }
4827    }
4828
4829    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4830        @Override
4831        public void onReceive(Context context, Intent intent) {
4832            final String action = intent.getAction();
4833            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4834            if (userId == UserHandle.USER_NULL) return;
4835
4836            if (Intent.ACTION_USER_STARTING.equals(action)) {
4837                onUserStart(userId);
4838            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4839                onUserStop(userId);
4840            }
4841        }
4842    };
4843
4844    @Override
4845    public LinkQualityInfo getLinkQualityInfo(int networkType) {
4846        enforceAccessPermission();
4847        if (isNetworkTypeValid(networkType)) {
4848            return mNetTrackers[networkType].getLinkQualityInfo();
4849        } else {
4850            return null;
4851        }
4852    }
4853
4854    @Override
4855    public LinkQualityInfo getActiveLinkQualityInfo() {
4856        enforceAccessPermission();
4857        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
4858            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
4859        } else {
4860            return null;
4861        }
4862    }
4863
4864    @Override
4865    public LinkQualityInfo[] getAllLinkQualityInfo() {
4866        enforceAccessPermission();
4867        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
4868        for (NetworkStateTracker tracker : mNetTrackers) {
4869            if (tracker != null) {
4870                LinkQualityInfo li = tracker.getLinkQualityInfo();
4871                if (li != null) {
4872                    result.add(li);
4873                }
4874            }
4875        }
4876
4877        return result.toArray(new LinkQualityInfo[result.size()]);
4878    }
4879
4880    /* Infrastructure for network sampling */
4881
4882    private void handleNetworkSamplingTimeout() {
4883
4884        log("Sampling interval elapsed, updating statistics ..");
4885
4886        // initialize list of interfaces ..
4887        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4888                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4889        for (NetworkStateTracker tracker : mNetTrackers) {
4890            if (tracker != null) {
4891                String ifaceName = tracker.getNetworkInterfaceName();
4892                if (ifaceName != null) {
4893                    mapIfaceToSample.put(ifaceName, null);
4894                }
4895            }
4896        }
4897
4898        // Read samples for all interfaces
4899        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4900
4901        // process samples for all networks
4902        for (NetworkStateTracker tracker : mNetTrackers) {
4903            if (tracker != null) {
4904                String ifaceName = tracker.getNetworkInterfaceName();
4905                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4906                if (ss != null) {
4907                    // end the previous sampling cycle
4908                    tracker.stopSampling(ss);
4909                    // start a new sampling cycle ..
4910                    tracker.startSampling(ss);
4911                }
4912            }
4913        }
4914
4915        log("Done.");
4916
4917        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4918                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4919                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4920
4921        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4922
4923        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4924    }
4925
4926    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4927        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4928        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4929    }
4930}
4931