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