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