ConnectivityService.java revision 8f9b33e77686de8e917ba61c5e2f2e31a1e0e49b
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.telephony.TelephonyIntents;
118import com.android.internal.util.IndentingPrintWriter;
119import com.android.internal.util.XmlUtils;
120import com.android.server.am.BatteryStatsService;
121import com.android.server.connectivity.DataConnectionStats;
122import com.android.server.connectivity.Nat464Xlat;
123import com.android.server.connectivity.PacManager;
124import com.android.server.connectivity.Tethering;
125import com.android.server.connectivity.Vpn;
126import com.android.server.net.BaseNetworkObserver;
127import com.android.server.net.LockdownVpnTracker;
128import com.google.android.collect.Lists;
129import com.google.android.collect.Sets;
130
131import dalvik.system.DexClassLoader;
132
133import org.xmlpull.v1.XmlPullParser;
134import org.xmlpull.v1.XmlPullParserException;
135
136import java.io.File;
137import java.io.FileDescriptor;
138import java.io.FileNotFoundException;
139import java.io.FileReader;
140import java.io.IOException;
141import java.io.PrintWriter;
142import java.lang.reflect.Constructor;
143import java.net.HttpURLConnection;
144import java.net.Inet4Address;
145import java.net.Inet6Address;
146import java.net.InetAddress;
147import java.net.URL;
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 = true;
173
174    private static final boolean LOGD_RULES = true;
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) {
1545        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1546
1547        if (inetAddress == null) {
1548            return false;
1549        }
1550
1551        return requestRouteToHostAddress(networkType, inetAddress.getAddress());
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        enforceChangePermission();
1565        if (mProtectedNetworks.contains(networkType)) {
1566            enforceConnectivityInternalPermission();
1567        }
1568
1569        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1570            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1571            return false;
1572        }
1573        NetworkStateTracker tracker = mNetTrackers[networkType];
1574        DetailedState netState = DetailedState.DISCONNECTED;
1575        if (tracker != null) {
1576            netState = tracker.getNetworkInfo().getDetailedState();
1577        }
1578
1579        if ((netState != DetailedState.CONNECTED &&
1580                netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1581                tracker.isTeardownRequested()) {
1582            if (VDBG) {
1583                log("requestRouteToHostAddress on down network "
1584                        + "(" + networkType + ") - dropped"
1585                        + " tracker=" + tracker
1586                        + " netState=" + netState
1587                        + " isTeardownRequested="
1588                            + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
1589            }
1590            return false;
1591        }
1592        final long token = Binder.clearCallingIdentity();
1593        try {
1594            InetAddress addr = InetAddress.getByAddress(hostAddress);
1595            LinkProperties lp = tracker.getLinkProperties();
1596            boolean ok = addRouteToAddress(lp, addr, EXEMPT);
1597            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1598            return ok;
1599        } catch (UnknownHostException e) {
1600            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1601        } finally {
1602            Binder.restoreCallingIdentity(token);
1603        }
1604        if (DBG) log("requestRouteToHostAddress X bottom return false");
1605        return false;
1606    }
1607
1608    private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1609            boolean exempt) {
1610        return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
1611    }
1612
1613    private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1614        return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
1615    }
1616
1617    private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1618        return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
1619    }
1620
1621    private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1622        return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
1623    }
1624
1625    private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1626            boolean toDefaultTable, boolean exempt) {
1627        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1628        if (bestRoute == null) {
1629            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1630        } else {
1631            String iface = bestRoute.getInterface();
1632            if (bestRoute.getGateway().equals(addr)) {
1633                // if there is no better route, add the implied hostroute for our gateway
1634                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1635            } else {
1636                // if we will connect to this through another route, add a direct route
1637                // to it's gateway
1638                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1639            }
1640        }
1641        return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
1642    }
1643
1644    private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1645            boolean toDefaultTable, boolean exempt) {
1646        if ((lp == null) || (r == null)) {
1647            if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1648            return false;
1649        }
1650
1651        if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1652            loge("Error modifying route - too much recursion");
1653            return false;
1654        }
1655
1656        String ifaceName = r.getInterface();
1657        if(ifaceName == null) {
1658            loge("Error modifying route - no interface name");
1659            return false;
1660        }
1661        if (r.hasGateway()) {
1662            RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1663            if (bestRoute != null) {
1664                if (bestRoute.getGateway().equals(r.getGateway())) {
1665                    // if there is no better route, add the implied hostroute for our gateway
1666                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1667                } else {
1668                    // if we will connect to our gateway through another route, add a direct
1669                    // route to it's gateway
1670                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1671                                                        bestRoute.getGateway(),
1672                                                        ifaceName);
1673                }
1674                modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
1675            }
1676        }
1677        if (doAdd) {
1678            if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1679            try {
1680                if (toDefaultTable) {
1681                    synchronized (mRoutesLock) {
1682                        // only track default table - only one apps can effect
1683                        mAddedRoutes.add(r);
1684                        mNetd.addRoute(ifaceName, r);
1685                        if (exempt) {
1686                            LinkAddress dest = r.getDestination();
1687                            if (!mExemptAddresses.contains(dest)) {
1688                                mNetd.setHostExemption(dest);
1689                                mExemptAddresses.add(dest);
1690                            }
1691                        }
1692                    }
1693                } else {
1694                    mNetd.addSecondaryRoute(ifaceName, r);
1695                }
1696            } catch (Exception e) {
1697                // never crash - catch them all
1698                if (DBG) loge("Exception trying to add a route: " + e);
1699                return false;
1700            }
1701        } else {
1702            // if we remove this one and there are no more like it, then refcount==0 and
1703            // we can remove it from the table
1704            if (toDefaultTable) {
1705                synchronized (mRoutesLock) {
1706                    mAddedRoutes.remove(r);
1707                    if (mAddedRoutes.contains(r) == false) {
1708                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1709                        try {
1710                            mNetd.removeRoute(ifaceName, r);
1711                            LinkAddress dest = r.getDestination();
1712                            if (mExemptAddresses.contains(dest)) {
1713                                mNetd.clearHostExemption(dest);
1714                                mExemptAddresses.remove(dest);
1715                            }
1716                        } catch (Exception e) {
1717                            // never crash - catch them all
1718                            if (VDBG) loge("Exception trying to remove a route: " + e);
1719                            return false;
1720                        }
1721                    } else {
1722                        if (VDBG) log("not removing " + r + " as it's still in use");
1723                    }
1724                }
1725            } else {
1726                if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1727                try {
1728                    mNetd.removeSecondaryRoute(ifaceName, r);
1729                } catch (Exception e) {
1730                    // never crash - catch them all
1731                    if (VDBG) loge("Exception trying to remove a route: " + e);
1732                    return false;
1733                }
1734            }
1735        }
1736        return true;
1737    }
1738
1739    /**
1740     * @see ConnectivityManager#getMobileDataEnabled()
1741     */
1742    public boolean getMobileDataEnabled() {
1743        // TODO: This detail should probably be in DataConnectionTracker's
1744        //       which is where we store the value and maybe make this
1745        //       asynchronous.
1746        enforceAccessPermission();
1747        boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1748                Settings.Global.MOBILE_DATA, 1) == 1;
1749        if (VDBG) log("getMobileDataEnabled returning " + retVal);
1750        return retVal;
1751    }
1752
1753    public void setDataDependency(int networkType, boolean met) {
1754        enforceConnectivityInternalPermission();
1755
1756        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1757                (met ? ENABLED : DISABLED), networkType));
1758    }
1759
1760    private void handleSetDependencyMet(int networkType, boolean met) {
1761        if (mNetTrackers[networkType] != null) {
1762            if (DBG) {
1763                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1764            }
1765            mNetTrackers[networkType].setDependencyMet(met);
1766        }
1767    }
1768
1769    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1770        @Override
1771        public void onUidRulesChanged(int uid, int uidRules) {
1772            // caller is NPMS, since we only register with them
1773            if (LOGD_RULES) {
1774                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1775            }
1776
1777            synchronized (mRulesLock) {
1778                // skip update when we've already applied rules
1779                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1780                if (oldRules == uidRules) return;
1781
1782                mUidRules.put(uid, uidRules);
1783            }
1784
1785            // TODO: notify UID when it has requested targeted updates
1786        }
1787
1788        @Override
1789        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1790            // caller is NPMS, since we only register with them
1791            if (LOGD_RULES) {
1792                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1793            }
1794
1795            synchronized (mRulesLock) {
1796                mMeteredIfaces.clear();
1797                for (String iface : meteredIfaces) {
1798                    mMeteredIfaces.add(iface);
1799                }
1800            }
1801        }
1802
1803        @Override
1804        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1805            // caller is NPMS, since we only register with them
1806            if (LOGD_RULES) {
1807                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1808            }
1809
1810            // kick off connectivity change broadcast for active network, since
1811            // global background policy change is radical.
1812            final int networkType = mActiveDefaultNetwork;
1813            if (isNetworkTypeValid(networkType)) {
1814                final NetworkStateTracker tracker = mNetTrackers[networkType];
1815                if (tracker != null) {
1816                    final NetworkInfo info = tracker.getNetworkInfo();
1817                    if (info != null && info.isConnected()) {
1818                        sendConnectedBroadcast(info);
1819                    }
1820                }
1821            }
1822        }
1823    };
1824
1825    /**
1826     * @see ConnectivityManager#setMobileDataEnabled(boolean)
1827     */
1828    public void setMobileDataEnabled(boolean enabled) {
1829        enforceChangePermission();
1830        if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1831
1832        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1833                (enabled ? ENABLED : DISABLED), 0));
1834    }
1835
1836    private void handleSetMobileData(boolean enabled) {
1837        if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1838            if (VDBG) {
1839                log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1840            }
1841            mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1842        }
1843        if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1844            if (VDBG) {
1845                log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1846            }
1847            mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1848        }
1849    }
1850
1851    @Override
1852    public void setPolicyDataEnable(int networkType, boolean enabled) {
1853        // only someone like NPMS should only be calling us
1854        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1855
1856        mHandler.sendMessage(mHandler.obtainMessage(
1857                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1858    }
1859
1860    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1861        if (isNetworkTypeValid(networkType)) {
1862            final NetworkStateTracker tracker = mNetTrackers[networkType];
1863            if (tracker != null) {
1864                tracker.setPolicyDataEnable(enabled);
1865            }
1866        }
1867    }
1868
1869    private void enforceAccessPermission() {
1870        mContext.enforceCallingOrSelfPermission(
1871                android.Manifest.permission.ACCESS_NETWORK_STATE,
1872                "ConnectivityService");
1873    }
1874
1875    private void enforceChangePermission() {
1876        mContext.enforceCallingOrSelfPermission(
1877                android.Manifest.permission.CHANGE_NETWORK_STATE,
1878                "ConnectivityService");
1879    }
1880
1881    // TODO Make this a special check when it goes public
1882    private void enforceTetherChangePermission() {
1883        mContext.enforceCallingOrSelfPermission(
1884                android.Manifest.permission.CHANGE_NETWORK_STATE,
1885                "ConnectivityService");
1886    }
1887
1888    private void enforceTetherAccessPermission() {
1889        mContext.enforceCallingOrSelfPermission(
1890                android.Manifest.permission.ACCESS_NETWORK_STATE,
1891                "ConnectivityService");
1892    }
1893
1894    private void enforceConnectivityInternalPermission() {
1895        mContext.enforceCallingOrSelfPermission(
1896                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1897                "ConnectivityService");
1898    }
1899
1900    private void enforceMarkNetworkSocketPermission() {
1901        //Media server special case
1902        if (Binder.getCallingUid() == Process.MEDIA_UID) {
1903            return;
1904        }
1905        mContext.enforceCallingOrSelfPermission(
1906                android.Manifest.permission.MARK_NETWORK_SOCKET,
1907                "ConnectivityService");
1908    }
1909
1910    /**
1911     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1912     * network, we ignore it. If it is for the active network, we send out a
1913     * broadcast. But first, we check whether it might be possible to connect
1914     * to a different network.
1915     * @param info the {@code NetworkInfo} for the network
1916     */
1917    private void handleDisconnect(NetworkInfo info) {
1918
1919        int prevNetType = info.getType();
1920
1921        mNetTrackers[prevNetType].setTeardownRequested(false);
1922
1923        // Remove idletimer previously setup in {@code handleConnect}
1924        removeDataActivityTracking(prevNetType);
1925
1926        /*
1927         * If the disconnected network is not the active one, then don't report
1928         * this as a loss of connectivity. What probably happened is that we're
1929         * getting the disconnect for a network that we explicitly disabled
1930         * in accordance with network preference policies.
1931         */
1932        if (!mNetConfigs[prevNetType].isDefault()) {
1933            List<Integer> pids = mNetRequestersPids[prevNetType];
1934            for (Integer pid : pids) {
1935                // will remove them because the net's no longer connected
1936                // need to do this now as only now do we know the pids and
1937                // can properly null things that are no longer referenced.
1938                reassessPidDns(pid.intValue(), false);
1939            }
1940        }
1941
1942        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1943        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1944        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1945        if (info.isFailover()) {
1946            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1947            info.setFailover(false);
1948        }
1949        if (info.getReason() != null) {
1950            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1951        }
1952        if (info.getExtraInfo() != null) {
1953            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1954                    info.getExtraInfo());
1955        }
1956
1957        if (mNetConfigs[prevNetType].isDefault()) {
1958            tryFailover(prevNetType);
1959            if (mActiveDefaultNetwork != -1) {
1960                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1961                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1962            } else {
1963                mDefaultInetConditionPublished = 0; // we're not connected anymore
1964                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1965            }
1966        }
1967        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1968
1969        // Reset interface if no other connections are using the same interface
1970        boolean doReset = true;
1971        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1972        if (linkProperties != null) {
1973            String oldIface = linkProperties.getInterfaceName();
1974            if (TextUtils.isEmpty(oldIface) == false) {
1975                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1976                    if (networkStateTracker == null) continue;
1977                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1978                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1979                        LinkProperties l = networkStateTracker.getLinkProperties();
1980                        if (l == null) continue;
1981                        if (oldIface.equals(l.getInterfaceName())) {
1982                            doReset = false;
1983                            break;
1984                        }
1985                    }
1986                }
1987            }
1988        }
1989
1990        // do this before we broadcast the change
1991        handleConnectivityChange(prevNetType, doReset);
1992
1993        final Intent immediateIntent = new Intent(intent);
1994        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1995        sendStickyBroadcast(immediateIntent);
1996        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1997        /*
1998         * If the failover network is already connected, then immediately send
1999         * out a followup broadcast indicating successful failover
2000         */
2001        if (mActiveDefaultNetwork != -1) {
2002            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2003                    getConnectivityChangeDelay());
2004        }
2005    }
2006
2007    private void tryFailover(int prevNetType) {
2008        /*
2009         * If this is a default network, check if other defaults are available.
2010         * Try to reconnect on all available and let them hash it out when
2011         * more than one connects.
2012         */
2013        if (mNetConfigs[prevNetType].isDefault()) {
2014            if (mActiveDefaultNetwork == prevNetType) {
2015                if (DBG) {
2016                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2017                }
2018                mActiveDefaultNetwork = -1;
2019            }
2020
2021            // don't signal a reconnect for anything lower or equal priority than our
2022            // current connected default
2023            // TODO - don't filter by priority now - nice optimization but risky
2024//            int currentPriority = -1;
2025//            if (mActiveDefaultNetwork != -1) {
2026//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
2027//            }
2028
2029            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
2030                if (checkType == prevNetType) continue;
2031                if (mNetConfigs[checkType] == null) continue;
2032                if (!mNetConfigs[checkType].isDefault()) continue;
2033                if (mNetTrackers[checkType] == null) continue;
2034
2035// Enabling the isAvailable() optimization caused mobile to not get
2036// selected if it was in the middle of error handling. Specifically
2037// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2038// would not be available and we wouldn't get connected to anything.
2039// So removing the isAvailable() optimization below for now. TODO: This
2040// optimization should work and we need to investigate why it doesn't work.
2041// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2042// complete before it is really complete.
2043
2044//                if (!mNetTrackers[checkType].isAvailable()) continue;
2045
2046//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
2047
2048                NetworkStateTracker checkTracker = mNetTrackers[checkType];
2049                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2050                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2051                    checkInfo.setFailover(true);
2052                    checkTracker.reconnect();
2053                }
2054                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
2055            }
2056        }
2057    }
2058
2059    public void sendConnectedBroadcast(NetworkInfo info) {
2060        enforceConnectivityInternalPermission();
2061        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2062        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2063    }
2064
2065    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
2066        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2067        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
2068    }
2069
2070    private void sendInetConditionBroadcast(NetworkInfo info) {
2071        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2072    }
2073
2074    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2075        if (mLockdownTracker != null) {
2076            info = mLockdownTracker.augmentNetworkInfo(info);
2077        }
2078
2079        Intent intent = new Intent(bcastType);
2080        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2081        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2082        if (info.isFailover()) {
2083            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2084            info.setFailover(false);
2085        }
2086        if (info.getReason() != null) {
2087            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2088        }
2089        if (info.getExtraInfo() != null) {
2090            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2091                    info.getExtraInfo());
2092        }
2093        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2094        return intent;
2095    }
2096
2097    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2098        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2099    }
2100
2101    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2102        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
2103    }
2104
2105    private void sendDataActivityBroadcast(int deviceType, boolean active) {
2106        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2107        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2108        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
2109        final long ident = Binder.clearCallingIdentity();
2110        try {
2111            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2112                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2113        } finally {
2114            Binder.restoreCallingIdentity(ident);
2115        }
2116    }
2117
2118    /**
2119     * Called when an attempt to fail over to another network has failed.
2120     * @param info the {@link NetworkInfo} for the failed network
2121     */
2122    private void handleConnectionFailure(NetworkInfo info) {
2123        mNetTrackers[info.getType()].setTeardownRequested(false);
2124
2125        String reason = info.getReason();
2126        String extraInfo = info.getExtraInfo();
2127
2128        String reasonText;
2129        if (reason == null) {
2130            reasonText = ".";
2131        } else {
2132            reasonText = " (" + reason + ").";
2133        }
2134        loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
2135
2136        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
2137        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2138        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2139        if (getActiveNetworkInfo() == null) {
2140            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2141        }
2142        if (reason != null) {
2143            intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2144        }
2145        if (extraInfo != null) {
2146            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2147        }
2148        if (info.isFailover()) {
2149            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2150            info.setFailover(false);
2151        }
2152
2153        if (mNetConfigs[info.getType()].isDefault()) {
2154            tryFailover(info.getType());
2155            if (mActiveDefaultNetwork != -1) {
2156                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2157                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2158            } else {
2159                mDefaultInetConditionPublished = 0;
2160                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2161            }
2162        }
2163
2164        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2165
2166        final Intent immediateIntent = new Intent(intent);
2167        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2168        sendStickyBroadcast(immediateIntent);
2169        sendStickyBroadcast(intent);
2170        /*
2171         * If the failover network is already connected, then immediately send
2172         * out a followup broadcast indicating successful failover
2173         */
2174        if (mActiveDefaultNetwork != -1) {
2175            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
2176        }
2177    }
2178
2179    private void sendStickyBroadcast(Intent intent) {
2180        synchronized(this) {
2181            if (!mSystemReady) {
2182                mInitialBroadcast = new Intent(intent);
2183            }
2184            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2185            if (VDBG) {
2186                log("sendStickyBroadcast: action=" + intent.getAction());
2187            }
2188
2189            final long ident = Binder.clearCallingIdentity();
2190            try {
2191                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2192            } finally {
2193                Binder.restoreCallingIdentity(ident);
2194            }
2195        }
2196    }
2197
2198    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2199        if (delayMs <= 0) {
2200            sendStickyBroadcast(intent);
2201        } else {
2202            if (VDBG) {
2203                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2204                        + intent.getAction());
2205            }
2206            mHandler.sendMessageDelayed(mHandler.obtainMessage(
2207                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2208        }
2209    }
2210
2211    void systemReady() {
2212        mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2213        loadGlobalProxy();
2214
2215        synchronized(this) {
2216            mSystemReady = true;
2217            if (mInitialBroadcast != null) {
2218                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2219                mInitialBroadcast = null;
2220            }
2221        }
2222        // load the global proxy at startup
2223        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2224
2225        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2226        // for user to unlock device.
2227        if (!updateLockdownVpn()) {
2228            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2229            mContext.registerReceiver(mUserPresentReceiver, filter);
2230        }
2231    }
2232
2233    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2234        @Override
2235        public void onReceive(Context context, Intent intent) {
2236            // Try creating lockdown tracker, since user present usually means
2237            // unlocked keystore.
2238            if (updateLockdownVpn()) {
2239                mContext.unregisterReceiver(this);
2240            }
2241        }
2242    };
2243
2244    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2245        if (((type != mNetworkPreference)
2246                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2247                   || (mNetworkPreference == mActiveDefaultNetwork)) {
2248            return false;
2249        }
2250        return true;
2251    }
2252
2253    private void handleConnect(NetworkInfo info) {
2254        final int newNetType = info.getType();
2255
2256        setupDataActivityTracking(newNetType);
2257
2258        // snapshot isFailover, because sendConnectedBroadcast() resets it
2259        boolean isFailover = info.isFailover();
2260        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2261        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2262
2263        if (VDBG) {
2264            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2265                    + " isFailover" + isFailover);
2266        }
2267
2268        // if this is a default net and other default is running
2269        // kill the one not preferred
2270        if (mNetConfigs[newNetType].isDefault()) {
2271            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2272                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2273                    // tear down the other
2274                    NetworkStateTracker otherNet =
2275                            mNetTrackers[mActiveDefaultNetwork];
2276                    if (DBG) {
2277                        log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2278                            " teardown");
2279                    }
2280                    if (!teardown(otherNet)) {
2281                        loge("Network declined teardown request");
2282                        teardown(thisNet);
2283                        return;
2284                    }
2285                } else {
2286                       // don't accept this one
2287                        if (VDBG) {
2288                            log("Not broadcasting CONNECT_ACTION " +
2289                                "to torn down network " + info.getTypeName());
2290                        }
2291                        teardown(thisNet);
2292                        return;
2293                }
2294            }
2295            synchronized (ConnectivityService.this) {
2296                // have a new default network, release the transition wakelock in a second
2297                // if it's held.  The second pause is to allow apps to reconnect over the
2298                // new network
2299                if (mNetTransitionWakeLock.isHeld()) {
2300                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
2301                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2302                            mNetTransitionWakeLockSerialNumber, 0),
2303                            1000);
2304                }
2305            }
2306            mActiveDefaultNetwork = newNetType;
2307            // this will cause us to come up initially as unconnected and switching
2308            // to connected after our normal pause unless somebody reports us as reall
2309            // disconnected
2310            mDefaultInetConditionPublished = 0;
2311            mDefaultConnectionSequence++;
2312            mInetConditionChangeInFlight = false;
2313            // Don't do this - if we never sign in stay, grey
2314            //reportNetworkCondition(mActiveDefaultNetwork, 100);
2315        }
2316        thisNet.setTeardownRequested(false);
2317        updateNetworkSettings(thisNet);
2318        updateMtuSizeSettings(thisNet);
2319        handleConnectivityChange(newNetType, false);
2320        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2321
2322        // notify battery stats service about this network
2323        if (thisIface != null) {
2324            try {
2325                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2326            } catch (RemoteException e) {
2327                // ignored; service lives in system_server
2328            }
2329        }
2330    }
2331
2332    /** @hide */
2333    @Override
2334    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2335        enforceConnectivityInternalPermission();
2336        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2337        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2338    }
2339
2340    /**
2341     * Setup data activity tracking for the given network interface.
2342     *
2343     * Every {@code setupDataActivityTracking} should be paired with a
2344     * {@link removeDataActivityTracking} for cleanup.
2345     */
2346    private void setupDataActivityTracking(int type) {
2347        final NetworkStateTracker thisNet = mNetTrackers[type];
2348        final String iface = thisNet.getLinkProperties().getInterfaceName();
2349
2350        final int timeout;
2351
2352        if (ConnectivityManager.isNetworkTypeMobile(type)) {
2353            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2354                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2355                                             0);
2356            // Canonicalize mobile network type
2357            type = ConnectivityManager.TYPE_MOBILE;
2358        } else if (ConnectivityManager.TYPE_WIFI == type) {
2359            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2360                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2361                                             0);
2362        } else {
2363            // do not track any other networks
2364            timeout = 0;
2365        }
2366
2367        if (timeout > 0 && iface != null) {
2368            try {
2369                mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2370            } catch (RemoteException e) {
2371            }
2372        }
2373    }
2374
2375    /**
2376     * Remove data activity tracking when network disconnects.
2377     */
2378    private void removeDataActivityTracking(int type) {
2379        final NetworkStateTracker net = mNetTrackers[type];
2380        final String iface = net.getLinkProperties().getInterfaceName();
2381
2382        if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2383                              ConnectivityManager.TYPE_WIFI == type)) {
2384            try {
2385                // the call fails silently if no idletimer setup for this interface
2386                mNetd.removeIdleTimer(iface);
2387            } catch (RemoteException e) {
2388            }
2389        }
2390    }
2391
2392    /**
2393     * After a change in the connectivity state of a network. We're mainly
2394     * concerned with making sure that the list of DNS servers is set up
2395     * according to which networks are connected, and ensuring that the
2396     * right routing table entries exist.
2397     */
2398    private void handleConnectivityChange(int netType, boolean doReset) {
2399        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2400        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
2401        if (VDBG) {
2402            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2403                    + " resetMask=" + resetMask);
2404        }
2405
2406        /*
2407         * If a non-default network is enabled, add the host routes that
2408         * will allow it's DNS servers to be accessed.
2409         */
2410        handleDnsConfigurationChange(netType);
2411
2412        LinkProperties curLp = mCurrentLinkProperties[netType];
2413        LinkProperties newLp = null;
2414
2415        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2416            newLp = mNetTrackers[netType].getLinkProperties();
2417            if (VDBG) {
2418                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2419                        " doReset=" + doReset + " resetMask=" + resetMask +
2420                        "\n   curLp=" + curLp +
2421                        "\n   newLp=" + newLp);
2422            }
2423
2424            if (curLp != null) {
2425                if (curLp.isIdenticalInterfaceName(newLp)) {
2426                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2427                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2428                        for (LinkAddress linkAddr : car.removed) {
2429                            if (linkAddr.getAddress() instanceof Inet4Address) {
2430                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2431                            }
2432                            if (linkAddr.getAddress() instanceof Inet6Address) {
2433                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2434                            }
2435                        }
2436                        if (DBG) {
2437                            log("handleConnectivityChange: addresses changed" +
2438                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2439                                    "\n   car=" + car);
2440                        }
2441                    } else {
2442                        if (VDBG) {
2443                            log("handleConnectivityChange: addresses are the same reset per" +
2444                                   " doReset linkProperty[" + netType + "]:" +
2445                                   " resetMask=" + resetMask);
2446                        }
2447                    }
2448                } else {
2449                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2450                    if (DBG) {
2451                        log("handleConnectivityChange: interface not not equivalent reset both" +
2452                                " linkProperty[" + netType + "]:" +
2453                                " resetMask=" + resetMask);
2454                    }
2455                }
2456            }
2457            if (mNetConfigs[netType].isDefault()) {
2458                handleApplyDefaultProxy(newLp.getHttpProxy());
2459            }
2460        } else {
2461            if (VDBG) {
2462                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2463                        " doReset=" + doReset + " resetMask=" + resetMask +
2464                        "\n  curLp=" + curLp +
2465                        "\n  newLp= null");
2466            }
2467        }
2468        mCurrentLinkProperties[netType] = newLp;
2469        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
2470
2471        if (resetMask != 0 || resetDns) {
2472            if (VDBG) log("handleConnectivityChange: resetting");
2473            if (curLp != null) {
2474                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
2475                for (String iface : curLp.getAllInterfaceNames()) {
2476                    if (TextUtils.isEmpty(iface) == false) {
2477                        if (resetMask != 0) {
2478                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2479                            NetworkUtils.resetConnections(iface, resetMask);
2480
2481                            // Tell VPN the interface is down. It is a temporary
2482                            // but effective fix to make VPN aware of the change.
2483                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2484                                synchronized(mVpns) {
2485                                    for (int i = 0; i < mVpns.size(); i++) {
2486                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2487                                    }
2488                                }
2489                            }
2490                        }
2491                        if (resetDns) {
2492                            flushVmDnsCache();
2493                            if (VDBG) log("resetting DNS cache for " + iface);
2494                            try {
2495                                mNetd.flushInterfaceDnsCache(iface);
2496                            } catch (Exception e) {
2497                                // never crash - catch them all
2498                                if (DBG) loge("Exception resetting dns cache: " + e);
2499                            }
2500                        }
2501                    } else {
2502                        loge("Can't reset connection for type "+netType);
2503                    }
2504                }
2505            }
2506        }
2507
2508        // Update 464xlat state.
2509        NetworkStateTracker tracker = mNetTrackers[netType];
2510        if (mClat.requiresClat(netType, tracker)) {
2511
2512            // If the connection was previously using clat, but is not using it now, stop the clat
2513            // daemon. Normally, this happens automatically when the connection disconnects, but if
2514            // the disconnect is not reported, or if the connection's LinkProperties changed for
2515            // some other reason (e.g., handoff changes the IP addresses on the link), it would
2516            // still be running. If it's not running, then stopping it is a no-op.
2517            if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2518                mClat.stopClat();
2519            }
2520            // If the link requires clat to be running, then start the daemon now.
2521            if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2522                mClat.startClat(tracker);
2523            } else {
2524                mClat.stopClat();
2525            }
2526        }
2527
2528        // TODO: Temporary notifying upstread change to Tethering.
2529        //       @see bug/4455071
2530        /** Notify TetheringService if interface name has been changed. */
2531        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2532                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2533            if (isTetheringSupported()) {
2534                mTethering.handleTetherIfaceChange();
2535            }
2536        }
2537    }
2538
2539    /**
2540     * Add and remove routes using the old properties (null if not previously connected),
2541     * new properties (null if becoming disconnected).  May even be double null, which
2542     * is a noop.
2543     * Uses isLinkDefault to determine if default routes should be set or conversely if
2544     * host routes should be set to the dns servers
2545     * returns a boolean indicating the routes changed
2546     */
2547    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2548            boolean isLinkDefault, boolean exempt) {
2549        Collection<RouteInfo> routesToAdd = null;
2550        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2551        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2552        if (curLp != null) {
2553            // check for the delta between the current set and the new
2554            routeDiff = curLp.compareAllRoutes(newLp);
2555            dnsDiff = curLp.compareDnses(newLp);
2556        } else if (newLp != null) {
2557            routeDiff.added = newLp.getAllRoutes();
2558            dnsDiff.added = newLp.getDnses();
2559        }
2560
2561        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2562
2563        for (RouteInfo r : routeDiff.removed) {
2564            if (isLinkDefault || ! r.isDefaultRoute()) {
2565                if (VDBG) log("updateRoutes: default remove route r=" + r);
2566                removeRoute(curLp, r, TO_DEFAULT_TABLE);
2567            }
2568            if (isLinkDefault == false) {
2569                // remove from a secondary route table
2570                removeRoute(curLp, r, TO_SECONDARY_TABLE);
2571            }
2572        }
2573
2574        if (!isLinkDefault) {
2575            // handle DNS routes
2576            if (routesChanged) {
2577                // routes changed - remove all old dns entries and add new
2578                if (curLp != null) {
2579                    for (InetAddress oldDns : curLp.getDnses()) {
2580                        removeRouteToAddress(curLp, oldDns);
2581                    }
2582                }
2583                if (newLp != null) {
2584                    for (InetAddress newDns : newLp.getDnses()) {
2585                        addRouteToAddress(newLp, newDns, exempt);
2586                    }
2587                }
2588            } else {
2589                // no change in routes, check for change in dns themselves
2590                for (InetAddress oldDns : dnsDiff.removed) {
2591                    removeRouteToAddress(curLp, oldDns);
2592                }
2593                for (InetAddress newDns : dnsDiff.added) {
2594                    addRouteToAddress(newLp, newDns, exempt);
2595                }
2596            }
2597        }
2598
2599        for (RouteInfo r :  routeDiff.added) {
2600            if (isLinkDefault || ! r.isDefaultRoute()) {
2601                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
2602            } else {
2603                // add to a secondary route table
2604                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
2605
2606                // many radios add a default route even when we don't want one.
2607                // remove the default route unless somebody else has asked for it
2608                String ifaceName = newLp.getInterfaceName();
2609                synchronized (mRoutesLock) {
2610                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2611                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2612                        try {
2613                            mNetd.removeRoute(ifaceName, r);
2614                        } catch (Exception e) {
2615                            // never crash - catch them all
2616                            if (DBG) loge("Exception trying to remove a route: " + e);
2617                        }
2618                    }
2619                }
2620            }
2621        }
2622
2623        return routesChanged;
2624    }
2625
2626   /**
2627     * Reads the network specific MTU size from reources.
2628     * and set it on it's iface.
2629     */
2630   private void updateMtuSizeSettings(NetworkStateTracker nt) {
2631       final String iface = nt.getLinkProperties().getInterfaceName();
2632       final int mtu = nt.getLinkProperties().getMtu();
2633
2634       if (mtu < 68 || mtu > 10000) {
2635           loge("Unexpected mtu value: " + nt);
2636           return;
2637       }
2638
2639       try {
2640           if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2641           mNetd.setMtu(iface, mtu);
2642       } catch (Exception e) {
2643           Slog.e(TAG, "exception in setMtu()" + e);
2644       }
2645   }
2646
2647    /**
2648     * Reads the network specific TCP buffer sizes from SystemProperties
2649     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2650     * wide use
2651     */
2652    private void updateNetworkSettings(NetworkStateTracker nt) {
2653        String key = nt.getTcpBufferSizesPropName();
2654        String bufferSizes = key == null ? null : SystemProperties.get(key);
2655
2656        if (TextUtils.isEmpty(bufferSizes)) {
2657            if (VDBG) log(key + " not found in system properties. Using defaults");
2658
2659            // Setting to default values so we won't be stuck to previous values
2660            key = "net.tcp.buffersize.default";
2661            bufferSizes = SystemProperties.get(key);
2662        }
2663
2664        // Set values in kernel
2665        if (bufferSizes.length() != 0) {
2666            if (VDBG) {
2667                log("Setting TCP values: [" + bufferSizes
2668                        + "] which comes from [" + key + "]");
2669            }
2670            setBufferSize(bufferSizes);
2671        }
2672    }
2673
2674    /**
2675     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2676     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2677     *
2678     * @param bufferSizes in the format of "readMin, readInitial, readMax,
2679     *        writeMin, writeInitial, writeMax"
2680     */
2681    private void setBufferSize(String bufferSizes) {
2682        try {
2683            String[] values = bufferSizes.split(",");
2684
2685            if (values.length == 6) {
2686              final String prefix = "/sys/kernel/ipv4/tcp_";
2687                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2688                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2689                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2690                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2691                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2692                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2693            } else {
2694                loge("Invalid buffersize string: " + bufferSizes);
2695            }
2696        } catch (IOException e) {
2697            loge("Can't set tcp buffer sizes:" + e);
2698        }
2699    }
2700
2701    /**
2702     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2703     * on the highest priority active net which this process requested.
2704     * If there aren't any, clear it out
2705     */
2706    private void reassessPidDns(int pid, boolean doBump)
2707    {
2708        if (VDBG) log("reassessPidDns for pid " + pid);
2709        Integer myPid = new Integer(pid);
2710        for(int i : mPriorityList) {
2711            if (mNetConfigs[i].isDefault()) {
2712                continue;
2713            }
2714            NetworkStateTracker nt = mNetTrackers[i];
2715            if (nt.getNetworkInfo().isConnected() &&
2716                    !nt.isTeardownRequested()) {
2717                LinkProperties p = nt.getLinkProperties();
2718                if (p == null) continue;
2719                if (mNetRequestersPids[i].contains(myPid)) {
2720                    try {
2721                        mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2722                    } catch (Exception e) {
2723                        Slog.e(TAG, "exception reasseses pid dns: " + e);
2724                    }
2725                    return;
2726                }
2727           }
2728        }
2729        // nothing found - delete
2730        try {
2731            mNetd.clearDnsInterfaceForPid(pid);
2732        } catch (Exception e) {
2733            Slog.e(TAG, "exception clear interface from pid: " + e);
2734        }
2735    }
2736
2737    private void flushVmDnsCache() {
2738        /*
2739         * Tell the VMs to toss their DNS caches
2740         */
2741        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2742        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2743        /*
2744         * Connectivity events can happen before boot has completed ...
2745         */
2746        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2747        final long ident = Binder.clearCallingIdentity();
2748        try {
2749            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2750        } finally {
2751            Binder.restoreCallingIdentity(ident);
2752        }
2753    }
2754
2755    // Caller must grab mDnsLock.
2756    private void updateDnsLocked(String network, String iface,
2757            Collection<InetAddress> dnses, String domains, boolean defaultDns) {
2758        int last = 0;
2759        if (dnses.size() == 0 && mDefaultDns != null) {
2760            dnses = new ArrayList();
2761            dnses.add(mDefaultDns);
2762            if (DBG) {
2763                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2764            }
2765        }
2766
2767        try {
2768            mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2769            if (defaultDns) {
2770                mNetd.setDefaultInterfaceForDns(iface);
2771            }
2772
2773            for (InetAddress dns : dnses) {
2774                ++last;
2775                String key = "net.dns" + last;
2776                String value = dns.getHostAddress();
2777                SystemProperties.set(key, value);
2778            }
2779            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2780                String key = "net.dns" + i;
2781                SystemProperties.set(key, "");
2782            }
2783            mNumDnsEntries = last;
2784        } catch (Exception e) {
2785            loge("exception setting default dns interface: " + e);
2786        }
2787    }
2788
2789    private void handleDnsConfigurationChange(int netType) {
2790        // add default net's dns entries
2791        NetworkStateTracker nt = mNetTrackers[netType];
2792        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2793            LinkProperties p = nt.getLinkProperties();
2794            if (p == null) return;
2795            Collection<InetAddress> dnses = p.getDnses();
2796            if (mNetConfigs[netType].isDefault()) {
2797                String network = nt.getNetworkInfo().getTypeName();
2798                synchronized (mDnsLock) {
2799                    updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
2800                }
2801            } else {
2802                try {
2803                    mNetd.setDnsServersForInterface(p.getInterfaceName(),
2804                            NetworkUtils.makeStrings(dnses), p.getDomains());
2805                } catch (Exception e) {
2806                    if (DBG) loge("exception setting dns servers: " + e);
2807                }
2808                // set per-pid dns for attached secondary nets
2809                List<Integer> pids = mNetRequestersPids[netType];
2810                for (Integer pid : pids) {
2811                    try {
2812                        mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2813                    } catch (Exception e) {
2814                        Slog.e(TAG, "exception setting interface for pid: " + e);
2815                    }
2816                }
2817            }
2818            flushVmDnsCache();
2819        }
2820    }
2821
2822    private int getRestoreDefaultNetworkDelay(int networkType) {
2823        String restoreDefaultNetworkDelayStr = SystemProperties.get(
2824                NETWORK_RESTORE_DELAY_PROP_NAME);
2825        if(restoreDefaultNetworkDelayStr != null &&
2826                restoreDefaultNetworkDelayStr.length() != 0) {
2827            try {
2828                return Integer.valueOf(restoreDefaultNetworkDelayStr);
2829            } catch (NumberFormatException e) {
2830            }
2831        }
2832        // if the system property isn't set, use the value for the apn type
2833        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2834
2835        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2836                (mNetConfigs[networkType] != null)) {
2837            ret = mNetConfigs[networkType].restoreTime;
2838        }
2839        return ret;
2840    }
2841
2842    @Override
2843    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2844        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2845        if (mContext.checkCallingOrSelfPermission(
2846                android.Manifest.permission.DUMP)
2847                != PackageManager.PERMISSION_GRANTED) {
2848            pw.println("Permission Denial: can't dump ConnectivityService " +
2849                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
2850                    Binder.getCallingUid());
2851            return;
2852        }
2853
2854        // TODO: add locking to get atomic snapshot
2855        pw.println();
2856        for (int i = 0; i < mNetTrackers.length; i++) {
2857            final NetworkStateTracker nst = mNetTrackers[i];
2858            if (nst != null) {
2859                pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2860                pw.increaseIndent();
2861                if (nst.getNetworkInfo().isConnected()) {
2862                    pw.println("Active network: " + nst.getNetworkInfo().
2863                            getTypeName());
2864                }
2865                pw.println(nst.getNetworkInfo());
2866                pw.println(nst.getLinkProperties());
2867                pw.println(nst);
2868                pw.println();
2869                pw.decreaseIndent();
2870            }
2871        }
2872
2873        pw.println("Network Requester Pids:");
2874        pw.increaseIndent();
2875        for (int net : mPriorityList) {
2876            String pidString = net + ": ";
2877            for (Integer pid : mNetRequestersPids[net]) {
2878                pidString = pidString + pid.toString() + ", ";
2879            }
2880            pw.println(pidString);
2881        }
2882        pw.println();
2883        pw.decreaseIndent();
2884
2885        pw.println("FeatureUsers:");
2886        pw.increaseIndent();
2887        for (Object requester : mFeatureUsers) {
2888            pw.println(requester.toString());
2889        }
2890        pw.println();
2891        pw.decreaseIndent();
2892
2893        synchronized (this) {
2894            pw.println("NetworkTranstionWakeLock is currently " +
2895                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2896            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2897        }
2898        pw.println();
2899
2900        mTethering.dump(fd, pw, args);
2901
2902        if (mInetLog != null) {
2903            pw.println();
2904            pw.println("Inet condition reports:");
2905            pw.increaseIndent();
2906            for(int i = 0; i < mInetLog.size(); i++) {
2907                pw.println(mInetLog.get(i));
2908            }
2909            pw.decreaseIndent();
2910        }
2911    }
2912
2913    // must be stateless - things change under us.
2914    private class NetworkStateTrackerHandler extends Handler {
2915        public NetworkStateTrackerHandler(Looper looper) {
2916            super(looper);
2917        }
2918
2919        @Override
2920        public void handleMessage(Message msg) {
2921            NetworkInfo info;
2922            switch (msg.what) {
2923                case NetworkStateTracker.EVENT_STATE_CHANGED: {
2924                    info = (NetworkInfo) msg.obj;
2925                    NetworkInfo.State state = info.getState();
2926
2927                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2928                            (state == NetworkInfo.State.DISCONNECTED) ||
2929                            (state == NetworkInfo.State.SUSPENDED)) {
2930                        log("ConnectivityChange for " +
2931                            info.getTypeName() + ": " +
2932                            state + "/" + info.getDetailedState());
2933                    }
2934
2935                    // Since mobile has the notion of a network/apn that can be used for
2936                    // provisioning we need to check every time we're connected as
2937                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
2938                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2939                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2940                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
2941                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
2942                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2943                                        Settings.Global.DEVICE_PROVISIONED, 0))
2944                            && (((state == NetworkInfo.State.CONNECTED)
2945                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2946                                || info.isConnectedToProvisioningNetwork())) {
2947                        log("ConnectivityChange checkMobileProvisioning for"
2948                                + " TYPE_MOBILE or ProvisioningNetwork");
2949                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
2950                    }
2951
2952                    EventLogTags.writeConnectivityStateChanged(
2953                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2954
2955                    if (info.getDetailedState() ==
2956                            NetworkInfo.DetailedState.FAILED) {
2957                        handleConnectionFailure(info);
2958                    } else if (info.isConnectedToProvisioningNetwork()) {
2959                        /**
2960                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2961                         * for now its an in between network, its a network that
2962                         * is actually a default network but we don't want it to be
2963                         * announced as such to keep background applications from
2964                         * trying to use it. It turns out that some still try so we
2965                         * take the additional step of clearing any default routes
2966                         * to the link that may have incorrectly setup by the lower
2967                         * levels.
2968                         */
2969                        LinkProperties lp = getLinkProperties(info.getType());
2970                        if (DBG) {
2971                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2972                        }
2973
2974                        // Clear any default routes setup by the radio so
2975                        // any activity by applications trying to use this
2976                        // connection will fail until the provisioning network
2977                        // is enabled.
2978                        for (RouteInfo r : lp.getRoutes()) {
2979                            removeRoute(lp, r, TO_DEFAULT_TABLE);
2980                        }
2981                    } else if (state == NetworkInfo.State.DISCONNECTED) {
2982                        handleDisconnect(info);
2983                    } else if (state == NetworkInfo.State.SUSPENDED) {
2984                        // TODO: need to think this over.
2985                        // the logic here is, handle SUSPENDED the same as
2986                        // DISCONNECTED. The only difference being we are
2987                        // broadcasting an intent with NetworkInfo that's
2988                        // suspended. This allows the applications an
2989                        // opportunity to handle DISCONNECTED and SUSPENDED
2990                        // differently, or not.
2991                        handleDisconnect(info);
2992                    } else if (state == NetworkInfo.State.CONNECTED) {
2993                        handleConnect(info);
2994                    }
2995                    if (mLockdownTracker != null) {
2996                        mLockdownTracker.onNetworkInfoChanged(info);
2997                    }
2998                    break;
2999                }
3000                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
3001                    info = (NetworkInfo) msg.obj;
3002                    // TODO: Temporary allowing network configuration
3003                    //       change not resetting sockets.
3004                    //       @see bug/4455071
3005                    handleConnectivityChange(info.getType(), false);
3006                    break;
3007                }
3008                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
3009                    info = (NetworkInfo) msg.obj;
3010                    int type = info.getType();
3011                    updateNetworkSettings(mNetTrackers[type]);
3012                    break;
3013                }
3014            }
3015        }
3016    }
3017
3018    private class InternalHandler extends Handler {
3019        public InternalHandler(Looper looper) {
3020            super(looper);
3021        }
3022
3023        @Override
3024        public void handleMessage(Message msg) {
3025            NetworkInfo info;
3026            switch (msg.what) {
3027                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
3028                    String causedBy = null;
3029                    synchronized (ConnectivityService.this) {
3030                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3031                                mNetTransitionWakeLock.isHeld()) {
3032                            mNetTransitionWakeLock.release();
3033                            causedBy = mNetTransitionWakeLockCausedBy;
3034                        }
3035                    }
3036                    if (causedBy != null) {
3037                        log("NetTransition Wakelock for " + causedBy + " released by timeout");
3038                    }
3039                    break;
3040                }
3041                case EVENT_RESTORE_DEFAULT_NETWORK: {
3042                    FeatureUser u = (FeatureUser)msg.obj;
3043                    u.expire();
3044                    break;
3045                }
3046                case EVENT_INET_CONDITION_CHANGE: {
3047                    int netType = msg.arg1;
3048                    int condition = msg.arg2;
3049                    handleInetConditionChange(netType, condition);
3050                    break;
3051                }
3052                case EVENT_INET_CONDITION_HOLD_END: {
3053                    int netType = msg.arg1;
3054                    int sequence = msg.arg2;
3055                    handleInetConditionHoldEnd(netType, sequence);
3056                    break;
3057                }
3058                case EVENT_SET_NETWORK_PREFERENCE: {
3059                    int preference = msg.arg1;
3060                    handleSetNetworkPreference(preference);
3061                    break;
3062                }
3063                case EVENT_SET_MOBILE_DATA: {
3064                    boolean enabled = (msg.arg1 == ENABLED);
3065                    handleSetMobileData(enabled);
3066                    break;
3067                }
3068                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
3069                    handleDeprecatedGlobalHttpProxy();
3070                    break;
3071                }
3072                case EVENT_SET_DEPENDENCY_MET: {
3073                    boolean met = (msg.arg1 == ENABLED);
3074                    handleSetDependencyMet(msg.arg2, met);
3075                    break;
3076                }
3077                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
3078                    Intent intent = (Intent)msg.obj;
3079                    sendStickyBroadcast(intent);
3080                    break;
3081                }
3082                case EVENT_SET_POLICY_DATA_ENABLE: {
3083                    final int networkType = msg.arg1;
3084                    final boolean enabled = msg.arg2 == ENABLED;
3085                    handleSetPolicyDataEnable(networkType, enabled);
3086                    break;
3087                }
3088                case EVENT_VPN_STATE_CHANGED: {
3089                    if (mLockdownTracker != null) {
3090                        mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3091                    }
3092                    break;
3093                }
3094                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3095                    int tag = mEnableFailFastMobileDataTag.get();
3096                    if (msg.arg1 == tag) {
3097                        MobileDataStateTracker mobileDst =
3098                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3099                        if (mobileDst != null) {
3100                            mobileDst.setEnableFailFastMobileData(msg.arg2);
3101                        }
3102                    } else {
3103                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3104                                + " != tag:" + tag);
3105                    }
3106                    break;
3107                }
3108                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
3109                    handleNetworkSamplingTimeout();
3110                    break;
3111                }
3112                case EVENT_PROXY_HAS_CHANGED: {
3113                    handleApplyDefaultProxy((ProxyProperties)msg.obj);
3114                    break;
3115                }
3116            }
3117        }
3118    }
3119
3120    // javadoc from interface
3121    public int tether(String iface) {
3122        enforceTetherChangePermission();
3123
3124        if (isTetheringSupported()) {
3125            return mTethering.tether(iface);
3126        } else {
3127            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3128        }
3129    }
3130
3131    // javadoc from interface
3132    public int untether(String iface) {
3133        enforceTetherChangePermission();
3134
3135        if (isTetheringSupported()) {
3136            return mTethering.untether(iface);
3137        } else {
3138            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3139        }
3140    }
3141
3142    // javadoc from interface
3143    public int getLastTetherError(String iface) {
3144        enforceTetherAccessPermission();
3145
3146        if (isTetheringSupported()) {
3147            return mTethering.getLastTetherError(iface);
3148        } else {
3149            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3150        }
3151    }
3152
3153    // TODO - proper iface API for selection by property, inspection, etc
3154    public String[] getTetherableUsbRegexs() {
3155        enforceTetherAccessPermission();
3156        if (isTetheringSupported()) {
3157            return mTethering.getTetherableUsbRegexs();
3158        } else {
3159            return new String[0];
3160        }
3161    }
3162
3163    public String[] getTetherableWifiRegexs() {
3164        enforceTetherAccessPermission();
3165        if (isTetheringSupported()) {
3166            return mTethering.getTetherableWifiRegexs();
3167        } else {
3168            return new String[0];
3169        }
3170    }
3171
3172    public String[] getTetherableBluetoothRegexs() {
3173        enforceTetherAccessPermission();
3174        if (isTetheringSupported()) {
3175            return mTethering.getTetherableBluetoothRegexs();
3176        } else {
3177            return new String[0];
3178        }
3179    }
3180
3181    public int setUsbTethering(boolean enable) {
3182        enforceTetherChangePermission();
3183        if (isTetheringSupported()) {
3184            return mTethering.setUsbTethering(enable);
3185        } else {
3186            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3187        }
3188    }
3189
3190    // TODO - move iface listing, queries, etc to new module
3191    // javadoc from interface
3192    public String[] getTetherableIfaces() {
3193        enforceTetherAccessPermission();
3194        return mTethering.getTetherableIfaces();
3195    }
3196
3197    public String[] getTetheredIfaces() {
3198        enforceTetherAccessPermission();
3199        return mTethering.getTetheredIfaces();
3200    }
3201
3202    public String[] getTetheringErroredIfaces() {
3203        enforceTetherAccessPermission();
3204        return mTethering.getErroredIfaces();
3205    }
3206
3207    // if ro.tether.denied = true we default to no tethering
3208    // gservices could set the secure setting to 1 though to enable it on a build where it
3209    // had previously been turned off.
3210    public boolean isTetheringSupported() {
3211        enforceTetherAccessPermission();
3212        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3213        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3214                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3215        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3216                mTethering.getTetherableWifiRegexs().length != 0 ||
3217                mTethering.getTetherableBluetoothRegexs().length != 0) &&
3218                mTethering.getUpstreamIfaceTypes().length != 0);
3219    }
3220
3221    // An API NetworkStateTrackers can call when they lose their network.
3222    // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3223    // whichever happens first.  The timer is started by the first caller and not
3224    // restarted by subsequent callers.
3225    public void requestNetworkTransitionWakelock(String forWhom) {
3226        enforceConnectivityInternalPermission();
3227        synchronized (this) {
3228            if (mNetTransitionWakeLock.isHeld()) return;
3229            mNetTransitionWakeLockSerialNumber++;
3230            mNetTransitionWakeLock.acquire();
3231            mNetTransitionWakeLockCausedBy = forWhom;
3232        }
3233        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3234                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3235                mNetTransitionWakeLockSerialNumber, 0),
3236                mNetTransitionWakeLockTimeout);
3237        return;
3238    }
3239
3240    // 100 percent is full good, 0 is full bad.
3241    public void reportInetCondition(int networkType, int percentage) {
3242        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3243        mContext.enforceCallingOrSelfPermission(
3244                android.Manifest.permission.STATUS_BAR,
3245                "ConnectivityService");
3246
3247        if (DBG) {
3248            int pid = getCallingPid();
3249            int uid = getCallingUid();
3250            String s = pid + "(" + uid + ") reports inet is " +
3251                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3252                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3253            mInetLog.add(s);
3254            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3255                mInetLog.remove(0);
3256            }
3257        }
3258        mHandler.sendMessage(mHandler.obtainMessage(
3259            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3260    }
3261
3262    private void handleInetConditionChange(int netType, int condition) {
3263        if (mActiveDefaultNetwork == -1) {
3264            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3265            return;
3266        }
3267        if (mActiveDefaultNetwork != netType) {
3268            if (DBG) log("handleInetConditionChange: net=" + netType +
3269                            " != default=" + mActiveDefaultNetwork + " - ignore");
3270            return;
3271        }
3272        if (VDBG) {
3273            log("handleInetConditionChange: net=" +
3274                    netType + ", condition=" + condition +
3275                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3276        }
3277        mDefaultInetCondition = condition;
3278        int delay;
3279        if (mInetConditionChangeInFlight == false) {
3280            if (VDBG) log("handleInetConditionChange: starting a change hold");
3281            // setup a new hold to debounce this
3282            if (mDefaultInetCondition > 50) {
3283                delay = Settings.Global.getInt(mContext.getContentResolver(),
3284                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3285            } else {
3286                delay = Settings.Global.getInt(mContext.getContentResolver(),
3287                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3288            }
3289            mInetConditionChangeInFlight = true;
3290            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3291                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3292        } else {
3293            // we've set the new condition, when this hold ends that will get picked up
3294            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3295        }
3296    }
3297
3298    private void handleInetConditionHoldEnd(int netType, int sequence) {
3299        if (DBG) {
3300            log("handleInetConditionHoldEnd: net=" + netType +
3301                    ", condition=" + mDefaultInetCondition +
3302                    ", published condition=" + mDefaultInetConditionPublished);
3303        }
3304        mInetConditionChangeInFlight = false;
3305
3306        if (mActiveDefaultNetwork == -1) {
3307            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3308            return;
3309        }
3310        if (mDefaultConnectionSequence != sequence) {
3311            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3312            return;
3313        }
3314        // TODO: Figure out why this optimization sometimes causes a
3315        //       change in mDefaultInetCondition to be missed and the
3316        //       UI to not be updated.
3317        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3318        //    if (DBG) log("no change in condition - aborting");
3319        //    return;
3320        //}
3321        NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3322        if (networkInfo.isConnected() == false) {
3323            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3324            return;
3325        }
3326        mDefaultInetConditionPublished = mDefaultInetCondition;
3327        sendInetConditionBroadcast(networkInfo);
3328        return;
3329    }
3330
3331    public ProxyProperties getProxy() {
3332        // this information is already available as a world read/writable jvm property
3333        // so this API change wouldn't have a benifit.  It also breaks the passing
3334        // of proxy info to all the JVMs.
3335        // enforceAccessPermission();
3336        synchronized (mProxyLock) {
3337            ProxyProperties ret = mGlobalProxy;
3338            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3339            return ret;
3340        }
3341    }
3342
3343    public void setGlobalProxy(ProxyProperties proxyProperties) {
3344        enforceConnectivityInternalPermission();
3345
3346        synchronized (mProxyLock) {
3347            if (proxyProperties == mGlobalProxy) return;
3348            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3349            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3350
3351            String host = "";
3352            int port = 0;
3353            String exclList = "";
3354            String pacFileUrl = "";
3355            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3356                    !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
3357                if (!proxyProperties.isValid()) {
3358                    if (DBG)
3359                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3360                    return;
3361                }
3362                mGlobalProxy = new ProxyProperties(proxyProperties);
3363                host = mGlobalProxy.getHost();
3364                port = mGlobalProxy.getPort();
3365                exclList = mGlobalProxy.getExclusionList();
3366                if (proxyProperties.getPacFileUrl() != null) {
3367                    pacFileUrl = proxyProperties.getPacFileUrl();
3368                }
3369            } else {
3370                mGlobalProxy = null;
3371            }
3372            ContentResolver res = mContext.getContentResolver();
3373            final long token = Binder.clearCallingIdentity();
3374            try {
3375                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3376                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3377                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3378                        exclList);
3379                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3380            } finally {
3381                Binder.restoreCallingIdentity(token);
3382            }
3383        }
3384
3385        if (mGlobalProxy == null) {
3386            proxyProperties = mDefaultProxy;
3387        }
3388        sendProxyBroadcast(proxyProperties);
3389    }
3390
3391    private void loadGlobalProxy() {
3392        ContentResolver res = mContext.getContentResolver();
3393        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3394        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3395        String exclList = Settings.Global.getString(res,
3396                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3397        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3398        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3399            ProxyProperties proxyProperties;
3400            if (!TextUtils.isEmpty(pacFileUrl)) {
3401                proxyProperties = new ProxyProperties(pacFileUrl);
3402            } else {
3403                proxyProperties = new ProxyProperties(host, port, exclList);
3404            }
3405            if (!proxyProperties.isValid()) {
3406                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3407                return;
3408            }
3409
3410            synchronized (mProxyLock) {
3411                mGlobalProxy = proxyProperties;
3412            }
3413        }
3414    }
3415
3416    public ProxyProperties getGlobalProxy() {
3417        // this information is already available as a world read/writable jvm property
3418        // so this API change wouldn't have a benifit.  It also breaks the passing
3419        // of proxy info to all the JVMs.
3420        // enforceAccessPermission();
3421        synchronized (mProxyLock) {
3422            return mGlobalProxy;
3423        }
3424    }
3425
3426    private void handleApplyDefaultProxy(ProxyProperties proxy) {
3427        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3428                && TextUtils.isEmpty(proxy.getPacFileUrl())) {
3429            proxy = null;
3430        }
3431        synchronized (mProxyLock) {
3432            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3433            if (mDefaultProxy == proxy) return; // catches repeated nulls
3434            if (proxy != null &&  !proxy.isValid()) {
3435                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3436                return;
3437            }
3438            mDefaultProxy = proxy;
3439
3440            if (mGlobalProxy != null) return;
3441            if (!mDefaultProxyDisabled) {
3442                sendProxyBroadcast(proxy);
3443            }
3444        }
3445    }
3446
3447    private void handleDeprecatedGlobalHttpProxy() {
3448        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3449                Settings.Global.HTTP_PROXY);
3450        if (!TextUtils.isEmpty(proxy)) {
3451            String data[] = proxy.split(":");
3452            if (data.length == 0) {
3453                return;
3454            }
3455
3456            String proxyHost =  data[0];
3457            int proxyPort = 8080;
3458            if (data.length > 1) {
3459                try {
3460                    proxyPort = Integer.parseInt(data[1]);
3461                } catch (NumberFormatException e) {
3462                    return;
3463                }
3464            }
3465            ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3466            setGlobalProxy(p);
3467        }
3468    }
3469
3470    private void sendProxyBroadcast(ProxyProperties proxy) {
3471        if (proxy == null) proxy = new ProxyProperties("", 0, "");
3472        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3473        if (DBG) log("sending Proxy Broadcast for " + proxy);
3474        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3475        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3476            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3477        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3478        final long ident = Binder.clearCallingIdentity();
3479        try {
3480            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3481        } finally {
3482            Binder.restoreCallingIdentity(ident);
3483        }
3484    }
3485
3486    private static class SettingsObserver extends ContentObserver {
3487        private int mWhat;
3488        private Handler mHandler;
3489        SettingsObserver(Handler handler, int what) {
3490            super(handler);
3491            mHandler = handler;
3492            mWhat = what;
3493        }
3494
3495        void observe(Context context) {
3496            ContentResolver resolver = context.getContentResolver();
3497            resolver.registerContentObserver(Settings.Global.getUriFor(
3498                    Settings.Global.HTTP_PROXY), false, this);
3499        }
3500
3501        @Override
3502        public void onChange(boolean selfChange) {
3503            mHandler.obtainMessage(mWhat).sendToTarget();
3504        }
3505    }
3506
3507    private static void log(String s) {
3508        Slog.d(TAG, s);
3509    }
3510
3511    private static void loge(String s) {
3512        Slog.e(TAG, s);
3513    }
3514
3515    int convertFeatureToNetworkType(int networkType, String feature) {
3516        int usedNetworkType = networkType;
3517
3518        if(networkType == ConnectivityManager.TYPE_MOBILE) {
3519            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3520                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3521            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3522                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3523            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3524                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3525                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3526            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3527                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3528            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3529                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3530            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3531                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3532            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3533                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3534            } else {
3535                Slog.e(TAG, "Can't match any mobile netTracker!");
3536            }
3537        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3538            if (TextUtils.equals(feature, "p2p")) {
3539                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3540            } else {
3541                Slog.e(TAG, "Can't match any wifi netTracker!");
3542            }
3543        } else {
3544            Slog.e(TAG, "Unexpected network type");
3545        }
3546        return usedNetworkType;
3547    }
3548
3549    private static <T> T checkNotNull(T value, String message) {
3550        if (value == null) {
3551            throw new NullPointerException(message);
3552        }
3553        return value;
3554    }
3555
3556    /**
3557     * Protect a socket from VPN routing rules. This method is used by
3558     * VpnBuilder and not available in ConnectivityManager. Permissions
3559     * are checked in Vpn class.
3560     * @hide
3561     */
3562    @Override
3563    public boolean protectVpn(ParcelFileDescriptor socket) {
3564        throwIfLockdownEnabled();
3565        try {
3566            int type = mActiveDefaultNetwork;
3567            int user = UserHandle.getUserId(Binder.getCallingUid());
3568            if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3569                synchronized(mVpns) {
3570                    mVpns.get(user).protect(socket,
3571                            mNetTrackers[type].getLinkProperties().getInterfaceName());
3572                }
3573                return true;
3574            }
3575        } catch (Exception e) {
3576            // ignore
3577        } finally {
3578            try {
3579                socket.close();
3580            } catch (Exception e) {
3581                // ignore
3582            }
3583        }
3584        return false;
3585    }
3586
3587    /**
3588     * Prepare for a VPN application. This method is used by VpnDialogs
3589     * and not available in ConnectivityManager. Permissions are checked
3590     * in Vpn class.
3591     * @hide
3592     */
3593    @Override
3594    public boolean prepareVpn(String oldPackage, String newPackage) {
3595        throwIfLockdownEnabled();
3596        int user = UserHandle.getUserId(Binder.getCallingUid());
3597        synchronized(mVpns) {
3598            return mVpns.get(user).prepare(oldPackage, newPackage);
3599        }
3600    }
3601
3602    @Override
3603    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3604        enforceMarkNetworkSocketPermission();
3605        final long token = Binder.clearCallingIdentity();
3606        try {
3607            int mark = mNetd.getMarkForUid(uid);
3608            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3609            if (mark == -1) {
3610                mark = 0;
3611            }
3612            NetworkUtils.markSocket(socket.getFd(), mark);
3613        } catch (RemoteException e) {
3614        } finally {
3615            Binder.restoreCallingIdentity(token);
3616        }
3617    }
3618
3619    /**
3620     * Configure a TUN interface and return its file descriptor. Parameters
3621     * are encoded and opaque to this class. This method is used by VpnBuilder
3622     * and not available in ConnectivityManager. Permissions are checked in
3623     * Vpn class.
3624     * @hide
3625     */
3626    @Override
3627    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3628        throwIfLockdownEnabled();
3629        int user = UserHandle.getUserId(Binder.getCallingUid());
3630        synchronized(mVpns) {
3631            return mVpns.get(user).establish(config);
3632        }
3633    }
3634
3635    /**
3636     * Start legacy VPN, controlling native daemons as needed. Creates a
3637     * secondary thread to perform connection work, returning quickly.
3638     */
3639    @Override
3640    public void startLegacyVpn(VpnProfile profile) {
3641        throwIfLockdownEnabled();
3642        final LinkProperties egress = getActiveLinkProperties();
3643        if (egress == null) {
3644            throw new IllegalStateException("Missing active network connection");
3645        }
3646        int user = UserHandle.getUserId(Binder.getCallingUid());
3647        synchronized(mVpns) {
3648            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3649        }
3650    }
3651
3652    /**
3653     * Return the information of the ongoing legacy VPN. This method is used
3654     * by VpnSettings and not available in ConnectivityManager. Permissions
3655     * are checked in Vpn class.
3656     * @hide
3657     */
3658    @Override
3659    public LegacyVpnInfo getLegacyVpnInfo() {
3660        throwIfLockdownEnabled();
3661        int user = UserHandle.getUserId(Binder.getCallingUid());
3662        synchronized(mVpns) {
3663            return mVpns.get(user).getLegacyVpnInfo();
3664        }
3665    }
3666
3667    /**
3668     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3669     * not available in ConnectivityManager.
3670     * Permissions are checked in Vpn class.
3671     * @hide
3672     */
3673    @Override
3674    public VpnConfig getVpnConfig() {
3675        int user = UserHandle.getUserId(Binder.getCallingUid());
3676        synchronized(mVpns) {
3677            return mVpns.get(user).getVpnConfig();
3678        }
3679    }
3680
3681    /**
3682     * Callback for VPN subsystem. Currently VPN is not adapted to the service
3683     * through NetworkStateTracker since it works differently. For example, it
3684     * needs to override DNS servers but never takes the default routes. It
3685     * relies on another data network, and it could keep existing connections
3686     * alive after reconnecting, switching between networks, or even resuming
3687     * from deep sleep. Calls from applications should be done synchronously
3688     * to avoid race conditions. As these are all hidden APIs, refactoring can
3689     * be done whenever a better abstraction is developed.
3690     */
3691    public class VpnCallback {
3692        private VpnCallback() {
3693        }
3694
3695        public void onStateChanged(NetworkInfo info) {
3696            mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3697        }
3698
3699        public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
3700            if (dnsServers == null) {
3701                restore();
3702                return;
3703            }
3704
3705            // Convert DNS servers into addresses.
3706            List<InetAddress> addresses = new ArrayList<InetAddress>();
3707            for (String address : dnsServers) {
3708                // Double check the addresses and remove invalid ones.
3709                try {
3710                    addresses.add(InetAddress.parseNumericAddress(address));
3711                } catch (Exception e) {
3712                    // ignore
3713                }
3714            }
3715            if (addresses.isEmpty()) {
3716                restore();
3717                return;
3718            }
3719
3720            // Concatenate search domains into a string.
3721            StringBuilder buffer = new StringBuilder();
3722            if (searchDomains != null) {
3723                for (String domain : searchDomains) {
3724                    buffer.append(domain).append(' ');
3725                }
3726            }
3727            String domains = buffer.toString().trim();
3728
3729            // Apply DNS changes.
3730            synchronized (mDnsLock) {
3731                updateDnsLocked("VPN", iface, addresses, domains, false);
3732            }
3733
3734            // Temporarily disable the default proxy (not global).
3735            synchronized (mProxyLock) {
3736                mDefaultProxyDisabled = true;
3737                if (mGlobalProxy == null && mDefaultProxy != null) {
3738                    sendProxyBroadcast(null);
3739                }
3740            }
3741
3742            // TODO: support proxy per network.
3743        }
3744
3745        public void restore() {
3746            synchronized (mProxyLock) {
3747                mDefaultProxyDisabled = false;
3748                if (mGlobalProxy == null && mDefaultProxy != null) {
3749                    sendProxyBroadcast(mDefaultProxy);
3750                }
3751            }
3752        }
3753
3754        public void protect(ParcelFileDescriptor socket) {
3755            try {
3756                final int mark = mNetd.getMarkForProtect();
3757                NetworkUtils.markSocket(socket.getFd(), mark);
3758            } catch (RemoteException e) {
3759            }
3760        }
3761
3762        public void setRoutes(String interfaze, List<RouteInfo> routes) {
3763            for (RouteInfo route : routes) {
3764                try {
3765                    mNetd.setMarkedForwardingRoute(interfaze, route);
3766                } catch (RemoteException e) {
3767                }
3768            }
3769        }
3770
3771        public void setMarkedForwarding(String interfaze) {
3772            try {
3773                mNetd.setMarkedForwarding(interfaze);
3774            } catch (RemoteException e) {
3775            }
3776        }
3777
3778        public void clearMarkedForwarding(String interfaze) {
3779            try {
3780                mNetd.clearMarkedForwarding(interfaze);
3781            } catch (RemoteException e) {
3782            }
3783        }
3784
3785        public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
3786            int uidStart = uid * UserHandle.PER_USER_RANGE;
3787            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3788            addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
3789        }
3790
3791        public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
3792            int uidStart = uid * UserHandle.PER_USER_RANGE;
3793            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3794            clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
3795        }
3796
3797        public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3798                boolean forwardDns) {
3799            try {
3800                mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3801                if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3802            } catch (RemoteException e) {
3803            }
3804
3805        }
3806
3807        public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3808                boolean forwardDns) {
3809            try {
3810                mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3811                if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3812            } catch (RemoteException e) {
3813            }
3814
3815        }
3816    }
3817
3818    @Override
3819    public boolean updateLockdownVpn() {
3820        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3821            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3822            return false;
3823        }
3824
3825        // Tear down existing lockdown if profile was removed
3826        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3827        if (mLockdownEnabled) {
3828            if (!mKeyStore.isUnlocked()) {
3829                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3830                return false;
3831            }
3832
3833            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3834            final VpnProfile profile = VpnProfile.decode(
3835                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3836            int user = UserHandle.getUserId(Binder.getCallingUid());
3837            synchronized(mVpns) {
3838                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3839                            profile));
3840            }
3841        } else {
3842            setLockdownTracker(null);
3843        }
3844
3845        return true;
3846    }
3847
3848    /**
3849     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3850     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3851     */
3852    private void setLockdownTracker(LockdownVpnTracker tracker) {
3853        // Shutdown any existing tracker
3854        final LockdownVpnTracker existing = mLockdownTracker;
3855        mLockdownTracker = null;
3856        if (existing != null) {
3857            existing.shutdown();
3858        }
3859
3860        try {
3861            if (tracker != null) {
3862                mNetd.setFirewallEnabled(true);
3863                mNetd.setFirewallInterfaceRule("lo", true);
3864                mLockdownTracker = tracker;
3865                mLockdownTracker.init();
3866            } else {
3867                mNetd.setFirewallEnabled(false);
3868            }
3869        } catch (RemoteException e) {
3870            // ignored; NMS lives inside system_server
3871        }
3872    }
3873
3874    private void throwIfLockdownEnabled() {
3875        if (mLockdownEnabled) {
3876            throw new IllegalStateException("Unavailable in lockdown mode");
3877        }
3878    }
3879
3880    public void supplyMessenger(int networkType, Messenger messenger) {
3881        enforceConnectivityInternalPermission();
3882
3883        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3884            mNetTrackers[networkType].supplyMessenger(messenger);
3885        }
3886    }
3887
3888    public int findConnectionTypeForIface(String iface) {
3889        enforceConnectivityInternalPermission();
3890
3891        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3892        for (NetworkStateTracker tracker : mNetTrackers) {
3893            if (tracker != null) {
3894                LinkProperties lp = tracker.getLinkProperties();
3895                if (lp != null && iface.equals(lp.getInterfaceName())) {
3896                    return tracker.getNetworkInfo().getType();
3897                }
3898            }
3899        }
3900        return ConnectivityManager.TYPE_NONE;
3901    }
3902
3903    /**
3904     * Have mobile data fail fast if enabled.
3905     *
3906     * @param enabled DctConstants.ENABLED/DISABLED
3907     */
3908    private void setEnableFailFastMobileData(int enabled) {
3909        int tag;
3910
3911        if (enabled == DctConstants.ENABLED) {
3912            tag = mEnableFailFastMobileDataTag.incrementAndGet();
3913        } else {
3914            tag = mEnableFailFastMobileDataTag.get();
3915        }
3916        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3917                         enabled));
3918    }
3919
3920    private boolean isMobileDataStateTrackerReady() {
3921        MobileDataStateTracker mdst =
3922                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3923        return (mdst != null) && (mdst.isReady());
3924    }
3925
3926    /**
3927     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3928     */
3929
3930    /**
3931     * No connection was possible to the network.
3932     * This is NOT a warm sim.
3933     */
3934    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
3935
3936    /**
3937     * A connection was made to the internet, all is well.
3938     * This is NOT a warm sim.
3939     */
3940    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
3941
3942    /**
3943     * A connection was made but no dns server was available to resolve a name to address.
3944     * This is NOT a warm sim since provisioning network is supported.
3945     */
3946    private static final int CMP_RESULT_CODE_NO_DNS = 2;
3947
3948    /**
3949     * A connection was made but could not open a TCP connection.
3950     * This is NOT a warm sim since provisioning network is supported.
3951     */
3952    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3953
3954    /**
3955     * A connection was made but there was a redirection, we appear to be in walled garden.
3956     * This is an indication of a warm sim on a mobile network such as T-Mobile.
3957     */
3958    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
3959
3960    /**
3961     * The mobile network is a provisioning network.
3962     * This is an indication of a warm sim on a mobile network such as AT&T.
3963     */
3964    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
3965
3966    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
3967
3968    @Override
3969    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3970        int timeOutMs = -1;
3971        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3972        enforceConnectivityInternalPermission();
3973
3974        final long token = Binder.clearCallingIdentity();
3975        try {
3976            timeOutMs = suggestedTimeOutMs;
3977            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3978                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3979            }
3980
3981            // Check that mobile networks are supported
3982            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3983                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3984                if (DBG) log("checkMobileProvisioning: X no mobile network");
3985                return timeOutMs;
3986            }
3987
3988            // If we're already checking don't do it again
3989            // TODO: Add a queue of results...
3990            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3991                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3992                return timeOutMs;
3993            }
3994
3995            // Start off with mobile notification off
3996            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
3997
3998            CheckMp checkMp = new CheckMp(mContext, this);
3999            CheckMp.CallBack cb = new CheckMp.CallBack() {
4000                @Override
4001                void onComplete(Integer result) {
4002                    if (DBG) log("CheckMp.onComplete: result=" + result);
4003                    NetworkInfo ni =
4004                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4005                    switch(result) {
4006                        case CMP_RESULT_CODE_CONNECTABLE:
4007                        case CMP_RESULT_CODE_NO_CONNECTION:
4008                        case CMP_RESULT_CODE_NO_DNS:
4009                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4010                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4011                            break;
4012                        }
4013                        case CMP_RESULT_CODE_REDIRECTED: {
4014                            if (DBG) log("CheckMp.onComplete: warm sim");
4015                            String url = getMobileProvisioningUrl();
4016                            if (TextUtils.isEmpty(url)) {
4017                                url = getMobileRedirectedProvisioningUrl();
4018                            }
4019                            if (TextUtils.isEmpty(url) == false) {
4020                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4021                                setProvNotificationVisible(true,
4022                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4023                                        url);
4024                            } else {
4025                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4026                            }
4027                            break;
4028                        }
4029                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4030                            String url = getMobileProvisioningUrl();
4031                            if (TextUtils.isEmpty(url) == false) {
4032                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4033                                setProvNotificationVisible(true,
4034                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4035                                        url);
4036                            } else {
4037                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4038                            }
4039                            break;
4040                        }
4041                        default: {
4042                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4043                            break;
4044                        }
4045                    }
4046                    mIsCheckingMobileProvisioning.set(false);
4047                }
4048            };
4049            CheckMp.Params params =
4050                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4051            if (DBG) log("checkMobileProvisioning: params=" + params);
4052            checkMp.execute(params);
4053        } finally {
4054            Binder.restoreCallingIdentity(token);
4055            if (DBG) log("checkMobileProvisioning: X");
4056        }
4057        return timeOutMs;
4058    }
4059
4060    static class CheckMp extends
4061            AsyncTask<CheckMp.Params, Void, Integer> {
4062        private static final String CHECKMP_TAG = "CheckMp";
4063
4064        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4065        private static boolean mTestingFailures;
4066
4067        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4068        private static final int MAX_LOOPS = 4;
4069
4070        // Number of milli-seconds to complete all of the retires
4071        public static final int MAX_TIMEOUT_MS =  60000;
4072
4073        // The socket should retry only 5 seconds, the default is longer
4074        private static final int SOCKET_TIMEOUT_MS = 5000;
4075
4076        // Sleep time for network errors
4077        private static final int NET_ERROR_SLEEP_SEC = 3;
4078
4079        // Sleep time for network route establishment
4080        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4081
4082        // Short sleep time for polling :(
4083        private static final int POLLING_SLEEP_SEC = 1;
4084
4085        private Context mContext;
4086        private ConnectivityService mCs;
4087        private TelephonyManager mTm;
4088        private Params mParams;
4089
4090        /**
4091         * Parameters for AsyncTask.execute
4092         */
4093        static class Params {
4094            private String mUrl;
4095            private long mTimeOutMs;
4096            private CallBack mCb;
4097
4098            Params(String url, long timeOutMs, CallBack cb) {
4099                mUrl = url;
4100                mTimeOutMs = timeOutMs;
4101                mCb = cb;
4102            }
4103
4104            @Override
4105            public String toString() {
4106                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4107            }
4108        }
4109
4110        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4111        // issued by name or ip address, for Google its by name so when we construct
4112        // this HostnameVerifier we'll pass the original Uri and use it to verify
4113        // the host. If the host name in the original uril fails we'll test the
4114        // hostname parameter just incase things change.
4115        static class CheckMpHostnameVerifier implements HostnameVerifier {
4116            Uri mOrgUri;
4117
4118            CheckMpHostnameVerifier(Uri orgUri) {
4119                mOrgUri = orgUri;
4120            }
4121
4122            @Override
4123            public boolean verify(String hostname, SSLSession session) {
4124                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4125                String orgUriHost = mOrgUri.getHost();
4126                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4127                if (DBG) {
4128                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4129                        + " orgUriHost=" + orgUriHost);
4130                }
4131                return retVal;
4132            }
4133        }
4134
4135        /**
4136         * The call back object passed in Params. onComplete will be called
4137         * on the main thread.
4138         */
4139        abstract static class CallBack {
4140            // Called on the main thread.
4141            abstract void onComplete(Integer result);
4142        }
4143
4144        public CheckMp(Context context, ConnectivityService cs) {
4145            if (Build.IS_DEBUGGABLE) {
4146                mTestingFailures =
4147                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4148            } else {
4149                mTestingFailures = false;
4150            }
4151
4152            mContext = context;
4153            mCs = cs;
4154
4155            // Setup access to TelephonyService we'll be using.
4156            mTm = (TelephonyManager) mContext.getSystemService(
4157                    Context.TELEPHONY_SERVICE);
4158        }
4159
4160        /**
4161         * Get the default url to use for the test.
4162         */
4163        public String getDefaultUrl() {
4164            // See http://go/clientsdns for usage approval
4165            String server = Settings.Global.getString(mContext.getContentResolver(),
4166                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4167            if (server == null) {
4168                server = "clients3.google.com";
4169            }
4170            return "http://" + server + "/generate_204";
4171        }
4172
4173        /**
4174         * Detect if its possible to connect to the http url. DNS based detection techniques
4175         * do not work at all hotspots. The best way to check is to perform a request to
4176         * a known address that fetches the data we expect.
4177         */
4178        private synchronized Integer isMobileOk(Params params) {
4179            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4180            Uri orgUri = Uri.parse(params.mUrl);
4181            Random rand = new Random();
4182            mParams = params;
4183
4184            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4185                result = CMP_RESULT_CODE_NO_CONNECTION;
4186                log("isMobileOk: X not mobile capable result=" + result);
4187                return result;
4188            }
4189
4190            // See if we've already determined we've got a provisioning connection,
4191            // if so we don't need to do anything active.
4192            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4193                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4194            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4195            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4196
4197            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4198                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4199            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4200            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4201
4202            if (isDefaultProvisioning || isHipriProvisioning) {
4203                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4204                log("isMobileOk: X default || hipri is provisioning result=" + result);
4205                return result;
4206            }
4207
4208            try {
4209                // Continue trying to connect until time has run out
4210                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4211
4212                if (!mCs.isMobileDataStateTrackerReady()) {
4213                    // Wait for MobileDataStateTracker to be ready.
4214                    if (DBG) log("isMobileOk: mdst is not ready");
4215                    while(SystemClock.elapsedRealtime() < endTime) {
4216                        if (mCs.isMobileDataStateTrackerReady()) {
4217                            // Enable fail fast as we'll do retries here and use a
4218                            // hipri connection so the default connection stays active.
4219                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4220                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4221                            break;
4222                        }
4223                        sleep(POLLING_SLEEP_SEC);
4224                    }
4225                }
4226
4227                log("isMobileOk: start hipri url=" + params.mUrl);
4228
4229                // First wait until we can start using hipri
4230                Binder binder = new Binder();
4231                while(SystemClock.elapsedRealtime() < endTime) {
4232                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4233                            Phone.FEATURE_ENABLE_HIPRI, binder);
4234                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4235                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4236                            log("isMobileOk: hipri started");
4237                            break;
4238                    }
4239                    if (VDBG) log("isMobileOk: hipri not started yet");
4240                    result = CMP_RESULT_CODE_NO_CONNECTION;
4241                    sleep(POLLING_SLEEP_SEC);
4242                }
4243
4244                // Continue trying to connect until time has run out
4245                while(SystemClock.elapsedRealtime() < endTime) {
4246                    try {
4247                        // Wait for hipri to connect.
4248                        // TODO: Don't poll and handle situation where hipri fails
4249                        // because default is retrying. See b/9569540
4250                        NetworkInfo.State state = mCs
4251                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4252                        if (state != NetworkInfo.State.CONNECTED) {
4253                            if (true/*VDBG*/) {
4254                                log("isMobileOk: not connected ni=" +
4255                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4256                            }
4257                            sleep(POLLING_SLEEP_SEC);
4258                            result = CMP_RESULT_CODE_NO_CONNECTION;
4259                            continue;
4260                        }
4261
4262                        // Hipri has started check if this is a provisioning url
4263                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4264                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4265                        if (mdst.isProvisioningNetwork()) {
4266                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4267                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4268                            return result;
4269                        } else {
4270                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4271                        }
4272
4273                        // Get of the addresses associated with the url host. We need to use the
4274                        // address otherwise HttpURLConnection object will use the name to get
4275                        // the addresses and will try every address but that will bypass the
4276                        // route to host we setup and the connection could succeed as the default
4277                        // interface might be connected to the internet via wifi or other interface.
4278                        InetAddress[] addresses;
4279                        try {
4280                            addresses = InetAddress.getAllByName(orgUri.getHost());
4281                        } catch (UnknownHostException e) {
4282                            result = CMP_RESULT_CODE_NO_DNS;
4283                            log("isMobileOk: X UnknownHostException result=" + result);
4284                            return result;
4285                        }
4286                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4287
4288                        // Get the type of addresses supported by this link
4289                        LinkProperties lp = mCs.getLinkProperties(
4290                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4291                        boolean linkHasIpv4 = lp.hasIPv4Address();
4292                        boolean linkHasIpv6 = lp.hasIPv6Address();
4293                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4294                                + " linkHasIpv6=" + linkHasIpv6);
4295
4296                        final ArrayList<InetAddress> validAddresses =
4297                                new ArrayList<InetAddress>(addresses.length);
4298
4299                        for (InetAddress addr : addresses) {
4300                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4301                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4302                                validAddresses.add(addr);
4303                            }
4304                        }
4305
4306                        if (validAddresses.size() == 0) {
4307                            return CMP_RESULT_CODE_NO_CONNECTION;
4308                        }
4309
4310                        int addrTried = 0;
4311                        while (true) {
4312                            // Loop through at most MAX_LOOPS valid addresses or until
4313                            // we run out of time
4314                            if (addrTried++ >= MAX_LOOPS) {
4315                                log("isMobileOk: too many loops tried - giving up");
4316                                break;
4317                            }
4318                            if (SystemClock.elapsedRealtime() >= endTime) {
4319                                log("isMobileOk: spend too much time - giving up");
4320                                break;
4321                            }
4322
4323                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4324                                    validAddresses.size()));
4325
4326                            // Make a route to host so we check the specific interface.
4327                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4328                                    hostAddr.getAddress())) {
4329                                // Wait a short time to be sure the route is established ??
4330                                log("isMobileOk:"
4331                                        + " wait to establish route to hostAddr=" + hostAddr);
4332                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4333                            } else {
4334                                log("isMobileOk:"
4335                                        + " could not establish route to hostAddr=" + hostAddr);
4336                                // Wait a short time before the next attempt
4337                                sleep(NET_ERROR_SLEEP_SEC);
4338                                continue;
4339                            }
4340
4341                            // Rewrite the url to have numeric address to use the specific route
4342                            // using http for half the attempts and https for the other half.
4343                            // Doing https first and http second as on a redirected walled garden
4344                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4345                            // handshake timed out" which we declare as
4346                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4347                            // having http second we will be using logic used for some time.
4348                            URL newUrl;
4349                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4350                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4351                                        orgUri.getPath());
4352                            log("isMobileOk: newUrl=" + newUrl);
4353
4354                            HttpURLConnection urlConn = null;
4355                            try {
4356                                // Open the connection set the request headers and get the response
4357                                urlConn = (HttpURLConnection)newUrl.openConnection(
4358                                        java.net.Proxy.NO_PROXY);
4359                                if (scheme.equals("https")) {
4360                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4361                                            new CheckMpHostnameVerifier(orgUri));
4362                                }
4363                                urlConn.setInstanceFollowRedirects(false);
4364                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4365                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4366                                urlConn.setUseCaches(false);
4367                                urlConn.setAllowUserInteraction(false);
4368                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4369                                // is used which is useless in this case.
4370                                urlConn.setRequestProperty("Connection", "close");
4371                                int responseCode = urlConn.getResponseCode();
4372
4373                                // For debug display the headers
4374                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4375                                log("isMobileOk: headers=" + headers);
4376
4377                                // Close the connection
4378                                urlConn.disconnect();
4379                                urlConn = null;
4380
4381                                if (mTestingFailures) {
4382                                    // Pretend no connection, this tests using http and https
4383                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4384                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4385                                    continue;
4386                                }
4387
4388                                if (responseCode == 204) {
4389                                    // Return
4390                                    result = CMP_RESULT_CODE_CONNECTABLE;
4391                                    log("isMobileOk: X got expected responseCode=" + responseCode
4392                                            + " result=" + result);
4393                                    return result;
4394                                } else {
4395                                    // Retry to be sure this was redirected, we've gotten
4396                                    // occasions where a server returned 200 even though
4397                                    // the device didn't have a "warm" sim.
4398                                    log("isMobileOk: not expected responseCode=" + responseCode);
4399                                    // TODO - it would be nice in the single-address case to do
4400                                    // another DNS resolve here, but flushing the cache is a bit
4401                                    // heavy-handed.
4402                                    result = CMP_RESULT_CODE_REDIRECTED;
4403                                }
4404                            } catch (Exception e) {
4405                                log("isMobileOk: HttpURLConnection Exception" + e);
4406                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4407                                if (urlConn != null) {
4408                                    urlConn.disconnect();
4409                                    urlConn = null;
4410                                }
4411                                sleep(NET_ERROR_SLEEP_SEC);
4412                                continue;
4413                            }
4414                        }
4415                        log("isMobileOk: X loops|timed out result=" + result);
4416                        return result;
4417                    } catch (Exception e) {
4418                        log("isMobileOk: Exception e=" + e);
4419                        continue;
4420                    }
4421                }
4422                log("isMobileOk: timed out");
4423            } finally {
4424                log("isMobileOk: F stop hipri");
4425                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4426                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4427                        Phone.FEATURE_ENABLE_HIPRI);
4428
4429                // Wait for hipri to disconnect.
4430                long endTime = SystemClock.elapsedRealtime() + 5000;
4431
4432                while(SystemClock.elapsedRealtime() < endTime) {
4433                    NetworkInfo.State state = mCs
4434                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4435                    if (state != NetworkInfo.State.DISCONNECTED) {
4436                        if (VDBG) {
4437                            log("isMobileOk: connected ni=" +
4438                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4439                        }
4440                        sleep(POLLING_SLEEP_SEC);
4441                        continue;
4442                    }
4443                }
4444
4445                log("isMobileOk: X result=" + result);
4446            }
4447            return result;
4448        }
4449
4450        @Override
4451        protected Integer doInBackground(Params... params) {
4452            return isMobileOk(params[0]);
4453        }
4454
4455        @Override
4456        protected void onPostExecute(Integer result) {
4457            log("onPostExecute: result=" + result);
4458            if ((mParams != null) && (mParams.mCb != null)) {
4459                mParams.mCb.onComplete(result);
4460            }
4461        }
4462
4463        private String inetAddressesToString(InetAddress[] addresses) {
4464            StringBuffer sb = new StringBuffer();
4465            boolean firstTime = true;
4466            for(InetAddress addr : addresses) {
4467                if (firstTime) {
4468                    firstTime = false;
4469                } else {
4470                    sb.append(",");
4471                }
4472                sb.append(addr);
4473            }
4474            return sb.toString();
4475        }
4476
4477        private void printNetworkInfo() {
4478            boolean hasIccCard = mTm.hasIccCard();
4479            int simState = mTm.getSimState();
4480            log("hasIccCard=" + hasIccCard
4481                    + " simState=" + simState);
4482            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4483            if (ni != null) {
4484                log("ni.length=" + ni.length);
4485                for (NetworkInfo netInfo: ni) {
4486                    log("netInfo=" + netInfo.toString());
4487                }
4488            } else {
4489                log("no network info ni=null");
4490            }
4491        }
4492
4493        /**
4494         * Sleep for a few seconds then return.
4495         * @param seconds
4496         */
4497        private static void sleep(int seconds) {
4498            log("XXXXX sleeping for " + seconds + " sec");
4499            long stopTime = System.nanoTime() + (seconds * 1000000000);
4500            long sleepTime;
4501            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
4502                try {
4503                    Thread.sleep(sleepTime / 1000000);
4504                } catch (InterruptedException ignored) {
4505                }
4506            }
4507            log("XXXXX returning from sleep");
4508        }
4509
4510        private static void log(String s) {
4511            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4512        }
4513    }
4514
4515    // TODO: Move to ConnectivityManager and make public?
4516    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4517            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4518
4519    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4520        @Override
4521        public void onReceive(Context context, Intent intent) {
4522            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4523                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4524            }
4525        }
4526    };
4527
4528    private void handleMobileProvisioningAction(String url) {
4529        // Notication mark notification as not visible
4530        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4531
4532        // If provisioning network handle as a special case,
4533        // otherwise launch browser with the intent directly.
4534        NetworkInfo ni = getProvisioningNetworkInfo();
4535        if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
4536            if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4537            MobileDataStateTracker mdst = (MobileDataStateTracker)
4538                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4539            mdst.enableMobileProvisioning(url);
4540        } else {
4541            if (DBG) log("handleMobileProvisioningAction: on default network");
4542            // Check for  apps that can handle provisioning first
4543            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4544            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4545                    + mTelephonyManager.getSimOperator());
4546            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4547                    != null) {
4548                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4549                        Intent.FLAG_ACTIVITY_NEW_TASK);
4550                mContext.startActivity(provisioningIntent);
4551            } else {
4552                // If no apps exist, use standard URL ACTION_VIEW method
4553                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4554                        Intent.CATEGORY_APP_BROWSER);
4555                newIntent.setData(Uri.parse(url));
4556                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4557                        Intent.FLAG_ACTIVITY_NEW_TASK);
4558                try {
4559                    mContext.startActivity(newIntent);
4560                } catch (ActivityNotFoundException e) {
4561                    loge("handleMobileProvisioningAction: startActivity failed" + e);
4562                }
4563            }
4564        }
4565    }
4566
4567    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4568    private volatile boolean mIsNotificationVisible = false;
4569
4570    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4571            String url) {
4572        if (DBG) {
4573            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4574                + " extraInfo=" + extraInfo + " url=" + url);
4575        }
4576
4577        Resources r = Resources.getSystem();
4578        NotificationManager notificationManager = (NotificationManager) mContext
4579            .getSystemService(Context.NOTIFICATION_SERVICE);
4580
4581        if (visible) {
4582            CharSequence title;
4583            CharSequence details;
4584            int icon;
4585            Intent intent;
4586            Notification notification = new Notification();
4587            switch (networkType) {
4588                case ConnectivityManager.TYPE_WIFI:
4589                    title = r.getString(R.string.wifi_available_sign_in, 0);
4590                    details = r.getString(R.string.network_available_sign_in_detailed,
4591                            extraInfo);
4592                    icon = R.drawable.stat_notify_wifi_in_range;
4593                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4594                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4595                            Intent.FLAG_ACTIVITY_NEW_TASK);
4596                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4597                    break;
4598                case ConnectivityManager.TYPE_MOBILE:
4599                case ConnectivityManager.TYPE_MOBILE_HIPRI:
4600                    title = r.getString(R.string.network_available_sign_in, 0);
4601                    // TODO: Change this to pull from NetworkInfo once a printable
4602                    // name has been added to it
4603                    details = mTelephonyManager.getNetworkOperatorName();
4604                    icon = R.drawable.stat_notify_rssi_in_range;
4605                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4606                    intent.putExtra("EXTRA_URL", url);
4607                    intent.setFlags(0);
4608                    notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
4609                    break;
4610                default:
4611                    title = r.getString(R.string.network_available_sign_in, 0);
4612                    details = r.getString(R.string.network_available_sign_in_detailed,
4613                            extraInfo);
4614                    icon = R.drawable.stat_notify_rssi_in_range;
4615                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4616                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4617                            Intent.FLAG_ACTIVITY_NEW_TASK);
4618                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4619                    break;
4620            }
4621
4622            notification.when = 0;
4623            notification.icon = icon;
4624            notification.flags = Notification.FLAG_AUTO_CANCEL;
4625            notification.tickerText = title;
4626            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4627
4628            try {
4629                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
4630            } catch (NullPointerException npe) {
4631                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4632                npe.printStackTrace();
4633            }
4634        } else {
4635            try {
4636                notificationManager.cancel(NOTIFICATION_ID, networkType);
4637            } catch (NullPointerException npe) {
4638                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4639                npe.printStackTrace();
4640            }
4641        }
4642        mIsNotificationVisible = visible;
4643    }
4644
4645    /** Location to an updatable file listing carrier provisioning urls.
4646     *  An example:
4647     *
4648     * <?xml version="1.0" encoding="utf-8"?>
4649     *  <provisioningUrls>
4650     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
4651     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4652     *  </provisioningUrls>
4653     */
4654    private static final String PROVISIONING_URL_PATH =
4655            "/data/misc/radio/provisioning_urls.xml";
4656    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4657
4658    /** XML tag for root element. */
4659    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4660    /** XML tag for individual url */
4661    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4662    /** XML tag for redirected url */
4663    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4664    /** XML attribute for mcc */
4665    private static final String ATTR_MCC = "mcc";
4666    /** XML attribute for mnc */
4667    private static final String ATTR_MNC = "mnc";
4668
4669    private static final int REDIRECTED_PROVISIONING = 1;
4670    private static final int PROVISIONING = 2;
4671
4672    private String getProvisioningUrlBaseFromFile(int type) {
4673        FileReader fileReader = null;
4674        XmlPullParser parser = null;
4675        Configuration config = mContext.getResources().getConfiguration();
4676        String tagType;
4677
4678        switch (type) {
4679            case PROVISIONING:
4680                tagType = TAG_PROVISIONING_URL;
4681                break;
4682            case REDIRECTED_PROVISIONING:
4683                tagType = TAG_REDIRECTED_URL;
4684                break;
4685            default:
4686                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4687                        type);
4688        }
4689
4690        try {
4691            fileReader = new FileReader(mProvisioningUrlFile);
4692            parser = Xml.newPullParser();
4693            parser.setInput(fileReader);
4694            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4695
4696            while (true) {
4697                XmlUtils.nextElement(parser);
4698
4699                String element = parser.getName();
4700                if (element == null) break;
4701
4702                if (element.equals(tagType)) {
4703                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
4704                    try {
4705                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4706                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
4707                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4708                                parser.next();
4709                                if (parser.getEventType() == XmlPullParser.TEXT) {
4710                                    return parser.getText();
4711                                }
4712                            }
4713                        }
4714                    } catch (NumberFormatException e) {
4715                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4716                    }
4717                }
4718            }
4719            return null;
4720        } catch (FileNotFoundException e) {
4721            loge("Carrier Provisioning Urls file not found");
4722        } catch (XmlPullParserException e) {
4723            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4724        } catch (IOException e) {
4725            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4726        } finally {
4727            if (fileReader != null) {
4728                try {
4729                    fileReader.close();
4730                } catch (IOException e) {}
4731            }
4732        }
4733        return null;
4734    }
4735
4736    @Override
4737    public String getMobileRedirectedProvisioningUrl() {
4738        enforceConnectivityInternalPermission();
4739        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4740        if (TextUtils.isEmpty(url)) {
4741            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4742        }
4743        return url;
4744    }
4745
4746    @Override
4747    public String getMobileProvisioningUrl() {
4748        enforceConnectivityInternalPermission();
4749        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4750        if (TextUtils.isEmpty(url)) {
4751            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4752            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
4753        } else {
4754            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
4755        }
4756        // populate the iccid, imei and phone number in the provisioning url.
4757        if (!TextUtils.isEmpty(url)) {
4758            String phoneNumber = mTelephonyManager.getLine1Number();
4759            if (TextUtils.isEmpty(phoneNumber)) {
4760                phoneNumber = "0000000000";
4761            }
4762            url = String.format(url,
4763                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
4764                    mTelephonyManager.getDeviceId() /* IMEI */,
4765                    phoneNumber /* Phone numer */);
4766        }
4767
4768        return url;
4769    }
4770
4771    @Override
4772    public void setProvisioningNotificationVisible(boolean visible, int networkType,
4773            String extraInfo, String url) {
4774        enforceConnectivityInternalPermission();
4775        setProvNotificationVisible(visible, networkType, extraInfo, url);
4776    }
4777
4778    @Override
4779    public void setAirplaneMode(boolean enable) {
4780        enforceConnectivityInternalPermission();
4781        final long ident = Binder.clearCallingIdentity();
4782        try {
4783            final ContentResolver cr = mContext.getContentResolver();
4784            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4785            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4786            intent.putExtra("state", enable);
4787            mContext.sendBroadcast(intent);
4788        } finally {
4789            Binder.restoreCallingIdentity(ident);
4790        }
4791    }
4792
4793    private void onUserStart(int userId) {
4794        synchronized(mVpns) {
4795            Vpn userVpn = mVpns.get(userId);
4796            if (userVpn != null) {
4797                loge("Starting user already has a VPN");
4798                return;
4799            }
4800            userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4801            mVpns.put(userId, userVpn);
4802            userVpn.startMonitoring(mContext, mTrackerHandler);
4803        }
4804    }
4805
4806    private void onUserStop(int userId) {
4807        synchronized(mVpns) {
4808            Vpn userVpn = mVpns.get(userId);
4809            if (userVpn == null) {
4810                loge("Stopping user has no VPN");
4811                return;
4812            }
4813            mVpns.delete(userId);
4814        }
4815    }
4816
4817    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4818        @Override
4819        public void onReceive(Context context, Intent intent) {
4820            final String action = intent.getAction();
4821            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4822            if (userId == UserHandle.USER_NULL) return;
4823
4824            if (Intent.ACTION_USER_STARTING.equals(action)) {
4825                onUserStart(userId);
4826            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4827                onUserStop(userId);
4828            }
4829        }
4830    };
4831
4832    @Override
4833    public LinkQualityInfo getLinkQualityInfo(int networkType) {
4834        enforceAccessPermission();
4835        if (isNetworkTypeValid(networkType)) {
4836            return mNetTrackers[networkType].getLinkQualityInfo();
4837        } else {
4838            return null;
4839        }
4840    }
4841
4842    @Override
4843    public LinkQualityInfo getActiveLinkQualityInfo() {
4844        enforceAccessPermission();
4845        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
4846            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
4847        } else {
4848            return null;
4849        }
4850    }
4851
4852    @Override
4853    public LinkQualityInfo[] getAllLinkQualityInfo() {
4854        enforceAccessPermission();
4855        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
4856        for (NetworkStateTracker tracker : mNetTrackers) {
4857            if (tracker != null) {
4858                LinkQualityInfo li = tracker.getLinkQualityInfo();
4859                if (li != null) {
4860                    result.add(li);
4861                }
4862            }
4863        }
4864
4865        return result.toArray(new LinkQualityInfo[result.size()]);
4866    }
4867
4868    /* Infrastructure for network sampling */
4869
4870    private void handleNetworkSamplingTimeout() {
4871
4872        log("Sampling interval elapsed, updating statistics ..");
4873
4874        // initialize list of interfaces ..
4875        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4876                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4877        for (NetworkStateTracker tracker : mNetTrackers) {
4878            if (tracker != null) {
4879                String ifaceName = tracker.getNetworkInterfaceName();
4880                if (ifaceName != null) {
4881                    mapIfaceToSample.put(ifaceName, null);
4882                }
4883            }
4884        }
4885
4886        // Read samples for all interfaces
4887        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4888
4889        // process samples for all networks
4890        for (NetworkStateTracker tracker : mNetTrackers) {
4891            if (tracker != null) {
4892                String ifaceName = tracker.getNetworkInterfaceName();
4893                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4894                if (ss != null) {
4895                    // end the previous sampling cycle
4896                    tracker.stopSampling(ss);
4897                    // start a new sampling cycle ..
4898                    tracker.startSampling(ss);
4899                }
4900            }
4901        }
4902
4903        log("Done.");
4904
4905        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4906                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4907                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4908
4909        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4910
4911        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4912    }
4913
4914    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4915        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4916        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4917    }
4918}
4919