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