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