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