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