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