ConnectivityService.java revision 64d6ce8a661fd63b90b4c9f3f7d400208cb2430a
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.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.NETID_UNSET;
22import static android.net.ConnectivityManager.TYPE_NONE;
23import static android.net.ConnectivityManager.TYPE_VPN;
24import static android.net.ConnectivityManager.getNetworkTypeName;
25import static android.net.ConnectivityManager.isNetworkTypeValid;
26import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
30import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
31import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
32import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
33
34import android.annotation.Nullable;
35import android.app.AlarmManager;
36import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
39import android.content.BroadcastReceiver;
40import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.pm.PackageManager;
45import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.ContentObserver;
48import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
50import android.net.INetworkManagementEventObserver;
51import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
53import android.net.INetworkStatsService;
54import android.net.LinkProperties;
55import android.net.LinkProperties.CompareResult;
56import android.net.Network;
57import android.net.NetworkAgent;
58import android.net.NetworkCapabilities;
59import android.net.NetworkConfig;
60import android.net.NetworkInfo;
61import android.net.NetworkInfo.DetailedState;
62import android.net.NetworkMisc;
63import android.net.NetworkQuotaInfo;
64import android.net.NetworkRequest;
65import android.net.NetworkState;
66import android.net.NetworkUtils;
67import android.net.Proxy;
68import android.net.ProxyInfo;
69import android.net.RouteInfo;
70import android.net.UidRange;
71import android.net.Uri;
72import android.os.Binder;
73import android.os.Bundle;
74import android.os.FileUtils;
75import android.os.Handler;
76import android.os.HandlerThread;
77import android.os.IBinder;
78import android.os.INetworkManagementService;
79import android.os.Looper;
80import android.os.Message;
81import android.os.Messenger;
82import android.os.ParcelFileDescriptor;
83import android.os.PowerManager;
84import android.os.Process;
85import android.os.RemoteException;
86import android.os.SystemClock;
87import android.os.SystemProperties;
88import android.os.UserHandle;
89import android.os.UserManager;
90import android.provider.Settings;
91import android.security.Credentials;
92import android.security.KeyStore;
93import android.telephony.TelephonyManager;
94import android.text.TextUtils;
95import android.util.Slog;
96import android.util.SparseArray;
97import android.util.SparseBooleanArray;
98import android.util.SparseIntArray;
99import android.util.Xml;
100
101import com.android.internal.R;
102import com.android.internal.annotations.GuardedBy;
103import com.android.internal.app.IBatteryStats;
104import com.android.internal.net.LegacyVpnInfo;
105import com.android.internal.net.NetworkStatsFactory;
106import com.android.internal.net.VpnConfig;
107import com.android.internal.net.VpnInfo;
108import com.android.internal.net.VpnProfile;
109import com.android.internal.telephony.DctConstants;
110import com.android.internal.util.AsyncChannel;
111import com.android.internal.util.IndentingPrintWriter;
112import com.android.internal.util.XmlUtils;
113import com.android.server.am.BatteryStatsService;
114import com.android.server.connectivity.DataConnectionStats;
115import com.android.server.connectivity.NetworkDiagnostics;
116import com.android.server.connectivity.Nat464Xlat;
117import com.android.server.connectivity.NetworkAgentInfo;
118import com.android.server.connectivity.NetworkMonitor;
119import com.android.server.connectivity.PacManager;
120import com.android.server.connectivity.PermissionMonitor;
121import com.android.server.connectivity.Tethering;
122import com.android.server.connectivity.Vpn;
123import com.android.server.net.BaseNetworkObserver;
124import com.android.server.net.LockdownVpnTracker;
125import com.google.android.collect.Lists;
126import com.google.android.collect.Sets;
127
128import org.xmlpull.v1.XmlPullParser;
129import org.xmlpull.v1.XmlPullParserException;
130
131import java.io.File;
132import java.io.FileDescriptor;
133import java.io.FileNotFoundException;
134import java.io.FileReader;
135import java.io.IOException;
136import java.io.PrintWriter;
137import java.net.Inet4Address;
138import java.net.InetAddress;
139import java.net.UnknownHostException;
140import java.util.ArrayList;
141import java.util.Arrays;
142import java.util.Collection;
143import java.util.HashMap;
144import java.util.HashSet;
145import java.util.Iterator;
146import java.util.List;
147import java.util.Map;
148import java.util.Objects;
149import java.util.concurrent.atomic.AtomicInteger;
150
151/**
152 * @hide
153 */
154public class ConnectivityService extends IConnectivityManager.Stub
155        implements PendingIntent.OnFinished {
156    private static final String TAG = "ConnectivityService";
157
158    private static final boolean DBG = true;
159    private static final boolean VDBG = false;
160
161    private static final boolean LOGD_RULES = false;
162
163    // TODO: create better separation between radio types and network types
164
165    // how long to wait before switching back to a radio's default network
166    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
167    // system property that can override the above value
168    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
169            "android.telephony.apn-restore";
170
171    // How long to wait before putting up a "This network doesn't have an Internet connection,
172    // connect anyway?" dialog after the user selects a network that doesn't validate.
173    private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
174
175    // How long to delay to removal of a pending intent based request.
176    // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
177    private final int mReleasePendingIntentDelayMs;
178
179    private Tethering mTethering;
180
181    private final PermissionMonitor mPermissionMonitor;
182
183    private KeyStore mKeyStore;
184
185    @GuardedBy("mVpns")
186    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
187
188    private boolean mLockdownEnabled;
189    private LockdownVpnTracker mLockdownTracker;
190
191    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
192    private Object mRulesLock = new Object();
193    /** Currently active network rules by UID. */
194    private SparseIntArray mUidRules = new SparseIntArray();
195    /** Set of ifaces that are costly. */
196    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
197
198    final private Context mContext;
199    private int mNetworkPreference;
200    // 0 is full bad, 100 is full good
201    private int mDefaultInetConditionPublished = 0;
202
203    private int mNumDnsEntries;
204
205    private boolean mTestMode;
206    private static ConnectivityService sServiceInstance;
207
208    private INetworkManagementService mNetd;
209    private INetworkStatsService mStatsService;
210    private INetworkPolicyManager mPolicyManager;
211
212    private String mCurrentTcpBufferSizes;
213
214    private static final int ENABLED  = 1;
215    private static final int DISABLED = 0;
216
217    // Arguments to rematchNetworkAndRequests()
218    private enum NascentState {
219        // Indicates a network was just validated for the first time.  If the network is found to
220        // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
221        JUST_VALIDATED,
222        // Indicates a network was not validated for the first time immediately prior to this call.
223        NOT_JUST_VALIDATED
224    };
225    private enum ReapUnvalidatedNetworks {
226        // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
227        // the highest scoring network satisfying a NetworkRequest.  This should be passed when it's
228        // known that there may be unvalidated networks that could potentially be reaped, and when
229        // all networks have been rematched against all NetworkRequests.
230        REAP,
231        // Don't reap unvalidated networks.  This should be passed when it's known that there are
232        // no unvalidated networks that could potentially be reaped, and when some networks have
233        // not yet been rematched against all NetworkRequests.
234        DONT_REAP
235    };
236
237    /**
238     * used internally to change our mobile data enabled flag
239     */
240    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
241
242    /**
243     * used internally to clear a wakelock when transitioning
244     * from one net to another.  Clear happens when we get a new
245     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246     * after a timeout if no network is found (typically 1 min).
247     */
248    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
249
250    /**
251     * used internally to reload global proxy settings
252     */
253    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
254
255    /**
256     * used internally to send a sticky broadcast delayed.
257     */
258    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
259
260    /**
261     * PAC manager has received new port.
262     */
263    private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
265    /**
266     * used internally when registering NetworkFactories
267     * obj = NetworkFactoryInfo
268     */
269    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
271    /**
272     * used internally when registering NetworkAgents
273     * obj = Messenger
274     */
275    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
277    /**
278     * used to add a network request
279     * includes a NetworkRequestInfo
280     */
281    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283    /**
284     * indicates a timeout period is over - check if we had a network yet or not
285     * and if not, call the timeout calback (but leave the request live until they
286     * cancel it.
287     * includes a NetworkRequestInfo
288     */
289    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291    /**
292     * used to add a network listener - no request
293     * includes a NetworkRequestInfo
294     */
295    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297    /**
298     * used to remove a network request, either a listener or a real request
299     * arg1 = UID of caller
300     * obj  = NetworkRequest
301     */
302    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
304    /**
305     * used internally when registering NetworkFactories
306     * obj = Messenger
307     */
308    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
310    /**
311     * used internally to expire a wakelock when transitioning
312     * from one net to another.  Expire happens when we fail to find
313     * a new network (typically after 1 minute) -
314     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315     * a replacement network.
316     */
317    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
319    /**
320     * Used internally to indicate the system is ready.
321     */
322    private static final int EVENT_SYSTEM_READY = 25;
323
324    /**
325     * used to add a network request with a pending intent
326     * includes a NetworkRequestInfo
327     */
328    private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330    /**
331     * used to remove a pending intent and its associated network request.
332     * arg1 = UID of caller
333     * obj  = PendingIntent
334     */
335    private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
337    /**
338     * used to specify whether a network should be used even if unvalidated.
339     * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340     * arg2 = whether to remember this choice in the future (1 or 0)
341     * obj  = network
342     */
343    private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345    /**
346     * used to ask the user to confirm a connection to an unvalidated network.
347     * obj  = network
348     */
349    private static final int EVENT_PROMPT_UNVALIDATED = 29;
350
351    /**
352     * used internally to (re)configure mobile data always-on settings.
353     */
354    private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
356    /** Handler used for internal events. */
357    final private InternalHandler mHandler;
358    /** Handler used for incoming {@link NetworkStateTracker} events. */
359    final private NetworkStateTrackerHandler mTrackerHandler;
360
361    private boolean mSystemReady;
362    private Intent mInitialBroadcast;
363
364    private PowerManager.WakeLock mNetTransitionWakeLock;
365    private String mNetTransitionWakeLockCausedBy = "";
366    private int mNetTransitionWakeLockSerialNumber;
367    private int mNetTransitionWakeLockTimeout;
368    private final PowerManager.WakeLock mPendingIntentWakeLock;
369
370    private InetAddress mDefaultDns;
371
372    // used in DBG mode to track inet condition reports
373    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
374    private ArrayList mInetLog;
375
376    // track the current default http proxy - tell the world if we get a new one (real change)
377    private volatile ProxyInfo mDefaultProxy = null;
378    private Object mProxyLock = new Object();
379    private boolean mDefaultProxyDisabled = false;
380
381    // track the global proxy.
382    private ProxyInfo mGlobalProxy = null;
383
384    private PacManager mPacManager = null;
385
386    final private SettingsObserver mSettingsObserver;
387
388    private UserManager mUserManager;
389
390    NetworkConfig[] mNetConfigs;
391    int mNetworksDefined;
392
393    // the set of network types that can only be enabled by system/sig apps
394    List mProtectedNetworks;
395
396    private DataConnectionStats mDataConnectionStats;
397
398    TelephonyManager mTelephonyManager;
399
400    // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
401    private final static int MIN_NET_ID = 100; // some reserved marks
402    private final static int MAX_NET_ID = 65535;
403    private int mNextNetId = MIN_NET_ID;
404
405    // sequence number of NetworkRequests
406    private int mNextNetworkRequestId = 1;
407
408    /**
409     * Implements support for the legacy "one network per network type" model.
410     *
411     * We used to have a static array of NetworkStateTrackers, one for each
412     * network type, but that doesn't work any more now that we can have,
413     * for example, more that one wifi network. This class stores all the
414     * NetworkAgentInfo objects that support a given type, but the legacy
415     * API will only see the first one.
416     *
417     * It serves two main purposes:
418     *
419     * 1. Provide information about "the network for a given type" (since this
420     *    API only supports one).
421     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
422     *    the first network for a given type changes, or if the default network
423     *    changes.
424     */
425    private class LegacyTypeTracker {
426
427        private static final boolean DBG = true;
428        private static final boolean VDBG = false;
429        private static final String TAG = "CSLegacyTypeTracker";
430
431        /**
432         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
433         * Each list holds references to all NetworkAgentInfos that are used to
434         * satisfy requests for that network type.
435         *
436         * This array is built out at startup such that an unsupported network
437         * doesn't get an ArrayList instance, making this a tristate:
438         * unsupported, supported but not active and active.
439         *
440         * The actual lists are populated when we scan the network types that
441         * are supported on this device.
442         */
443        private ArrayList<NetworkAgentInfo> mTypeLists[];
444
445        public LegacyTypeTracker() {
446            mTypeLists = (ArrayList<NetworkAgentInfo>[])
447                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
448        }
449
450        public void addSupportedType(int type) {
451            if (mTypeLists[type] != null) {
452                throw new IllegalStateException(
453                        "legacy list for type " + type + "already initialized");
454            }
455            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
456        }
457
458        public boolean isTypeSupported(int type) {
459            return isNetworkTypeValid(type) && mTypeLists[type] != null;
460        }
461
462        public NetworkAgentInfo getNetworkForType(int type) {
463            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
464                return mTypeLists[type].get(0);
465            } else {
466                return null;
467            }
468        }
469
470        private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
471                boolean isDefaultNetwork) {
472            if (DBG) {
473                log("Sending " + (connected ? "connected" : "disconnected") +
474                        " broadcast for type " + type + " " + nai.name() +
475                        " isDefaultNetwork=" + isDefaultNetwork);
476            }
477        }
478
479        /** Adds the given network to the specified legacy type list. */
480        public void add(int type, NetworkAgentInfo nai) {
481            if (!isTypeSupported(type)) {
482                return;  // Invalid network type.
483            }
484            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
485
486            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
487            if (list.contains(nai)) {
488                loge("Attempting to register duplicate agent for type " + type + ": " + nai);
489                return;
490            }
491
492            list.add(nai);
493
494            // Send a broadcast if this is the first network of its type or if it's the default.
495            final boolean isDefaultNetwork = isDefaultNetwork(nai);
496            if (list.size() == 1 || isDefaultNetwork) {
497                maybeLogBroadcast(nai, true, type, isDefaultNetwork);
498                sendLegacyNetworkBroadcast(nai, true, type);
499            }
500        }
501
502        /** Removes the given network from the specified legacy type list. */
503        public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
504            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
505            if (list == null || list.isEmpty()) {
506                return;
507            }
508
509            final boolean wasFirstNetwork = list.get(0).equals(nai);
510
511            if (!list.remove(nai)) {
512                return;
513            }
514
515            if (wasFirstNetwork || wasDefault) {
516                maybeLogBroadcast(nai, false, type, wasDefault);
517                sendLegacyNetworkBroadcast(nai, false, type);
518            }
519
520            if (!list.isEmpty() && wasFirstNetwork) {
521                if (DBG) log("Other network available for type " + type +
522                              ", sending connected broadcast");
523                final NetworkAgentInfo replacement = list.get(0);
524                maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
525                sendLegacyNetworkBroadcast(replacement, false, type);
526            }
527        }
528
529        /** Removes the given network from all legacy type lists. */
530        public void remove(NetworkAgentInfo nai, boolean wasDefault) {
531            if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
532            for (int type = 0; type < mTypeLists.length; type++) {
533                remove(type, nai, wasDefault);
534            }
535        }
536
537        private String naiToString(NetworkAgentInfo nai) {
538            String name = (nai != null) ? nai.name() : "null";
539            String state = (nai.networkInfo != null) ?
540                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
541                    "???/???";
542            return name + " " + state;
543        }
544
545        public void dump(IndentingPrintWriter pw) {
546            pw.println("mLegacyTypeTracker:");
547            pw.increaseIndent();
548            pw.print("Supported types:");
549            for (int type = 0; type < mTypeLists.length; type++) {
550                if (mTypeLists[type] != null) pw.print(" " + type);
551            }
552            pw.println();
553            pw.println("Current state:");
554            pw.increaseIndent();
555            for (int type = 0; type < mTypeLists.length; type++) {
556                if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
557                for (NetworkAgentInfo nai : mTypeLists[type]) {
558                    pw.println(type + " " + naiToString(nai));
559                }
560            }
561            pw.decreaseIndent();
562            pw.decreaseIndent();
563            pw.println();
564        }
565
566        // This class needs its own log method because it has a different TAG.
567        private void log(String s) {
568            Slog.d(TAG, s);
569        }
570
571    }
572    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
573
574    public ConnectivityService(Context context, INetworkManagementService netManager,
575            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
576        if (DBG) log("ConnectivityService starting up");
577
578        mDefaultRequest = createInternetRequestForTransport(-1);
579        mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
580                null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
581
582        mDefaultMobileDataRequest = createInternetRequestForTransport(
583                NetworkCapabilities.TRANSPORT_CELLULAR);
584
585        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
586        handlerThread.start();
587        mHandler = new InternalHandler(handlerThread.getLooper());
588        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
589
590        // setup our unique device name
591        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
592            String id = Settings.Secure.getString(context.getContentResolver(),
593                    Settings.Secure.ANDROID_ID);
594            if (id != null && id.length() > 0) {
595                String name = new String("android-").concat(id);
596                SystemProperties.set("net.hostname", name);
597            }
598        }
599
600        // read our default dns server ip
601        String dns = Settings.Global.getString(context.getContentResolver(),
602                Settings.Global.DEFAULT_DNS_SERVER);
603        if (dns == null || dns.length() == 0) {
604            dns = context.getResources().getString(
605                    com.android.internal.R.string.config_default_dns_server);
606        }
607        try {
608            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
609        } catch (IllegalArgumentException e) {
610            loge("Error setting defaultDns using " + dns);
611        }
612
613        mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
614                Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
615
616        mContext = checkNotNull(context, "missing Context");
617        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
618        mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
619        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
620        mKeyStore = KeyStore.getInstance();
621        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
622
623        try {
624            mPolicyManager.registerListener(mPolicyListener);
625        } catch (RemoteException e) {
626            // ouch, no rules updates means some processes may never get network
627            loge("unable to register INetworkPolicyListener" + e.toString());
628        }
629
630        final PowerManager powerManager = (PowerManager) context.getSystemService(
631                Context.POWER_SERVICE);
632        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
633        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
634                com.android.internal.R.integer.config_networkTransitionTimeout);
635        mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
636
637        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
638
639        // TODO: What is the "correct" way to do determine if this is a wifi only device?
640        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
641        log("wifiOnly=" + wifiOnly);
642        String[] naStrings = context.getResources().getStringArray(
643                com.android.internal.R.array.networkAttributes);
644        for (String naString : naStrings) {
645            try {
646                NetworkConfig n = new NetworkConfig(naString);
647                if (VDBG) log("naString=" + naString + " config=" + n);
648                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
649                    loge("Error in networkAttributes - ignoring attempt to define type " +
650                            n.type);
651                    continue;
652                }
653                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
654                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
655                            n.type);
656                    continue;
657                }
658                if (mNetConfigs[n.type] != null) {
659                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
660                            n.type);
661                    continue;
662                }
663                mLegacyTypeTracker.addSupportedType(n.type);
664
665                mNetConfigs[n.type] = n;
666                mNetworksDefined++;
667            } catch(Exception e) {
668                // ignore it - leave the entry null
669            }
670        }
671
672        // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
673        if (mNetConfigs[TYPE_VPN] == null) {
674            // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
675            // don't need to add TYPE_VPN to mNetConfigs.
676            mLegacyTypeTracker.addSupportedType(TYPE_VPN);
677            mNetworksDefined++;  // used only in the log() statement below.
678        }
679
680        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
681
682        mProtectedNetworks = new ArrayList<Integer>();
683        int[] protectedNetworks = context.getResources().getIntArray(
684                com.android.internal.R.array.config_protectedNetworks);
685        for (int p : protectedNetworks) {
686            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
687                mProtectedNetworks.add(p);
688            } else {
689                if (DBG) loge("Ignoring protectedNetwork " + p);
690            }
691        }
692
693        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
694                && SystemProperties.get("ro.build.type").equals("eng");
695
696        mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
697
698        mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
699
700        //set up the listener for user state for creating user VPNs
701        IntentFilter intentFilter = new IntentFilter();
702        intentFilter.addAction(Intent.ACTION_USER_STARTING);
703        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
704        mContext.registerReceiverAsUser(
705                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
706
707        try {
708            mNetd.registerObserver(mTethering);
709            mNetd.registerObserver(mDataActivityObserver);
710        } catch (RemoteException e) {
711            loge("Error registering observer :" + e);
712        }
713
714        if (DBG) {
715            mInetLog = new ArrayList();
716        }
717
718        mSettingsObserver = new SettingsObserver(mContext, mHandler);
719        registerSettingsCallbacks();
720
721        mDataConnectionStats = new DataConnectionStats(mContext);
722        mDataConnectionStats.startMonitoring();
723
724        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
725
726        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
727    }
728
729    private NetworkRequest createInternetRequestForTransport(int transportType) {
730        NetworkCapabilities netCap = new NetworkCapabilities();
731        netCap.addCapability(NET_CAPABILITY_INTERNET);
732        netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
733        if (transportType > -1) {
734            netCap.addTransportType(transportType);
735        }
736        return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
737    }
738
739    private void handleMobileDataAlwaysOn() {
740        final boolean enable = (Settings.Global.getInt(
741                mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
742        final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
743        if (enable == isEnabled) {
744            return;  // Nothing to do.
745        }
746
747        if (enable) {
748            handleRegisterNetworkRequest(new NetworkRequestInfo(
749                    null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
750        } else {
751            handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
752        }
753    }
754
755    private void registerSettingsCallbacks() {
756        // Watch for global HTTP proxy changes.
757        mSettingsObserver.observe(
758                Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
759                EVENT_APPLY_GLOBAL_HTTP_PROXY);
760
761        // Watch for whether or not to keep mobile data always on.
762        mSettingsObserver.observe(
763                Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
764                EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
765    }
766
767    private synchronized int nextNetworkRequestId() {
768        return mNextNetworkRequestId++;
769    }
770
771    private int reserveNetId() {
772        synchronized (mNetworkForNetId) {
773            for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
774                int netId = mNextNetId;
775                if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
776                // Make sure NetID unused.  http://b/16815182
777                if (!mNetIdInUse.get(netId)) {
778                    mNetIdInUse.put(netId, true);
779                    return netId;
780                }
781            }
782        }
783        throw new IllegalStateException("No free netIds");
784    }
785
786    private NetworkState getFilteredNetworkState(int networkType, int uid) {
787        NetworkInfo info = null;
788        LinkProperties lp = null;
789        NetworkCapabilities nc = null;
790        Network network = null;
791        String subscriberId = null;
792
793        if (mLegacyTypeTracker.isTypeSupported(networkType)) {
794            NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
795            if (nai != null) {
796                synchronized (nai) {
797                    info = new NetworkInfo(nai.networkInfo);
798                    lp = new LinkProperties(nai.linkProperties);
799                    nc = new NetworkCapabilities(nai.networkCapabilities);
800                    // Network objects are outwardly immutable so there is no point to duplicating.
801                    // Duplicating also precludes sharing socket factories and connection pools.
802                    network = nai.network;
803                    subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
804                }
805                info.setType(networkType);
806            } else {
807                info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
808                info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
809                info.setIsAvailable(true);
810                lp = new LinkProperties();
811                nc = new NetworkCapabilities();
812                network = null;
813            }
814            info = getFilteredNetworkInfo(info, lp, uid);
815        }
816
817        return new NetworkState(info, lp, nc, network, subscriberId, null);
818    }
819
820    private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
821        if (network == null) {
822            return null;
823        }
824        synchronized (mNetworkForNetId) {
825            return mNetworkForNetId.get(network.netId);
826        }
827    };
828
829    private Network[] getVpnUnderlyingNetworks(int uid) {
830        if (!mLockdownEnabled) {
831            int user = UserHandle.getUserId(uid);
832            synchronized (mVpns) {
833                Vpn vpn = mVpns.get(user);
834                if (vpn != null && vpn.appliesToUid(uid)) {
835                    return vpn.getUnderlyingNetworks();
836                }
837            }
838        }
839        return null;
840    }
841
842    private NetworkState getUnfilteredActiveNetworkState(int uid) {
843        NetworkInfo info = null;
844        LinkProperties lp = null;
845        NetworkCapabilities nc = null;
846        Network network = null;
847        String subscriberId = null;
848
849        NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
850
851        final Network[] networks = getVpnUnderlyingNetworks(uid);
852        if (networks != null) {
853            // getUnderlyingNetworks() returns:
854            // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
855            // empty array => the VPN explicitly said "no default network".
856            // non-empty array => the VPN specified one or more default networks; we use the
857            //                    first one.
858            if (networks.length > 0) {
859                nai = getNetworkAgentInfoForNetwork(networks[0]);
860            } else {
861                nai = null;
862            }
863        }
864
865        if (nai != null) {
866            synchronized (nai) {
867                info = new NetworkInfo(nai.networkInfo);
868                lp = new LinkProperties(nai.linkProperties);
869                nc = new NetworkCapabilities(nai.networkCapabilities);
870                // Network objects are outwardly immutable so there is no point to duplicating.
871                // Duplicating also precludes sharing socket factories and connection pools.
872                network = nai.network;
873                subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
874            }
875        }
876
877        return new NetworkState(info, lp, nc, network, subscriberId, null);
878    }
879
880    /**
881     * Check if UID should be blocked from using the network with the given LinkProperties.
882     */
883    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
884        final boolean networkCostly;
885        final int uidRules;
886
887        final String iface = (lp == null ? "" : lp.getInterfaceName());
888        synchronized (mRulesLock) {
889            networkCostly = mMeteredIfaces.contains(iface);
890            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
891        }
892
893        if ((uidRules & RULE_REJECT_ALL) != 0
894                || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
895            return true;
896        }
897
898        // no restrictive rules; network is visible
899        return false;
900    }
901
902    /**
903     * Return a filtered {@link NetworkInfo}, potentially marked
904     * {@link DetailedState#BLOCKED} based on
905     * {@link #isNetworkWithLinkPropertiesBlocked}.
906     */
907    private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
908        if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
909            // network is blocked; clone and override state
910            info = new NetworkInfo(info);
911            info.setDetailedState(DetailedState.BLOCKED, null, null);
912            if (VDBG) {
913                log("returning Blocked NetworkInfo for ifname=" +
914                        lp.getInterfaceName() + ", uid=" + uid);
915            }
916        }
917        if (info != null && mLockdownTracker != null) {
918            info = mLockdownTracker.augmentNetworkInfo(info);
919            if (VDBG) log("returning Locked NetworkInfo");
920        }
921        return info;
922    }
923
924    /**
925     * Return NetworkInfo for the active (i.e., connected) network interface.
926     * It is assumed that at most one network is active at a time. If more
927     * than one is active, it is indeterminate which will be returned.
928     * @return the info for the active network, or {@code null} if none is
929     * active
930     */
931    @Override
932    public NetworkInfo getActiveNetworkInfo() {
933        enforceAccessPermission();
934        final int uid = Binder.getCallingUid();
935        NetworkState state = getUnfilteredActiveNetworkState(uid);
936        return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
937    }
938
939    @Override
940    public Network getActiveNetwork() {
941        enforceAccessPermission();
942        final int uid = Binder.getCallingUid();
943        final int user = UserHandle.getUserId(uid);
944        int vpnNetId = NETID_UNSET;
945        synchronized (mVpns) {
946            final Vpn vpn = mVpns.get(user);
947            if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
948        }
949        NetworkAgentInfo nai;
950        if (vpnNetId != NETID_UNSET) {
951            synchronized (mNetworkForNetId) {
952                nai = mNetworkForNetId.get(vpnNetId);
953            }
954            if (nai != null) return nai.network;
955        }
956        nai = getDefaultNetwork();
957        if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
958        return nai != null ? nai.network : null;
959    }
960
961    /**
962     * Find the first Provisioning network.
963     *
964     * @return NetworkInfo or null if none.
965     */
966    private NetworkInfo getProvisioningNetworkInfo() {
967        enforceAccessPermission();
968
969        // Find the first Provisioning Network
970        NetworkInfo provNi = null;
971        for (NetworkInfo ni : getAllNetworkInfo()) {
972            if (ni.isConnectedToProvisioningNetwork()) {
973                provNi = ni;
974                break;
975            }
976        }
977        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
978        return provNi;
979    }
980
981    /**
982     * Find the first Provisioning network or the ActiveDefaultNetwork
983     * if there is no Provisioning network
984     *
985     * @return NetworkInfo or null if none.
986     */
987    @Override
988    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
989        enforceAccessPermission();
990
991        NetworkInfo provNi = getProvisioningNetworkInfo();
992        if (provNi == null) {
993            provNi = getActiveNetworkInfo();
994        }
995        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
996        return provNi;
997    }
998
999    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1000        enforceAccessPermission();
1001        final int uid = Binder.getCallingUid();
1002        NetworkState state = getUnfilteredActiveNetworkState(uid);
1003        return state.networkInfo;
1004    }
1005
1006    @Override
1007    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1008        enforceConnectivityInternalPermission();
1009        NetworkState state = getUnfilteredActiveNetworkState(uid);
1010        return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1011    }
1012
1013    @Override
1014    public NetworkInfo getNetworkInfo(int networkType) {
1015        enforceAccessPermission();
1016        final int uid = Binder.getCallingUid();
1017        if (getVpnUnderlyingNetworks(uid) != null) {
1018            // A VPN is active, so we may need to return one of its underlying networks. This
1019            // information is not available in LegacyTypeTracker, so we have to get it from
1020            // getUnfilteredActiveNetworkState.
1021            NetworkState state = getUnfilteredActiveNetworkState(uid);
1022            if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1023                return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1024            }
1025        }
1026        NetworkState state = getFilteredNetworkState(networkType, uid);
1027        return state.networkInfo;
1028    }
1029
1030    @Override
1031    public NetworkInfo getNetworkInfoForNetwork(Network network) {
1032        enforceAccessPermission();
1033        final int uid = Binder.getCallingUid();
1034        NetworkInfo info = null;
1035        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1036        if (nai != null) {
1037            synchronized (nai) {
1038                info = new NetworkInfo(nai.networkInfo);
1039                info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
1040            }
1041        }
1042        return info;
1043    }
1044
1045    @Override
1046    public NetworkInfo[] getAllNetworkInfo() {
1047        enforceAccessPermission();
1048        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1049        for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1050                networkType++) {
1051            NetworkInfo info = getNetworkInfo(networkType);
1052            if (info != null) {
1053                result.add(info);
1054            }
1055        }
1056        return result.toArray(new NetworkInfo[result.size()]);
1057    }
1058
1059    @Override
1060    public Network getNetworkForType(int networkType) {
1061        enforceAccessPermission();
1062        final int uid = Binder.getCallingUid();
1063        NetworkState state = getFilteredNetworkState(networkType, uid);
1064        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1065            return state.network;
1066        }
1067        return null;
1068    }
1069
1070    @Override
1071    public Network[] getAllNetworks() {
1072        enforceAccessPermission();
1073        synchronized (mNetworkForNetId) {
1074            final Network[] result = new Network[mNetworkForNetId.size()];
1075            for (int i = 0; i < mNetworkForNetId.size(); i++) {
1076                result[i] = mNetworkForNetId.valueAt(i).network;
1077            }
1078            return result;
1079        }
1080    }
1081
1082    @Override
1083    public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1084        // The basic principle is: if an app's traffic could possibly go over a
1085        // network, without the app doing anything multinetwork-specific,
1086        // (hence, by "default"), then include that network's capabilities in
1087        // the array.
1088        //
1089        // In the normal case, app traffic only goes over the system's default
1090        // network connection, so that's the only network returned.
1091        //
1092        // With a VPN in force, some app traffic may go into the VPN, and thus
1093        // over whatever underlying networks the VPN specifies, while other app
1094        // traffic may go over the system default network (e.g.: a split-tunnel
1095        // VPN, or an app disallowed by the VPN), so the set of networks
1096        // returned includes the VPN's underlying networks and the system
1097        // default.
1098        enforceAccessPermission();
1099
1100        HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1101
1102        NetworkAgentInfo nai = getDefaultNetwork();
1103        NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1104        if (nc != null) {
1105            result.put(nai.network, nc);
1106        }
1107
1108        if (!mLockdownEnabled) {
1109            synchronized (mVpns) {
1110                Vpn vpn = mVpns.get(userId);
1111                if (vpn != null) {
1112                    Network[] networks = vpn.getUnderlyingNetworks();
1113                    if (networks != null) {
1114                        for (Network network : networks) {
1115                            nai = getNetworkAgentInfoForNetwork(network);
1116                            nc = getNetworkCapabilitiesInternal(nai);
1117                            if (nc != null) {
1118                                result.put(network, nc);
1119                            }
1120                        }
1121                    }
1122                }
1123            }
1124        }
1125
1126        NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1127        out = result.values().toArray(out);
1128        return out;
1129    }
1130
1131    @Override
1132    public boolean isNetworkSupported(int networkType) {
1133        enforceAccessPermission();
1134        return mLegacyTypeTracker.isTypeSupported(networkType);
1135    }
1136
1137    /**
1138     * Return LinkProperties for the active (i.e., connected) default
1139     * network interface.  It is assumed that at most one default network
1140     * is active at a time. If more than one is active, it is indeterminate
1141     * which will be returned.
1142     * @return the ip properties for the active network, or {@code null} if
1143     * none is active
1144     */
1145    @Override
1146    public LinkProperties getActiveLinkProperties() {
1147        enforceAccessPermission();
1148        final int uid = Binder.getCallingUid();
1149        NetworkState state = getUnfilteredActiveNetworkState(uid);
1150        return state.linkProperties;
1151    }
1152
1153    @Override
1154    public LinkProperties getLinkPropertiesForType(int networkType) {
1155        enforceAccessPermission();
1156        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1157        if (nai != null) {
1158            synchronized (nai) {
1159                return new LinkProperties(nai.linkProperties);
1160            }
1161        }
1162        return null;
1163    }
1164
1165    // TODO - this should be ALL networks
1166    @Override
1167    public LinkProperties getLinkProperties(Network network) {
1168        enforceAccessPermission();
1169        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1170        if (nai != null) {
1171            synchronized (nai) {
1172                return new LinkProperties(nai.linkProperties);
1173            }
1174        }
1175        return null;
1176    }
1177
1178    private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1179        if (nai != null) {
1180            synchronized (nai) {
1181                if (nai.networkCapabilities != null) {
1182                    return new NetworkCapabilities(nai.networkCapabilities);
1183                }
1184            }
1185        }
1186        return null;
1187    }
1188
1189    @Override
1190    public NetworkCapabilities getNetworkCapabilities(Network network) {
1191        enforceAccessPermission();
1192        return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1193    }
1194
1195    @Override
1196    public NetworkState[] getAllNetworkState() {
1197        // Require internal since we're handing out IMSI details
1198        enforceConnectivityInternalPermission();
1199
1200        final ArrayList<NetworkState> result = Lists.newArrayList();
1201        for (Network network : getAllNetworks()) {
1202            final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1203            if (nai != null) {
1204                synchronized (nai) {
1205                    final String subscriberId = (nai.networkMisc != null)
1206                            ? nai.networkMisc.subscriberId : null;
1207                    result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1208                            nai.networkCapabilities, network, subscriberId, null));
1209                }
1210            }
1211        }
1212        return result.toArray(new NetworkState[result.size()]);
1213    }
1214
1215    @Override
1216    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1217        enforceAccessPermission();
1218        final int uid = Binder.getCallingUid();
1219        final long token = Binder.clearCallingIdentity();
1220        try {
1221            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1222            if (state.networkInfo != null) {
1223                try {
1224                    return mPolicyManager.getNetworkQuotaInfo(state);
1225                } catch (RemoteException e) {
1226                }
1227            }
1228            return null;
1229        } finally {
1230            Binder.restoreCallingIdentity(token);
1231        }
1232    }
1233
1234    @Override
1235    public boolean isActiveNetworkMetered() {
1236        enforceAccessPermission();
1237        final int uid = Binder.getCallingUid();
1238        final long token = Binder.clearCallingIdentity();
1239        try {
1240            return isActiveNetworkMeteredUnchecked(uid);
1241        } finally {
1242            Binder.restoreCallingIdentity(token);
1243        }
1244    }
1245
1246    private boolean isActiveNetworkMeteredUnchecked(int uid) {
1247        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1248        if (state.networkInfo != null) {
1249            try {
1250                return mPolicyManager.isNetworkMetered(state);
1251            } catch (RemoteException e) {
1252            }
1253        }
1254        return false;
1255    }
1256
1257    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1258        @Override
1259        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1260            int deviceType = Integer.parseInt(label);
1261            sendDataActivityBroadcast(deviceType, active, tsNanos);
1262        }
1263    };
1264
1265    /**
1266     * Ensure that a network route exists to deliver traffic to the specified
1267     * host via the specified network interface.
1268     * @param networkType the type of the network over which traffic to the
1269     * specified host is to be routed
1270     * @param hostAddress the IP address of the host to which the route is
1271     * desired
1272     * @return {@code true} on success, {@code false} on failure
1273     */
1274    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1275        enforceChangePermission();
1276        if (mProtectedNetworks.contains(networkType)) {
1277            enforceConnectivityInternalPermission();
1278        }
1279
1280        InetAddress addr;
1281        try {
1282            addr = InetAddress.getByAddress(hostAddress);
1283        } catch (UnknownHostException e) {
1284            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1285            return false;
1286        }
1287
1288        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1289            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1290            return false;
1291        }
1292
1293        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1294        if (nai == null) {
1295            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1296                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1297            } else {
1298                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1299            }
1300            return false;
1301        }
1302
1303        DetailedState netState;
1304        synchronized (nai) {
1305            netState = nai.networkInfo.getDetailedState();
1306        }
1307
1308        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1309            if (VDBG) {
1310                log("requestRouteToHostAddress on down network "
1311                        + "(" + networkType + ") - dropped"
1312                        + " netState=" + netState);
1313            }
1314            return false;
1315        }
1316
1317        final int uid = Binder.getCallingUid();
1318        final long token = Binder.clearCallingIdentity();
1319        try {
1320            LinkProperties lp;
1321            int netId;
1322            synchronized (nai) {
1323                lp = nai.linkProperties;
1324                netId = nai.network.netId;
1325            }
1326            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1327            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1328            return ok;
1329        } finally {
1330            Binder.restoreCallingIdentity(token);
1331        }
1332    }
1333
1334    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1335        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1336        if (bestRoute == null) {
1337            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1338        } else {
1339            String iface = bestRoute.getInterface();
1340            if (bestRoute.getGateway().equals(addr)) {
1341                // if there is no better route, add the implied hostroute for our gateway
1342                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1343            } else {
1344                // if we will connect to this through another route, add a direct route
1345                // to it's gateway
1346                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1347            }
1348        }
1349        if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
1350        try {
1351            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1352        } catch (Exception e) {
1353            // never crash - catch them all
1354            if (DBG) loge("Exception trying to add a route: " + e);
1355            return false;
1356        }
1357        return true;
1358    }
1359
1360    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1361        @Override
1362        public void onUidRulesChanged(int uid, int uidRules) {
1363            // caller is NPMS, since we only register with them
1364            if (LOGD_RULES) {
1365                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1366            }
1367
1368            synchronized (mRulesLock) {
1369                // skip update when we've already applied rules
1370                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1371                if (oldRules == uidRules) return;
1372
1373                mUidRules.put(uid, uidRules);
1374            }
1375
1376            // TODO: notify UID when it has requested targeted updates
1377        }
1378
1379        @Override
1380        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1381            // caller is NPMS, since we only register with them
1382            if (LOGD_RULES) {
1383                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1384            }
1385
1386            synchronized (mRulesLock) {
1387                mMeteredIfaces.clear();
1388                for (String iface : meteredIfaces) {
1389                    mMeteredIfaces.add(iface);
1390                }
1391            }
1392        }
1393
1394        @Override
1395        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1396            // caller is NPMS, since we only register with them
1397            if (LOGD_RULES) {
1398                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1399            }
1400        }
1401    };
1402
1403    /**
1404     * Require that the caller is either in the same user or has appropriate permission to interact
1405     * across users.
1406     *
1407     * @param userId Target user for whatever operation the current IPC is supposed to perform.
1408     */
1409    private void enforceCrossUserPermission(int userId) {
1410        if (userId == UserHandle.getCallingUserId()) {
1411            // Not a cross-user call.
1412            return;
1413        }
1414        mContext.enforceCallingOrSelfPermission(
1415                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1416                "ConnectivityService");
1417    }
1418
1419    private void enforceInternetPermission() {
1420        mContext.enforceCallingOrSelfPermission(
1421                android.Manifest.permission.INTERNET,
1422                "ConnectivityService");
1423    }
1424
1425    private void enforceAccessPermission() {
1426        mContext.enforceCallingOrSelfPermission(
1427                android.Manifest.permission.ACCESS_NETWORK_STATE,
1428                "ConnectivityService");
1429    }
1430
1431    private void enforceChangePermission() {
1432        mContext.enforceCallingOrSelfPermission(
1433                android.Manifest.permission.CHANGE_NETWORK_STATE,
1434                "ConnectivityService");
1435    }
1436
1437    private void enforceTetherAccessPermission() {
1438        mContext.enforceCallingOrSelfPermission(
1439                android.Manifest.permission.ACCESS_NETWORK_STATE,
1440                "ConnectivityService");
1441    }
1442
1443    private void enforceConnectivityInternalPermission() {
1444        mContext.enforceCallingOrSelfPermission(
1445                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1446                "ConnectivityService");
1447    }
1448
1449    public void sendConnectedBroadcast(NetworkInfo info) {
1450        enforceConnectivityInternalPermission();
1451        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1452    }
1453
1454    private void sendInetConditionBroadcast(NetworkInfo info) {
1455        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1456    }
1457
1458    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1459        if (mLockdownTracker != null) {
1460            info = mLockdownTracker.augmentNetworkInfo(info);
1461        }
1462
1463        Intent intent = new Intent(bcastType);
1464        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1465        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1466        if (info.isFailover()) {
1467            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1468            info.setFailover(false);
1469        }
1470        if (info.getReason() != null) {
1471            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1472        }
1473        if (info.getExtraInfo() != null) {
1474            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1475                    info.getExtraInfo());
1476        }
1477        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1478        return intent;
1479    }
1480
1481    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1482        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1483    }
1484
1485    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1486        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1487        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1488        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1489        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1490        final long ident = Binder.clearCallingIdentity();
1491        try {
1492            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1493                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1494        } finally {
1495            Binder.restoreCallingIdentity(ident);
1496        }
1497    }
1498
1499    private void sendStickyBroadcast(Intent intent) {
1500        synchronized(this) {
1501            if (!mSystemReady) {
1502                mInitialBroadcast = new Intent(intent);
1503            }
1504            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1505            if (DBG) {
1506                log("sendStickyBroadcast: action=" + intent.getAction());
1507            }
1508
1509            final long ident = Binder.clearCallingIdentity();
1510            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1511                final IBatteryStats bs = BatteryStatsService.getService();
1512                try {
1513                    NetworkInfo ni = intent.getParcelableExtra(
1514                            ConnectivityManager.EXTRA_NETWORK_INFO);
1515                    bs.noteConnectivityChanged(intent.getIntExtra(
1516                            ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1517                            ni != null ? ni.getState().toString() : "?");
1518                } catch (RemoteException e) {
1519                }
1520            }
1521            try {
1522                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1523            } finally {
1524                Binder.restoreCallingIdentity(ident);
1525            }
1526        }
1527    }
1528
1529    void systemReady() {
1530        loadGlobalProxy();
1531
1532        synchronized(this) {
1533            mSystemReady = true;
1534            if (mInitialBroadcast != null) {
1535                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1536                mInitialBroadcast = null;
1537            }
1538        }
1539        // load the global proxy at startup
1540        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1541
1542        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1543        // for user to unlock device.
1544        if (!updateLockdownVpn()) {
1545            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1546            mContext.registerReceiver(mUserPresentReceiver, filter);
1547        }
1548
1549        // Configure whether mobile data is always on.
1550        mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1551
1552        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1553
1554        mPermissionMonitor.startMonitoring();
1555    }
1556
1557    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1558        @Override
1559        public void onReceive(Context context, Intent intent) {
1560            // Try creating lockdown tracker, since user present usually means
1561            // unlocked keystore.
1562            if (updateLockdownVpn()) {
1563                mContext.unregisterReceiver(this);
1564            }
1565        }
1566    };
1567
1568    /** @hide */
1569    @Override
1570    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1571        enforceConnectivityInternalPermission();
1572        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
1573//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
1574    }
1575
1576    /**
1577     * Setup data activity tracking for the given network.
1578     *
1579     * Every {@code setupDataActivityTracking} should be paired with a
1580     * {@link #removeDataActivityTracking} for cleanup.
1581     */
1582    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1583        final String iface = networkAgent.linkProperties.getInterfaceName();
1584
1585        final int timeout;
1586        int type = ConnectivityManager.TYPE_NONE;
1587
1588        if (networkAgent.networkCapabilities.hasTransport(
1589                NetworkCapabilities.TRANSPORT_CELLULAR)) {
1590            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1591                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
1592                                             5);
1593            type = ConnectivityManager.TYPE_MOBILE;
1594        } else if (networkAgent.networkCapabilities.hasTransport(
1595                NetworkCapabilities.TRANSPORT_WIFI)) {
1596            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1597                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
1598                                             5);
1599            type = ConnectivityManager.TYPE_WIFI;
1600        } else {
1601            // do not track any other networks
1602            timeout = 0;
1603        }
1604
1605        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
1606            try {
1607                mNetd.addIdleTimer(iface, timeout, type);
1608            } catch (Exception e) {
1609                // You shall not crash!
1610                loge("Exception in setupDataActivityTracking " + e);
1611            }
1612        }
1613    }
1614
1615    /**
1616     * Remove data activity tracking when network disconnects.
1617     */
1618    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1619        final String iface = networkAgent.linkProperties.getInterfaceName();
1620        final NetworkCapabilities caps = networkAgent.networkCapabilities;
1621
1622        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1623                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
1624            try {
1625                // the call fails silently if no idletimer setup for this interface
1626                mNetd.removeIdleTimer(iface);
1627            } catch (Exception e) {
1628                loge("Exception in removeDataActivityTracking " + e);
1629            }
1630        }
1631    }
1632
1633    /**
1634     * Reads the network specific MTU size from reources.
1635     * and set it on it's iface.
1636     */
1637    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1638        final String iface = newLp.getInterfaceName();
1639        final int mtu = newLp.getMtu();
1640        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1641            if (VDBG) log("identical MTU - not setting");
1642            return;
1643        }
1644
1645        if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
1646            loge("Unexpected mtu value: " + mtu + ", " + iface);
1647            return;
1648        }
1649
1650        // Cannot set MTU without interface name
1651        if (TextUtils.isEmpty(iface)) {
1652            loge("Setting MTU size with null iface.");
1653            return;
1654        }
1655
1656        try {
1657            if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
1658            mNetd.setMtu(iface, mtu);
1659        } catch (Exception e) {
1660            Slog.e(TAG, "exception in setMtu()" + e);
1661        }
1662    }
1663
1664    private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
1665    private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1666
1667    // Overridden for testing purposes to avoid writing to SystemProperties.
1668    protected int getDefaultTcpRwnd() {
1669        return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1670    }
1671
1672    private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1673        if (isDefaultNetwork(nai) == false) {
1674            return;
1675        }
1676
1677        String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1678        String[] values = null;
1679        if (tcpBufferSizes != null) {
1680            values = tcpBufferSizes.split(",");
1681        }
1682
1683        if (values == null || values.length != 6) {
1684            if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
1685            tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1686            values = tcpBufferSizes.split(",");
1687        }
1688
1689        if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1690
1691        try {
1692            if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
1693
1694            final String prefix = "/sys/kernel/ipv4/tcp_";
1695            FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1696            FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1697            FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1698            FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1699            FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1700            FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1701            mCurrentTcpBufferSizes = tcpBufferSizes;
1702        } catch (IOException e) {
1703            loge("Can't set TCP buffer sizes:" + e);
1704        }
1705
1706        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1707            Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
1708        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1709        if (rwndValue != 0) {
1710            SystemProperties.set(sysctlKey, rwndValue.toString());
1711        }
1712    }
1713
1714    private void flushVmDnsCache() {
1715        /*
1716         * Tell the VMs to toss their DNS caches
1717         */
1718        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1719        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1720        /*
1721         * Connectivity events can happen before boot has completed ...
1722         */
1723        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1724        final long ident = Binder.clearCallingIdentity();
1725        try {
1726            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1727        } finally {
1728            Binder.restoreCallingIdentity(ident);
1729        }
1730    }
1731
1732    @Override
1733    public int getRestoreDefaultNetworkDelay(int networkType) {
1734        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1735                NETWORK_RESTORE_DELAY_PROP_NAME);
1736        if(restoreDefaultNetworkDelayStr != null &&
1737                restoreDefaultNetworkDelayStr.length() != 0) {
1738            try {
1739                return Integer.valueOf(restoreDefaultNetworkDelayStr);
1740            } catch (NumberFormatException e) {
1741            }
1742        }
1743        // if the system property isn't set, use the value for the apn type
1744        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1745
1746        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1747                (mNetConfigs[networkType] != null)) {
1748            ret = mNetConfigs[networkType].restoreTime;
1749        }
1750        return ret;
1751    }
1752
1753    private boolean shouldPerformDiagnostics(String[] args) {
1754        for (String arg : args) {
1755            if (arg.equals("--diag")) {
1756                return true;
1757            }
1758        }
1759        return false;
1760    }
1761
1762    @Override
1763    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1764        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1765        if (mContext.checkCallingOrSelfPermission(
1766                android.Manifest.permission.DUMP)
1767                != PackageManager.PERMISSION_GRANTED) {
1768            pw.println("Permission Denial: can't dump ConnectivityService " +
1769                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1770                    Binder.getCallingUid());
1771            return;
1772        }
1773
1774        final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1775        if (shouldPerformDiagnostics(args)) {
1776            final long DIAG_TIME_MS = 5000;
1777            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1778                // Start gathering diagnostic information.
1779                netDiags.add(new NetworkDiagnostics(
1780                        nai.network,
1781                        new LinkProperties(nai.linkProperties),
1782                        DIAG_TIME_MS));
1783            }
1784
1785            for (NetworkDiagnostics netDiag : netDiags) {
1786                pw.println();
1787                netDiag.waitForMeasurements();
1788                netDiag.dump(pw);
1789            }
1790
1791            return;
1792        }
1793
1794        pw.print("NetworkFactories for:");
1795        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1796            pw.print(" " + nfi.name);
1797        }
1798        pw.println();
1799        pw.println();
1800
1801        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1802        pw.print("Active default network: ");
1803        if (defaultNai == null) {
1804            pw.println("none");
1805        } else {
1806            pw.println(defaultNai.network.netId);
1807        }
1808        pw.println();
1809
1810        pw.println("Current Networks:");
1811        pw.increaseIndent();
1812        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1813            pw.println(nai.toString());
1814            pw.increaseIndent();
1815            pw.println("Requests:");
1816            pw.increaseIndent();
1817            for (int i = 0; i < nai.networkRequests.size(); i++) {
1818                pw.println(nai.networkRequests.valueAt(i).toString());
1819            }
1820            pw.decreaseIndent();
1821            pw.println("Lingered:");
1822            pw.increaseIndent();
1823            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1824            pw.decreaseIndent();
1825            pw.decreaseIndent();
1826        }
1827        pw.decreaseIndent();
1828        pw.println();
1829
1830        pw.println("Network Requests:");
1831        pw.increaseIndent();
1832        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1833            pw.println(nri.toString());
1834        }
1835        pw.println();
1836        pw.decreaseIndent();
1837
1838        mLegacyTypeTracker.dump(pw);
1839
1840        synchronized (this) {
1841            pw.print("mNetTransitionWakeLock: currently " +
1842                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1843            if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1844                pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1845            } else {
1846                pw.println(", last requested never");
1847            }
1848        }
1849        pw.println();
1850
1851        mTethering.dump(fd, pw, args);
1852
1853        if (mInetLog != null && mInetLog.size() > 0) {
1854            pw.println();
1855            pw.println("Inet condition reports:");
1856            pw.increaseIndent();
1857            for(int i = 0; i < mInetLog.size(); i++) {
1858                pw.println(mInetLog.get(i));
1859            }
1860            pw.decreaseIndent();
1861        }
1862    }
1863
1864    private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
1865        if (nai.network == null) return false;
1866        final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
1867        if (officialNai != null && officialNai.equals(nai)) return true;
1868        if (officialNai != null || VDBG) {
1869            loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
1870                " - " + nai);
1871        }
1872        return false;
1873    }
1874
1875    private boolean isRequest(NetworkRequest request) {
1876        return mNetworkRequests.get(request).isRequest;
1877    }
1878
1879    // must be stateless - things change under us.
1880    private class NetworkStateTrackerHandler extends Handler {
1881        public NetworkStateTrackerHandler(Looper looper) {
1882            super(looper);
1883        }
1884
1885        @Override
1886        public void handleMessage(Message msg) {
1887            NetworkInfo info;
1888            switch (msg.what) {
1889                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
1890                    handleAsyncChannelHalfConnect(msg);
1891                    break;
1892                }
1893                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1894                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1895                    if (nai != null) nai.asyncChannel.disconnect();
1896                    break;
1897                }
1898                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1899                    handleAsyncChannelDisconnected(msg);
1900                    break;
1901                }
1902                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1903                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1904                    if (nai == null) {
1905                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1906                    } else {
1907                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
1908                    }
1909                    break;
1910                }
1911                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1912                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1913                    if (nai == null) {
1914                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1915                    } else {
1916                        if (VDBG) {
1917                            log("Update of LinkProperties for " + nai.name() +
1918                                    "; created=" + nai.created);
1919                        }
1920                        LinkProperties oldLp = nai.linkProperties;
1921                        synchronized (nai) {
1922                            nai.linkProperties = (LinkProperties)msg.obj;
1923                        }
1924                        if (nai.created) updateLinkProperties(nai, oldLp);
1925                    }
1926                    break;
1927                }
1928                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1929                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930                    if (nai == null) {
1931                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1932                        break;
1933                    }
1934                    info = (NetworkInfo) msg.obj;
1935                    updateNetworkInfo(nai, info);
1936                    break;
1937                }
1938                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1939                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1940                    if (nai == null) {
1941                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1942                        break;
1943                    }
1944                    Integer score = (Integer) msg.obj;
1945                    if (score != null) updateNetworkScore(nai, score.intValue());
1946                    break;
1947                }
1948                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1949                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1950                    if (nai == null) {
1951                        loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1952                        break;
1953                    }
1954                    try {
1955                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1956                    } catch (Exception e) {
1957                        // Never crash!
1958                        loge("Exception in addVpnUidRanges: " + e);
1959                    }
1960                    break;
1961                }
1962                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1963                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1964                    if (nai == null) {
1965                        loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1966                        break;
1967                    }
1968                    try {
1969                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1970                    } catch (Exception e) {
1971                        // Never crash!
1972                        loge("Exception in removeVpnUidRanges: " + e);
1973                    }
1974                    break;
1975                }
1976                case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1977                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1978                    if (nai == null) {
1979                        loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1980                        break;
1981                    }
1982                    if (nai.created && !nai.networkMisc.explicitlySelected) {
1983                        loge("ERROR: created network explicitly selected.");
1984                    }
1985                    nai.networkMisc.explicitlySelected = true;
1986                    nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
1987                    break;
1988                }
1989                case NetworkMonitor.EVENT_NETWORK_TESTED: {
1990                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1991                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1992                        final boolean valid =
1993                                (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1994                        final boolean validationChanged = (valid != nai.lastValidated);
1995                        nai.lastValidated = valid;
1996                        if (valid) {
1997                            if (DBG) log("Validated " + nai.name());
1998                            nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
1999                            if (!nai.everValidated) {
2000                                nai.everValidated = true;
2001                                rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
2002                                    ReapUnvalidatedNetworks.REAP);
2003                                // If score has changed, rebroadcast to NetworkFactories. b/17726566
2004                                sendUpdatedScoreToFactories(nai);
2005                            }
2006                        } else {
2007                            nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
2008                        }
2009                        updateInetCondition(nai);
2010                        // Let the NetworkAgent know the state of its network
2011                        nai.asyncChannel.sendMessage(
2012                                android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2013                                (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2014                                0, null);
2015
2016                        if (validationChanged) {
2017                            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
2018                        }
2019                    }
2020                    break;
2021                }
2022                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
2023                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2024                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2025                        handleLingerComplete(nai);
2026                    }
2027                    break;
2028                }
2029                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
2030                    if (msg.arg1 == 0) {
2031                        setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
2032                    } else {
2033                        final NetworkAgentInfo nai;
2034                        synchronized (mNetworkForNetId) {
2035                            nai = mNetworkForNetId.get(msg.arg2);
2036                        }
2037                        if (nai == null) {
2038                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2039                            break;
2040                        }
2041                        nai.captivePortalDetected = true;
2042                        setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2043                                nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
2044                    }
2045                    break;
2046                }
2047            }
2048        }
2049    }
2050
2051    // Cancel any lingering so the linger timeout doesn't teardown a network.
2052    // This should be called when a network begins satisfying a NetworkRequest.
2053    // Note: depending on what state the NetworkMonitor is in (e.g.,
2054    // if it's awaiting captive portal login, or if validation failed), this
2055    // may trigger a re-evaluation of the network.
2056    private void unlinger(NetworkAgentInfo nai) {
2057        if (VDBG) log("Canceling linger of " + nai.name());
2058        // If network has never been validated, it cannot have been lingered, so don't bother
2059        // needlessly triggering a re-evaluation.
2060        if (!nai.everValidated) return;
2061        nai.networkLingered.clear();
2062        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2063    }
2064
2065    private void handleAsyncChannelHalfConnect(Message msg) {
2066        AsyncChannel ac = (AsyncChannel) msg.obj;
2067        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2068            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2069                if (VDBG) log("NetworkFactory connected");
2070                // A network factory has connected.  Send it all current NetworkRequests.
2071                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2072                    if (nri.isRequest == false) continue;
2073                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2074                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2075                            (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
2076                }
2077            } else {
2078                loge("Error connecting NetworkFactory");
2079                mNetworkFactoryInfos.remove(msg.obj);
2080            }
2081        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2082            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2083                if (VDBG) log("NetworkAgent connected");
2084                // A network agent has requested a connection.  Establish the connection.
2085                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2086                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2087            } else {
2088                loge("Error connecting NetworkAgent");
2089                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2090                if (nai != null) {
2091                    final boolean wasDefault = isDefaultNetwork(nai);
2092                    synchronized (mNetworkForNetId) {
2093                        mNetworkForNetId.remove(nai.network.netId);
2094                        mNetIdInUse.delete(nai.network.netId);
2095                    }
2096                    // Just in case.
2097                    mLegacyTypeTracker.remove(nai, wasDefault);
2098                }
2099            }
2100        }
2101    }
2102
2103    private void handleAsyncChannelDisconnected(Message msg) {
2104        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2105        if (nai != null) {
2106            if (DBG) {
2107                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2108            }
2109            // A network agent has disconnected.
2110            if (nai.created) {
2111                // Tell netd to clean up the configuration for this network
2112                // (routing rules, DNS, etc).
2113                try {
2114                    mNetd.removeNetwork(nai.network.netId);
2115                } catch (Exception e) {
2116                    loge("Exception removing network: " + e);
2117                }
2118            }
2119            // TODO - if we move the logic to the network agent (have them disconnect
2120            // because they lost all their requests or because their score isn't good)
2121            // then they would disconnect organically, report their new state and then
2122            // disconnect the channel.
2123            if (nai.networkInfo.isConnected()) {
2124                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2125                        null, null);
2126            }
2127            final boolean wasDefault = isDefaultNetwork(nai);
2128            if (wasDefault) {
2129                mDefaultInetConditionPublished = 0;
2130            }
2131            notifyIfacesChanged();
2132            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2133            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2134            mNetworkAgentInfos.remove(msg.replyTo);
2135            updateClat(null, nai.linkProperties, nai);
2136            synchronized (mNetworkForNetId) {
2137                mNetworkForNetId.remove(nai.network.netId);
2138                mNetIdInUse.delete(nai.network.netId);
2139            }
2140            // Since we've lost the network, go through all the requests that
2141            // it was satisfying and see if any other factory can satisfy them.
2142            // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
2143            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
2144            for (int i = 0; i < nai.networkRequests.size(); i++) {
2145                NetworkRequest request = nai.networkRequests.valueAt(i);
2146                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2147                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2148                    if (DBG) {
2149                        log("Checking for replacement network to handle request " + request );
2150                    }
2151                    mNetworkForRequestId.remove(request.requestId);
2152                    sendUpdatedScoreToFactories(request, 0);
2153                    NetworkAgentInfo alternative = null;
2154                    for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2155                        if (existing.satisfies(request) &&
2156                                (alternative == null ||
2157                                 alternative.getCurrentScore() < existing.getCurrentScore())) {
2158                            alternative = existing;
2159                        }
2160                    }
2161                    if (alternative != null) {
2162                        if (DBG) log(" found replacement in " + alternative.name());
2163                        if (!toActivate.contains(alternative)) {
2164                            toActivate.add(alternative);
2165                        }
2166                    }
2167                }
2168            }
2169            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2170                removeDataActivityTracking(nai);
2171                notifyLockdownVpn(nai);
2172                requestNetworkTransitionWakelock(nai.name());
2173            }
2174            mLegacyTypeTracker.remove(nai, wasDefault);
2175            for (NetworkAgentInfo networkToActivate : toActivate) {
2176                unlinger(networkToActivate);
2177                rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2178                        ReapUnvalidatedNetworks.DONT_REAP);
2179            }
2180        }
2181        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2182        if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
2183    }
2184
2185    // If this method proves to be too slow then we can maintain a separate
2186    // pendingIntent => NetworkRequestInfo map.
2187    // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2188    private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2189        Intent intent = pendingIntent.getIntent();
2190        for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2191            PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2192            if (existingPendingIntent != null &&
2193                    existingPendingIntent.getIntent().filterEquals(intent)) {
2194                return entry.getValue();
2195            }
2196        }
2197        return null;
2198    }
2199
2200    private void handleRegisterNetworkRequestWithIntent(Message msg) {
2201        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2202
2203        NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2204        if (existingRequest != null) { // remove the existing request.
2205            if (DBG) log("Replacing " + existingRequest.request + " with "
2206                    + nri.request + " because their intents matched.");
2207            handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2208        }
2209        handleRegisterNetworkRequest(nri);
2210    }
2211
2212    private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
2213        mNetworkRequests.put(nri.request, nri);
2214
2215        // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2216
2217        // Check for the best currently alive network that satisfies this request
2218        NetworkAgentInfo bestNetwork = null;
2219        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2220            if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
2221            if (network.satisfies(nri.request)) {
2222                if (DBG) log("apparently satisfied.  currentScore=" + network.getCurrentScore());
2223                if (!nri.isRequest) {
2224                    // Not setting bestNetwork here as a listening NetworkRequest may be
2225                    // satisfied by multiple Networks.  Instead the request is added to
2226                    // each satisfying Network and notified about each.
2227                    network.addRequest(nri.request);
2228                    notifyNetworkCallback(network, nri);
2229                } else if (bestNetwork == null ||
2230                        bestNetwork.getCurrentScore() < network.getCurrentScore()) {
2231                    bestNetwork = network;
2232                }
2233            }
2234        }
2235        if (bestNetwork != null) {
2236            if (DBG) log("using " + bestNetwork.name());
2237            unlinger(bestNetwork);
2238            bestNetwork.addRequest(nri.request);
2239            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
2240            notifyNetworkCallback(bestNetwork, nri);
2241            if (nri.request.legacyType != TYPE_NONE) {
2242                mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2243            }
2244        }
2245
2246        if (nri.isRequest) {
2247            if (DBG) log("sending new NetworkRequest to factories");
2248            final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
2249            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2250                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
2251                        0, nri.request);
2252            }
2253        }
2254    }
2255
2256    private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2257            int callingUid) {
2258        NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2259        if (nri != null) {
2260            handleReleaseNetworkRequest(nri.request, callingUid);
2261        }
2262    }
2263
2264    // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2265    // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2266    // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2267    // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2268    private boolean unneeded(NetworkAgentInfo nai) {
2269        if (!nai.created || nai.isVPN()) return false;
2270        boolean unneeded = true;
2271        if (nai.everValidated) {
2272            for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2273                final NetworkRequest nr = nai.networkRequests.valueAt(i);
2274                try {
2275                    if (isRequest(nr)) unneeded = false;
2276                } catch (Exception e) {
2277                    loge("Request " + nr + " not found in mNetworkRequests.");
2278                    loge("  it came from request list  of " + nai.name());
2279                }
2280            }
2281        } else {
2282            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2283                // If this Network is already the highest scoring Network for a request, or if
2284                // there is hope for it to become one if it validated, then it is needed.
2285                if (nri.isRequest && nai.satisfies(nri.request) &&
2286                        (nai.networkRequests.get(nri.request.requestId) != null ||
2287                        // Note that this catches two important cases:
2288                        // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2289                        //    is currently satisfying the request.  This is desirable when
2290                        //    cellular ends up validating but WiFi does not.
2291                        // 2. Unvalidated WiFi will not be reaped when validated cellular
2292                        //    is currently satsifying the request.  This is desirable when
2293                        //    WiFi ends up validating and out scoring cellular.
2294                        mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2295                                nai.getCurrentScoreAsValidated())) {
2296                    unneeded = false;
2297                    break;
2298                }
2299            }
2300        }
2301        return unneeded;
2302    }
2303
2304    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2305        NetworkRequestInfo nri = mNetworkRequests.get(request);
2306        if (nri != null) {
2307            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2308                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2309                return;
2310            }
2311            if (DBG) log("releasing NetworkRequest " + request);
2312            nri.unlinkDeathRecipient();
2313            mNetworkRequests.remove(request);
2314            if (nri.isRequest) {
2315                // Find all networks that are satisfying this request and remove the request
2316                // from their request lists.
2317                // TODO - it's my understanding that for a request there is only a single
2318                // network satisfying it, so this loop is wasteful
2319                boolean wasKept = false;
2320                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2321                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2322                        nai.networkRequests.remove(nri.request.requestId);
2323                        if (DBG) {
2324                            log(" Removing from current network " + nai.name() +
2325                                    ", leaving " + nai.networkRequests.size() +
2326                                    " requests.");
2327                        }
2328                        if (unneeded(nai)) {
2329                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2330                            teardownUnneededNetwork(nai);
2331                        } else {
2332                            // suspect there should only be one pass through here
2333                            // but if any were kept do the check below
2334                            wasKept |= true;
2335                        }
2336                    }
2337                }
2338
2339                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2340                if (nai != null) {
2341                    mNetworkForRequestId.remove(nri.request.requestId);
2342                }
2343                // Maintain the illusion.  When this request arrived, we might have pretended
2344                // that a network connected to serve it, even though the network was already
2345                // connected.  Now that this request has gone away, we might have to pretend
2346                // that the network disconnected.  LegacyTypeTracker will generate that
2347                // phantom disconnect for this type.
2348                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2349                    boolean doRemove = true;
2350                    if (wasKept) {
2351                        // check if any of the remaining requests for this network are for the
2352                        // same legacy type - if so, don't remove the nai
2353                        for (int i = 0; i < nai.networkRequests.size(); i++) {
2354                            NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2355                            if (otherRequest.legacyType == nri.request.legacyType &&
2356                                    isRequest(otherRequest)) {
2357                                if (DBG) log(" still have other legacy request - leaving");
2358                                doRemove = false;
2359                            }
2360                        }
2361                    }
2362
2363                    if (doRemove) {
2364                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2365                    }
2366                }
2367
2368                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2369                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2370                            nri.request);
2371                }
2372            } else {
2373                // listens don't have a singular affectedNetwork.  Check all networks to see
2374                // if this listen request applies and remove it.
2375                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2376                    nai.networkRequests.remove(nri.request.requestId);
2377                }
2378            }
2379            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2380        }
2381    }
2382
2383    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2384        enforceConnectivityInternalPermission();
2385        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2386                accept ? 1 : 0, always ? 1: 0, network));
2387    }
2388
2389    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2390        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2391                " accept=" + accept + " always=" + always);
2392
2393        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2394        if (nai == null) {
2395            // Nothing to do.
2396            return;
2397        }
2398
2399        if (nai.everValidated) {
2400            // The network validated while the dialog box was up. Don't make any changes. There's a
2401            // TODO in the dialog code to make it go away if the network validates; once that's
2402            // implemented, taking action here will be confusing.
2403            return;
2404        }
2405
2406        if (!nai.networkMisc.explicitlySelected) {
2407            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2408        }
2409
2410        if (accept != nai.networkMisc.acceptUnvalidated) {
2411            int oldScore = nai.getCurrentScore();
2412            nai.networkMisc.acceptUnvalidated = accept;
2413            rematchAllNetworksAndRequests(nai, oldScore);
2414            sendUpdatedScoreToFactories(nai);
2415        }
2416
2417        if (always) {
2418            nai.asyncChannel.sendMessage(
2419                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2420        }
2421
2422        // TODO: should we also disconnect from the network if accept is false?
2423    }
2424
2425    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2426        mHandler.sendMessageDelayed(
2427                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2428                PROMPT_UNVALIDATED_DELAY_MS);
2429    }
2430
2431    private void handlePromptUnvalidated(Network network) {
2432        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2433
2434        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2435        // we haven't already been told to switch to it regardless of whether it validated or not.
2436        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2437        if (nai == null || nai.everValidated || nai.captivePortalDetected ||
2438                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2439            return;
2440        }
2441
2442        // TODO: What should we do if we've already switched to this network because we had no
2443        // better option? There are two obvious alternatives.
2444        //
2445        // 1. Decide that there's no point prompting because this is our only usable network.
2446        //    However, because we didn't prompt, if later on a validated network comes along, we'll
2447        //    either a) silently switch to it - bad if the user wanted to connect to stay on this
2448        //    unvalidated network - or b) prompt the user at that later time - bad because the user
2449        //    might not understand why they are now being prompted.
2450        //
2451        // 2. Always prompt the user, even if we have no other network to use. The user could then
2452        //    try to find an alternative network to join (remember, if we got here, then the user
2453        //    selected this network manually). This is bad because the prompt isn't really very
2454        //    useful.
2455        //
2456        // For now we do #1, but we can revisit that later.
2457        if (isDefaultNetwork(nai)) {
2458            return;
2459        }
2460
2461        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2462        intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2463        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2464        intent.setClassName("com.android.settings",
2465                "com.android.settings.wifi.WifiNoInternetDialog");
2466        mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2467    }
2468
2469    private class InternalHandler extends Handler {
2470        public InternalHandler(Looper looper) {
2471            super(looper);
2472        }
2473
2474        @Override
2475        public void handleMessage(Message msg) {
2476            switch (msg.what) {
2477                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2478                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2479                    String causedBy = null;
2480                    synchronized (ConnectivityService.this) {
2481                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2482                                mNetTransitionWakeLock.isHeld()) {
2483                            mNetTransitionWakeLock.release();
2484                            causedBy = mNetTransitionWakeLockCausedBy;
2485                        } else {
2486                            break;
2487                        }
2488                    }
2489                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2490                        log("Failed to find a new network - expiring NetTransition Wakelock");
2491                    } else {
2492                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2493                                " cleared because we found a replacement network");
2494                    }
2495                    break;
2496                }
2497                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2498                    handleDeprecatedGlobalHttpProxy();
2499                    break;
2500                }
2501                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
2502                    Intent intent = (Intent)msg.obj;
2503                    sendStickyBroadcast(intent);
2504                    break;
2505                }
2506                case EVENT_PROXY_HAS_CHANGED: {
2507                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2508                    break;
2509                }
2510                case EVENT_REGISTER_NETWORK_FACTORY: {
2511                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2512                    break;
2513                }
2514                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2515                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2516                    break;
2517                }
2518                case EVENT_REGISTER_NETWORK_AGENT: {
2519                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2520                    break;
2521                }
2522                case EVENT_REGISTER_NETWORK_REQUEST:
2523                case EVENT_REGISTER_NETWORK_LISTENER: {
2524                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2525                    break;
2526                }
2527                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2528                    handleRegisterNetworkRequestWithIntent(msg);
2529                    break;
2530                }
2531                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2532                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2533                    break;
2534                }
2535                case EVENT_RELEASE_NETWORK_REQUEST: {
2536                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2537                    break;
2538                }
2539                case EVENT_SET_ACCEPT_UNVALIDATED: {
2540                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2541                    break;
2542                }
2543                case EVENT_PROMPT_UNVALIDATED: {
2544                    handlePromptUnvalidated((Network) msg.obj);
2545                    break;
2546                }
2547                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2548                    handleMobileDataAlwaysOn();
2549                    break;
2550                }
2551                case EVENT_SYSTEM_READY: {
2552                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2553                        nai.networkMonitor.systemReady = true;
2554                    }
2555                    break;
2556                }
2557            }
2558        }
2559    }
2560
2561    // javadoc from interface
2562    public int tether(String iface) {
2563        ConnectivityManager.enforceTetherChangePermission(mContext);
2564        if (isTetheringSupported()) {
2565            return mTethering.tether(iface);
2566        } else {
2567            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2568        }
2569    }
2570
2571    // javadoc from interface
2572    public int untether(String iface) {
2573        ConnectivityManager.enforceTetherChangePermission(mContext);
2574
2575        if (isTetheringSupported()) {
2576            return mTethering.untether(iface);
2577        } else {
2578            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2579        }
2580    }
2581
2582    // javadoc from interface
2583    public int getLastTetherError(String iface) {
2584        enforceTetherAccessPermission();
2585
2586        if (isTetheringSupported()) {
2587            return mTethering.getLastTetherError(iface);
2588        } else {
2589            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2590        }
2591    }
2592
2593    // TODO - proper iface API for selection by property, inspection, etc
2594    public String[] getTetherableUsbRegexs() {
2595        enforceTetherAccessPermission();
2596        if (isTetheringSupported()) {
2597            return mTethering.getTetherableUsbRegexs();
2598        } else {
2599            return new String[0];
2600        }
2601    }
2602
2603    public String[] getTetherableWifiRegexs() {
2604        enforceTetherAccessPermission();
2605        if (isTetheringSupported()) {
2606            return mTethering.getTetherableWifiRegexs();
2607        } else {
2608            return new String[0];
2609        }
2610    }
2611
2612    public String[] getTetherableBluetoothRegexs() {
2613        enforceTetherAccessPermission();
2614        if (isTetheringSupported()) {
2615            return mTethering.getTetherableBluetoothRegexs();
2616        } else {
2617            return new String[0];
2618        }
2619    }
2620
2621    public int setUsbTethering(boolean enable) {
2622        ConnectivityManager.enforceTetherChangePermission(mContext);
2623        if (isTetheringSupported()) {
2624            return mTethering.setUsbTethering(enable);
2625        } else {
2626            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2627        }
2628    }
2629
2630    // TODO - move iface listing, queries, etc to new module
2631    // javadoc from interface
2632    public String[] getTetherableIfaces() {
2633        enforceTetherAccessPermission();
2634        return mTethering.getTetherableIfaces();
2635    }
2636
2637    public String[] getTetheredIfaces() {
2638        enforceTetherAccessPermission();
2639        return mTethering.getTetheredIfaces();
2640    }
2641
2642    public String[] getTetheringErroredIfaces() {
2643        enforceTetherAccessPermission();
2644        return mTethering.getErroredIfaces();
2645    }
2646
2647    public String[] getTetheredDhcpRanges() {
2648        enforceConnectivityInternalPermission();
2649        return mTethering.getTetheredDhcpRanges();
2650    }
2651
2652    // if ro.tether.denied = true we default to no tethering
2653    // gservices could set the secure setting to 1 though to enable it on a build where it
2654    // had previously been turned off.
2655    public boolean isTetheringSupported() {
2656        enforceTetherAccessPermission();
2657        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2658        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2659                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2660                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2661        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2662                mTethering.getTetherableWifiRegexs().length != 0 ||
2663                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2664                mTethering.getUpstreamIfaceTypes().length != 0);
2665    }
2666
2667    // Called when we lose the default network and have no replacement yet.
2668    // This will automatically be cleared after X seconds or a new default network
2669    // becomes CONNECTED, whichever happens first.  The timer is started by the
2670    // first caller and not restarted by subsequent callers.
2671    private void requestNetworkTransitionWakelock(String forWhom) {
2672        int serialNum = 0;
2673        synchronized (this) {
2674            if (mNetTransitionWakeLock.isHeld()) return;
2675            serialNum = ++mNetTransitionWakeLockSerialNumber;
2676            mNetTransitionWakeLock.acquire();
2677            mNetTransitionWakeLockCausedBy = forWhom;
2678        }
2679        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2680                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2681                mNetTransitionWakeLockTimeout);
2682        return;
2683    }
2684
2685    // 100 percent is full good, 0 is full bad.
2686    public void reportInetCondition(int networkType, int percentage) {
2687        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2688        if (nai == null) return;
2689        reportNetworkConnectivity(nai.network, percentage > 50);
2690    }
2691
2692    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2693        enforceAccessPermission();
2694        enforceInternetPermission();
2695
2696        NetworkAgentInfo nai;
2697        if (network == null) {
2698            nai = getDefaultNetwork();
2699        } else {
2700            nai = getNetworkAgentInfoForNetwork(network);
2701        }
2702        if (nai == null) return;
2703        // Revalidate if the app report does not match our current validated state.
2704        if (hasConnectivity == nai.lastValidated) return;
2705        final int uid = Binder.getCallingUid();
2706        if (DBG) {
2707            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2708                    ") by " + uid);
2709        }
2710        synchronized (nai) {
2711            // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2712            // which isn't meant to work on uncreated networks.
2713            if (!nai.created) return;
2714
2715            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
2716
2717            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2718        }
2719    }
2720
2721    public void captivePortalAppResponse(Network network, int response, String actionToken) {
2722        if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2723            enforceConnectivityInternalPermission();
2724        }
2725        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2726        if (nai == null) return;
2727        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2728                actionToken);
2729    }
2730
2731    private ProxyInfo getDefaultProxy() {
2732        // this information is already available as a world read/writable jvm property
2733        // so this API change wouldn't have a benifit.  It also breaks the passing
2734        // of proxy info to all the JVMs.
2735        // enforceAccessPermission();
2736        synchronized (mProxyLock) {
2737            ProxyInfo ret = mGlobalProxy;
2738            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2739            return ret;
2740        }
2741    }
2742
2743    public ProxyInfo getProxyForNetwork(Network network) {
2744        if (network == null) return getDefaultProxy();
2745        final ProxyInfo globalProxy = getGlobalProxy();
2746        if (globalProxy != null) return globalProxy;
2747        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2748        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2749        // caller may not have.
2750        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2751        if (nai == null) return null;
2752        synchronized (nai) {
2753            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2754            if (proxyInfo == null) return null;
2755            return new ProxyInfo(proxyInfo);
2756        }
2757    }
2758
2759    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2760    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2761    // proxy is null then there is no proxy in place).
2762    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2763        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2764                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2765            proxy = null;
2766        }
2767        return proxy;
2768    }
2769
2770    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2771    // better for determining if a new proxy broadcast is necessary:
2772    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2773    //    avoid unnecessary broadcasts.
2774    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2775    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2776    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2777    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2778    //    all set.
2779    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2780        a = canonicalizeProxyInfo(a);
2781        b = canonicalizeProxyInfo(b);
2782        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2783        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2784        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2785    }
2786
2787    public void setGlobalProxy(ProxyInfo proxyProperties) {
2788        enforceConnectivityInternalPermission();
2789
2790        synchronized (mProxyLock) {
2791            if (proxyProperties == mGlobalProxy) return;
2792            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2793            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2794
2795            String host = "";
2796            int port = 0;
2797            String exclList = "";
2798            String pacFileUrl = "";
2799            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2800                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2801                if (!proxyProperties.isValid()) {
2802                    if (DBG)
2803                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2804                    return;
2805                }
2806                mGlobalProxy = new ProxyInfo(proxyProperties);
2807                host = mGlobalProxy.getHost();
2808                port = mGlobalProxy.getPort();
2809                exclList = mGlobalProxy.getExclusionListAsString();
2810                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2811                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2812                }
2813            } else {
2814                mGlobalProxy = null;
2815            }
2816            ContentResolver res = mContext.getContentResolver();
2817            final long token = Binder.clearCallingIdentity();
2818            try {
2819                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2820                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2821                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2822                        exclList);
2823                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2824            } finally {
2825                Binder.restoreCallingIdentity(token);
2826            }
2827
2828            if (mGlobalProxy == null) {
2829                proxyProperties = mDefaultProxy;
2830            }
2831            sendProxyBroadcast(proxyProperties);
2832        }
2833    }
2834
2835    private void loadGlobalProxy() {
2836        ContentResolver res = mContext.getContentResolver();
2837        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2838        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2839        String exclList = Settings.Global.getString(res,
2840                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2841        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2842        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2843            ProxyInfo proxyProperties;
2844            if (!TextUtils.isEmpty(pacFileUrl)) {
2845                proxyProperties = new ProxyInfo(pacFileUrl);
2846            } else {
2847                proxyProperties = new ProxyInfo(host, port, exclList);
2848            }
2849            if (!proxyProperties.isValid()) {
2850                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2851                return;
2852            }
2853
2854            synchronized (mProxyLock) {
2855                mGlobalProxy = proxyProperties;
2856            }
2857        }
2858    }
2859
2860    public ProxyInfo getGlobalProxy() {
2861        // this information is already available as a world read/writable jvm property
2862        // so this API change wouldn't have a benifit.  It also breaks the passing
2863        // of proxy info to all the JVMs.
2864        // enforceAccessPermission();
2865        synchronized (mProxyLock) {
2866            return mGlobalProxy;
2867        }
2868    }
2869
2870    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2871        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2872                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2873            proxy = null;
2874        }
2875        synchronized (mProxyLock) {
2876            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2877            if (mDefaultProxy == proxy) return; // catches repeated nulls
2878            if (proxy != null &&  !proxy.isValid()) {
2879                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2880                return;
2881            }
2882
2883            // This call could be coming from the PacManager, containing the port of the local
2884            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2885            // global (to get the correct local port), and send a broadcast.
2886            // TODO: Switch PacManager to have its own message to send back rather than
2887            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2888            if ((mGlobalProxy != null) && (proxy != null)
2889                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2890                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2891                mGlobalProxy = proxy;
2892                sendProxyBroadcast(mGlobalProxy);
2893                return;
2894            }
2895            mDefaultProxy = proxy;
2896
2897            if (mGlobalProxy != null) return;
2898            if (!mDefaultProxyDisabled) {
2899                sendProxyBroadcast(proxy);
2900            }
2901        }
2902    }
2903
2904    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2905    // This method gets called when any network changes proxy, but the broadcast only ever contains
2906    // the default proxy (even if it hasn't changed).
2907    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2908    // world where an app might be bound to a non-default network.
2909    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2910        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2911        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2912
2913        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2914            sendProxyBroadcast(getDefaultProxy());
2915        }
2916    }
2917
2918    private void handleDeprecatedGlobalHttpProxy() {
2919        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2920                Settings.Global.HTTP_PROXY);
2921        if (!TextUtils.isEmpty(proxy)) {
2922            String data[] = proxy.split(":");
2923            if (data.length == 0) {
2924                return;
2925            }
2926
2927            String proxyHost =  data[0];
2928            int proxyPort = 8080;
2929            if (data.length > 1) {
2930                try {
2931                    proxyPort = Integer.parseInt(data[1]);
2932                } catch (NumberFormatException e) {
2933                    return;
2934                }
2935            }
2936            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2937            setGlobalProxy(p);
2938        }
2939    }
2940
2941    private void sendProxyBroadcast(ProxyInfo proxy) {
2942        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2943        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2944        if (DBG) log("sending Proxy Broadcast for " + proxy);
2945        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2946        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2947            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2948        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2949        final long ident = Binder.clearCallingIdentity();
2950        try {
2951            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2952        } finally {
2953            Binder.restoreCallingIdentity(ident);
2954        }
2955    }
2956
2957    private static class SettingsObserver extends ContentObserver {
2958        final private HashMap<Uri, Integer> mUriEventMap;
2959        final private Context mContext;
2960        final private Handler mHandler;
2961
2962        SettingsObserver(Context context, Handler handler) {
2963            super(null);
2964            mUriEventMap = new HashMap<Uri, Integer>();
2965            mContext = context;
2966            mHandler = handler;
2967        }
2968
2969        void observe(Uri uri, int what) {
2970            mUriEventMap.put(uri, what);
2971            final ContentResolver resolver = mContext.getContentResolver();
2972            resolver.registerContentObserver(uri, false, this);
2973        }
2974
2975        @Override
2976        public void onChange(boolean selfChange) {
2977            Slog.wtf(TAG, "Should never be reached.");
2978        }
2979
2980        @Override
2981        public void onChange(boolean selfChange, Uri uri) {
2982            final Integer what = mUriEventMap.get(uri);
2983            if (what != null) {
2984                mHandler.obtainMessage(what.intValue()).sendToTarget();
2985            } else {
2986                loge("No matching event to send for URI=" + uri);
2987            }
2988        }
2989    }
2990
2991    private static void log(String s) {
2992        Slog.d(TAG, s);
2993    }
2994
2995    private static void loge(String s) {
2996        Slog.e(TAG, s);
2997    }
2998
2999    private static <T> T checkNotNull(T value, String message) {
3000        if (value == null) {
3001            throw new NullPointerException(message);
3002        }
3003        return value;
3004    }
3005
3006    /**
3007     * Prepare for a VPN application.
3008     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3009     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3010     *
3011     * @param oldPackage Package name of the application which currently controls VPN, which will
3012     *                   be replaced. If there is no such application, this should should either be
3013     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3014     * @param newPackage Package name of the application which should gain control of VPN, or
3015     *                   {@code null} to disable.
3016     * @param userId User for whom to prepare the new VPN.
3017     *
3018     * @hide
3019     */
3020    @Override
3021    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3022            int userId) {
3023        enforceCrossUserPermission(userId);
3024        throwIfLockdownEnabled();
3025
3026        synchronized(mVpns) {
3027            Vpn vpn = mVpns.get(userId);
3028            if (vpn != null) {
3029                return vpn.prepare(oldPackage, newPackage);
3030            } else {
3031                return false;
3032            }
3033        }
3034    }
3035
3036    /**
3037     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3038     * This method is used by system-privileged apps.
3039     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3040     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3041     *
3042     * @param packageName The package for which authorization state should change.
3043     * @param userId User for whom {@code packageName} is installed.
3044     * @param authorized {@code true} if this app should be able to start a VPN connection without
3045     *                   explicit user approval, {@code false} if not.
3046     *
3047     * @hide
3048     */
3049    @Override
3050    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3051        enforceCrossUserPermission(userId);
3052
3053        synchronized(mVpns) {
3054            Vpn vpn = mVpns.get(userId);
3055            if (vpn != null) {
3056                vpn.setPackageAuthorization(packageName, authorized);
3057            }
3058        }
3059    }
3060
3061    /**
3062     * Configure a TUN interface and return its file descriptor. Parameters
3063     * are encoded and opaque to this class. This method is used by VpnBuilder
3064     * and not available in ConnectivityManager. Permissions are checked in
3065     * Vpn class.
3066     * @hide
3067     */
3068    @Override
3069    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3070        throwIfLockdownEnabled();
3071        int user = UserHandle.getUserId(Binder.getCallingUid());
3072        synchronized(mVpns) {
3073            return mVpns.get(user).establish(config);
3074        }
3075    }
3076
3077    /**
3078     * Start legacy VPN, controlling native daemons as needed. Creates a
3079     * secondary thread to perform connection work, returning quickly.
3080     */
3081    @Override
3082    public void startLegacyVpn(VpnProfile profile) {
3083        throwIfLockdownEnabled();
3084        final LinkProperties egress = getActiveLinkProperties();
3085        if (egress == null) {
3086            throw new IllegalStateException("Missing active network connection");
3087        }
3088        int user = UserHandle.getUserId(Binder.getCallingUid());
3089        synchronized(mVpns) {
3090            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3091        }
3092    }
3093
3094    /**
3095     * Return the information of the ongoing legacy VPN. This method is used
3096     * by VpnSettings and not available in ConnectivityManager. Permissions
3097     * are checked in Vpn class.
3098     */
3099    @Override
3100    public LegacyVpnInfo getLegacyVpnInfo() {
3101        throwIfLockdownEnabled();
3102        int user = UserHandle.getUserId(Binder.getCallingUid());
3103        synchronized(mVpns) {
3104            return mVpns.get(user).getLegacyVpnInfo();
3105        }
3106    }
3107
3108    /**
3109     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3110     * and not available in ConnectivityManager.
3111     */
3112    @Override
3113    public VpnInfo[] getAllVpnInfo() {
3114        enforceConnectivityInternalPermission();
3115        if (mLockdownEnabled) {
3116            return new VpnInfo[0];
3117        }
3118
3119        synchronized(mVpns) {
3120            List<VpnInfo> infoList = new ArrayList<>();
3121            for (int i = 0; i < mVpns.size(); i++) {
3122                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3123                if (info != null) {
3124                    infoList.add(info);
3125                }
3126            }
3127            return infoList.toArray(new VpnInfo[infoList.size()]);
3128        }
3129    }
3130
3131    /**
3132     * @return VPN information for accounting, or null if we can't retrieve all required
3133     *         information, e.g primary underlying iface.
3134     */
3135    @Nullable
3136    private VpnInfo createVpnInfo(Vpn vpn) {
3137        VpnInfo info = vpn.getVpnInfo();
3138        if (info == null) {
3139            return null;
3140        }
3141        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3142        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3143        // the underlyingNetworks list.
3144        if (underlyingNetworks == null) {
3145            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3146            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3147                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3148            }
3149        } else if (underlyingNetworks.length > 0) {
3150            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3151            if (linkProperties != null) {
3152                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3153            }
3154        }
3155        return info.primaryUnderlyingIface == null ? null : info;
3156    }
3157
3158    /**
3159     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3160     * VpnDialogs and not available in ConnectivityManager.
3161     * Permissions are checked in Vpn class.
3162     * @hide
3163     */
3164    @Override
3165    public VpnConfig getVpnConfig(int userId) {
3166        enforceCrossUserPermission(userId);
3167        synchronized(mVpns) {
3168            Vpn vpn = mVpns.get(userId);
3169            if (vpn != null) {
3170                return vpn.getVpnConfig();
3171            } else {
3172                return null;
3173            }
3174        }
3175    }
3176
3177    @Override
3178    public boolean updateLockdownVpn() {
3179        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3180            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3181            return false;
3182        }
3183
3184        // Tear down existing lockdown if profile was removed
3185        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3186        if (mLockdownEnabled) {
3187            if (!mKeyStore.isUnlocked()) {
3188                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3189                return false;
3190            }
3191
3192            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3193            final VpnProfile profile = VpnProfile.decode(
3194                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3195            int user = UserHandle.getUserId(Binder.getCallingUid());
3196            synchronized(mVpns) {
3197                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3198                            profile));
3199            }
3200        } else {
3201            setLockdownTracker(null);
3202        }
3203
3204        return true;
3205    }
3206
3207    /**
3208     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3209     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3210     */
3211    private void setLockdownTracker(LockdownVpnTracker tracker) {
3212        // Shutdown any existing tracker
3213        final LockdownVpnTracker existing = mLockdownTracker;
3214        mLockdownTracker = null;
3215        if (existing != null) {
3216            existing.shutdown();
3217        }
3218
3219        try {
3220            if (tracker != null) {
3221                mNetd.setFirewallEnabled(true);
3222                mNetd.setFirewallInterfaceRule("lo", true);
3223                mLockdownTracker = tracker;
3224                mLockdownTracker.init();
3225            } else {
3226                mNetd.setFirewallEnabled(false);
3227            }
3228        } catch (RemoteException e) {
3229            // ignored; NMS lives inside system_server
3230        }
3231    }
3232
3233    private void throwIfLockdownEnabled() {
3234        if (mLockdownEnabled) {
3235            throw new IllegalStateException("Unavailable in lockdown mode");
3236        }
3237    }
3238
3239    @Override
3240    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3241        // TODO: Remove?  Any reason to trigger a provisioning check?
3242        return -1;
3243    }
3244
3245    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3246    private volatile boolean mIsNotificationVisible = false;
3247
3248    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3249        if (DBG) {
3250            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3251                + " action=" + action);
3252        }
3253        Intent intent = new Intent(action);
3254        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3255        // Concatenate the range of types onto the range of NetIDs.
3256        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3257        setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
3258    }
3259
3260    /**
3261     * Show or hide network provisioning notificaitons.
3262     *
3263     * @param id an identifier that uniquely identifies this notification.  This must match
3264     *         between show and hide calls.  We use the NetID value but for legacy callers
3265     *         we concatenate the range of types with the range of NetIDs.
3266     */
3267    private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
3268            String extraInfo, PendingIntent intent) {
3269        if (DBG) {
3270            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3271                networkType + " extraInfo=" + extraInfo);
3272        }
3273
3274        Resources r = Resources.getSystem();
3275        NotificationManager notificationManager = (NotificationManager) mContext
3276            .getSystemService(Context.NOTIFICATION_SERVICE);
3277
3278        if (visible) {
3279            CharSequence title;
3280            CharSequence details;
3281            int icon;
3282            Notification notification = new Notification();
3283            switch (networkType) {
3284                case ConnectivityManager.TYPE_WIFI:
3285                    title = r.getString(R.string.wifi_available_sign_in, 0);
3286                    details = r.getString(R.string.network_available_sign_in_detailed,
3287                            extraInfo);
3288                    icon = R.drawable.stat_notify_wifi_in_range;
3289                    break;
3290                case ConnectivityManager.TYPE_MOBILE:
3291                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3292                    title = r.getString(R.string.network_available_sign_in, 0);
3293                    // TODO: Change this to pull from NetworkInfo once a printable
3294                    // name has been added to it
3295                    details = mTelephonyManager.getNetworkOperatorName();
3296                    icon = R.drawable.stat_notify_rssi_in_range;
3297                    break;
3298                default:
3299                    title = r.getString(R.string.network_available_sign_in, 0);
3300                    details = r.getString(R.string.network_available_sign_in_detailed,
3301                            extraInfo);
3302                    icon = R.drawable.stat_notify_rssi_in_range;
3303                    break;
3304            }
3305
3306            notification.when = 0;
3307            notification.icon = icon;
3308            notification.flags = Notification.FLAG_AUTO_CANCEL;
3309            notification.tickerText = title;
3310            notification.color = mContext.getColor(
3311                    com.android.internal.R.color.system_notification_accent_color);
3312            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3313            notification.contentIntent = intent;
3314
3315            try {
3316                notificationManager.notify(NOTIFICATION_ID, id, notification);
3317            } catch (NullPointerException npe) {
3318                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3319                npe.printStackTrace();
3320            }
3321        } else {
3322            try {
3323                notificationManager.cancel(NOTIFICATION_ID, id);
3324            } catch (NullPointerException npe) {
3325                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3326                npe.printStackTrace();
3327            }
3328        }
3329        mIsNotificationVisible = visible;
3330    }
3331
3332    /** Location to an updatable file listing carrier provisioning urls.
3333     *  An example:
3334     *
3335     * <?xml version="1.0" encoding="utf-8"?>
3336     *  <provisioningUrls>
3337     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3338     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3339     *  </provisioningUrls>
3340     */
3341    private static final String PROVISIONING_URL_PATH =
3342            "/data/misc/radio/provisioning_urls.xml";
3343    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3344
3345    /** XML tag for root element. */
3346    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3347    /** XML tag for individual url */
3348    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3349    /** XML tag for redirected url */
3350    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3351    /** XML attribute for mcc */
3352    private static final String ATTR_MCC = "mcc";
3353    /** XML attribute for mnc */
3354    private static final String ATTR_MNC = "mnc";
3355
3356    private static final int REDIRECTED_PROVISIONING = 1;
3357    private static final int PROVISIONING = 2;
3358
3359    private String getProvisioningUrlBaseFromFile(int type) {
3360        FileReader fileReader = null;
3361        XmlPullParser parser = null;
3362        Configuration config = mContext.getResources().getConfiguration();
3363        String tagType;
3364
3365        switch (type) {
3366            case PROVISIONING:
3367                tagType = TAG_PROVISIONING_URL;
3368                break;
3369            case REDIRECTED_PROVISIONING:
3370                tagType = TAG_REDIRECTED_URL;
3371                break;
3372            default:
3373                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3374                        type);
3375        }
3376
3377        try {
3378            fileReader = new FileReader(mProvisioningUrlFile);
3379            parser = Xml.newPullParser();
3380            parser.setInput(fileReader);
3381            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3382
3383            while (true) {
3384                XmlUtils.nextElement(parser);
3385
3386                String element = parser.getName();
3387                if (element == null) break;
3388
3389                if (element.equals(tagType)) {
3390                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3391                    try {
3392                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3393                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3394                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3395                                parser.next();
3396                                if (parser.getEventType() == XmlPullParser.TEXT) {
3397                                    return parser.getText();
3398                                }
3399                            }
3400                        }
3401                    } catch (NumberFormatException e) {
3402                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3403                    }
3404                }
3405            }
3406            return null;
3407        } catch (FileNotFoundException e) {
3408            loge("Carrier Provisioning Urls file not found");
3409        } catch (XmlPullParserException e) {
3410            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3411        } catch (IOException e) {
3412            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3413        } finally {
3414            if (fileReader != null) {
3415                try {
3416                    fileReader.close();
3417                } catch (IOException e) {}
3418            }
3419        }
3420        return null;
3421    }
3422
3423    @Override
3424    public String getMobileRedirectedProvisioningUrl() {
3425        enforceConnectivityInternalPermission();
3426        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3427        if (TextUtils.isEmpty(url)) {
3428            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3429        }
3430        return url;
3431    }
3432
3433    @Override
3434    public String getMobileProvisioningUrl() {
3435        enforceConnectivityInternalPermission();
3436        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3437        if (TextUtils.isEmpty(url)) {
3438            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3439            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3440        } else {
3441            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3442        }
3443        // populate the iccid, imei and phone number in the provisioning url.
3444        if (!TextUtils.isEmpty(url)) {
3445            String phoneNumber = mTelephonyManager.getLine1Number();
3446            if (TextUtils.isEmpty(phoneNumber)) {
3447                phoneNumber = "0000000000";
3448            }
3449            url = String.format(url,
3450                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3451                    mTelephonyManager.getDeviceId() /* IMEI */,
3452                    phoneNumber /* Phone numer */);
3453        }
3454
3455        return url;
3456    }
3457
3458    @Override
3459    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3460            String action) {
3461        enforceConnectivityInternalPermission();
3462        final long ident = Binder.clearCallingIdentity();
3463        try {
3464            setProvNotificationVisible(visible, networkType, action);
3465        } finally {
3466            Binder.restoreCallingIdentity(ident);
3467        }
3468    }
3469
3470    @Override
3471    public void setAirplaneMode(boolean enable) {
3472        enforceConnectivityInternalPermission();
3473        final long ident = Binder.clearCallingIdentity();
3474        try {
3475            final ContentResolver cr = mContext.getContentResolver();
3476            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3477            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3478            intent.putExtra("state", enable);
3479            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3480        } finally {
3481            Binder.restoreCallingIdentity(ident);
3482        }
3483    }
3484
3485    private void onUserStart(int userId) {
3486        synchronized(mVpns) {
3487            Vpn userVpn = mVpns.get(userId);
3488            if (userVpn != null) {
3489                loge("Starting user already has a VPN");
3490                return;
3491            }
3492            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3493            mVpns.put(userId, userVpn);
3494        }
3495    }
3496
3497    private void onUserStop(int userId) {
3498        synchronized(mVpns) {
3499            Vpn userVpn = mVpns.get(userId);
3500            if (userVpn == null) {
3501                loge("Stopping user has no VPN");
3502                return;
3503            }
3504            mVpns.delete(userId);
3505        }
3506    }
3507
3508    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3509        @Override
3510        public void onReceive(Context context, Intent intent) {
3511            final String action = intent.getAction();
3512            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3513            if (userId == UserHandle.USER_NULL) return;
3514
3515            if (Intent.ACTION_USER_STARTING.equals(action)) {
3516                onUserStart(userId);
3517            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3518                onUserStop(userId);
3519            }
3520        }
3521    };
3522
3523    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3524            new HashMap<Messenger, NetworkFactoryInfo>();
3525    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3526            new HashMap<NetworkRequest, NetworkRequestInfo>();
3527
3528    private static class NetworkFactoryInfo {
3529        public final String name;
3530        public final Messenger messenger;
3531        public final AsyncChannel asyncChannel;
3532
3533        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3534            this.name = name;
3535            this.messenger = messenger;
3536            this.asyncChannel = asyncChannel;
3537        }
3538    }
3539
3540    /**
3541     * Tracks info about the requester.
3542     * Also used to notice when the calling process dies so we can self-expire
3543     */
3544    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3545        static final boolean REQUEST = true;
3546        static final boolean LISTEN = false;
3547
3548        final NetworkRequest request;
3549        final PendingIntent mPendingIntent;
3550        boolean mPendingIntentSent;
3551        private final IBinder mBinder;
3552        final int mPid;
3553        final int mUid;
3554        final Messenger messenger;
3555        final boolean isRequest;
3556
3557        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3558            request = r;
3559            mPendingIntent = pi;
3560            messenger = null;
3561            mBinder = null;
3562            mPid = getCallingPid();
3563            mUid = getCallingUid();
3564            this.isRequest = isRequest;
3565        }
3566
3567        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3568            super();
3569            messenger = m;
3570            request = r;
3571            mBinder = binder;
3572            mPid = getCallingPid();
3573            mUid = getCallingUid();
3574            this.isRequest = isRequest;
3575            mPendingIntent = null;
3576
3577            try {
3578                mBinder.linkToDeath(this, 0);
3579            } catch (RemoteException e) {
3580                binderDied();
3581            }
3582        }
3583
3584        void unlinkDeathRecipient() {
3585            if (mBinder != null) {
3586                mBinder.unlinkToDeath(this, 0);
3587            }
3588        }
3589
3590        public void binderDied() {
3591            log("ConnectivityService NetworkRequestInfo binderDied(" +
3592                    request + ", " + mBinder + ")");
3593            releaseNetworkRequest(request);
3594        }
3595
3596        public String toString() {
3597            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
3598                    mPid + " for " + request +
3599                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3600        }
3601    }
3602
3603    @Override
3604    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3605            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3606        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3607        enforceNetworkRequestPermissions(networkCapabilities);
3608        enforceMeteredApnPolicy(networkCapabilities);
3609
3610        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3611            throw new IllegalArgumentException("Bad timeout specified");
3612        }
3613
3614        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3615                nextNetworkRequestId());
3616        if (DBG) log("requestNetwork for " + networkRequest);
3617        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3618                NetworkRequestInfo.REQUEST);
3619
3620        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3621        if (timeoutMs > 0) {
3622            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3623                    nri), timeoutMs);
3624        }
3625        return networkRequest;
3626    }
3627
3628    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3629        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3630            enforceConnectivityInternalPermission();
3631        } else {
3632            enforceChangePermission();
3633        }
3634    }
3635
3636    @Override
3637    public boolean requestBandwidthUpdate(Network network) {
3638        enforceAccessPermission();
3639        NetworkAgentInfo nai = null;
3640        if (network == null) {
3641            return false;
3642        }
3643        synchronized (mNetworkForNetId) {
3644            nai = mNetworkForNetId.get(network.netId);
3645        }
3646        if (nai != null) {
3647            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3648            return true;
3649        }
3650        return false;
3651    }
3652
3653
3654    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3655        // if UID is restricted, don't allow them to bring up metered APNs
3656        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3657            final int uidRules;
3658            final int uid = Binder.getCallingUid();
3659            synchronized(mRulesLock) {
3660                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3661            }
3662            if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
3663                // we could silently fail or we can filter the available nets to only give
3664                // them those they have access to.  Chose the more useful
3665                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3666            }
3667        }
3668    }
3669
3670    @Override
3671    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3672            PendingIntent operation) {
3673        checkNotNull(operation, "PendingIntent cannot be null.");
3674        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3675        enforceNetworkRequestPermissions(networkCapabilities);
3676        enforceMeteredApnPolicy(networkCapabilities);
3677
3678        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3679                nextNetworkRequestId());
3680        if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3681        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3682                NetworkRequestInfo.REQUEST);
3683        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3684                nri));
3685        return networkRequest;
3686    }
3687
3688    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3689        mHandler.sendMessageDelayed(
3690                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3691                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3692    }
3693
3694    @Override
3695    public void releasePendingNetworkRequest(PendingIntent operation) {
3696        checkNotNull(operation, "PendingIntent cannot be null.");
3697        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3698                getCallingUid(), 0, operation));
3699    }
3700
3701    // In order to implement the compatibility measure for pre-M apps that call
3702    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3703    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3704    // This ensures it has permission to do so.
3705    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3706        if (nc == null) {
3707            return false;
3708        }
3709        int[] transportTypes = nc.getTransportTypes();
3710        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3711            return false;
3712        }
3713        try {
3714            mContext.enforceCallingOrSelfPermission(
3715                    android.Manifest.permission.ACCESS_WIFI_STATE,
3716                    "ConnectivityService");
3717        } catch (SecurityException e) {
3718            return false;
3719        }
3720        return true;
3721    }
3722
3723    @Override
3724    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3725            Messenger messenger, IBinder binder) {
3726        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3727            enforceAccessPermission();
3728        }
3729
3730        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3731                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3732        if (DBG) log("listenForNetwork for " + networkRequest);
3733        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3734                NetworkRequestInfo.LISTEN);
3735
3736        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3737        return networkRequest;
3738    }
3739
3740    @Override
3741    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3742            PendingIntent operation) {
3743    }
3744
3745    @Override
3746    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3747        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3748                0, networkRequest));
3749    }
3750
3751    @Override
3752    public void registerNetworkFactory(Messenger messenger, String name) {
3753        enforceConnectivityInternalPermission();
3754        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3755        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3756    }
3757
3758    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3759        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3760        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3761        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3762    }
3763
3764    @Override
3765    public void unregisterNetworkFactory(Messenger messenger) {
3766        enforceConnectivityInternalPermission();
3767        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3768    }
3769
3770    private void handleUnregisterNetworkFactory(Messenger messenger) {
3771        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3772        if (nfi == null) {
3773            loge("Failed to find Messenger in unregisterNetworkFactory");
3774            return;
3775        }
3776        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3777    }
3778
3779    /**
3780     * NetworkAgentInfo supporting a request by requestId.
3781     * These have already been vetted (their Capabilities satisfy the request)
3782     * and the are the highest scored network available.
3783     * the are keyed off the Requests requestId.
3784     */
3785    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3786    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3787            new SparseArray<NetworkAgentInfo>();
3788
3789    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3790    @GuardedBy("mNetworkForNetId")
3791    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3792            new SparseArray<NetworkAgentInfo>();
3793    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3794    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3795    // there may not be a strict 1:1 correlation between the two.
3796    @GuardedBy("mNetworkForNetId")
3797    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3798
3799    // NetworkAgentInfo keyed off its connecting messenger
3800    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3801    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3802    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3803            new HashMap<Messenger, NetworkAgentInfo>();
3804
3805    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3806    private final NetworkRequest mDefaultRequest;
3807
3808    // Request used to optionally keep mobile data active even when higher
3809    // priority networks like Wi-Fi are active.
3810    private final NetworkRequest mDefaultMobileDataRequest;
3811
3812    private NetworkAgentInfo getDefaultNetwork() {
3813        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3814    }
3815
3816    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3817        return nai == getDefaultNetwork();
3818    }
3819
3820    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3821            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3822            int currentScore, NetworkMisc networkMisc) {
3823        enforceConnectivityInternalPermission();
3824
3825        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3826        // satisfies mDefaultRequest.
3827        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3828                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3829                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3830                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
3831        synchronized (this) {
3832            nai.networkMonitor.systemReady = mSystemReady;
3833        }
3834        if (DBG) log("registerNetworkAgent " + nai);
3835        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3836        return nai.network.netId;
3837    }
3838
3839    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3840        if (VDBG) log("Got NetworkAgent Messenger");
3841        mNetworkAgentInfos.put(na.messenger, na);
3842        synchronized (mNetworkForNetId) {
3843            mNetworkForNetId.put(na.network.netId, na);
3844        }
3845        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3846        NetworkInfo networkInfo = na.networkInfo;
3847        na.networkInfo = null;
3848        updateNetworkInfo(na, networkInfo);
3849    }
3850
3851    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3852        LinkProperties newLp = networkAgent.linkProperties;
3853        int netId = networkAgent.network.netId;
3854
3855        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3856        // we do anything else, make sure its LinkProperties are accurate.
3857        if (networkAgent.clatd != null) {
3858            networkAgent.clatd.fixupLinkProperties(oldLp);
3859        }
3860
3861        updateInterfaces(newLp, oldLp, netId);
3862        updateMtu(newLp, oldLp);
3863        // TODO - figure out what to do for clat
3864//        for (LinkProperties lp : newLp.getStackedLinks()) {
3865//            updateMtu(lp, null);
3866//        }
3867        updateTcpBufferSizes(networkAgent);
3868
3869        // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3870        // In L, we used it only when the network had Internet access but provided no DNS servers.
3871        // For now, just disable it, and if disabling it doesn't break things, remove it.
3872        // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3873        //        NET_CAPABILITY_INTERNET);
3874        final boolean useDefaultDns = false;
3875        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3876        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3877
3878        updateClat(newLp, oldLp, networkAgent);
3879        if (isDefaultNetwork(networkAgent)) {
3880            handleApplyDefaultProxy(newLp.getHttpProxy());
3881        } else {
3882            updateProxy(newLp, oldLp, networkAgent);
3883        }
3884        // TODO - move this check to cover the whole function
3885        if (!Objects.equals(newLp, oldLp)) {
3886            notifyIfacesChanged();
3887            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3888        }
3889    }
3890
3891    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3892        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3893        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
3894
3895        if (!wasRunningClat && shouldRunClat) {
3896            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3897            nai.clatd.start();
3898        } else if (wasRunningClat && !shouldRunClat) {
3899            nai.clatd.stop();
3900        }
3901    }
3902
3903    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3904        CompareResult<String> interfaceDiff = new CompareResult<String>();
3905        if (oldLp != null) {
3906            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3907        } else if (newLp != null) {
3908            interfaceDiff.added = newLp.getAllInterfaceNames();
3909        }
3910        for (String iface : interfaceDiff.added) {
3911            try {
3912                if (DBG) log("Adding iface " + iface + " to network " + netId);
3913                mNetd.addInterfaceToNetwork(iface, netId);
3914            } catch (Exception e) {
3915                loge("Exception adding interface: " + e);
3916            }
3917        }
3918        for (String iface : interfaceDiff.removed) {
3919            try {
3920                if (DBG) log("Removing iface " + iface + " from network " + netId);
3921                mNetd.removeInterfaceFromNetwork(iface, netId);
3922            } catch (Exception e) {
3923                loge("Exception removing interface: " + e);
3924            }
3925        }
3926    }
3927
3928    /**
3929     * Have netd update routes from oldLp to newLp.
3930     * @return true if routes changed between oldLp and newLp
3931     */
3932    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
3933        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3934        if (oldLp != null) {
3935            routeDiff = oldLp.compareAllRoutes(newLp);
3936        } else if (newLp != null) {
3937            routeDiff.added = newLp.getAllRoutes();
3938        }
3939
3940        // add routes before removing old in case it helps with continuous connectivity
3941
3942        // do this twice, adding non-nexthop routes first, then routes they are dependent on
3943        for (RouteInfo route : routeDiff.added) {
3944            if (route.hasGateway()) continue;
3945            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3946            try {
3947                mNetd.addRoute(netId, route);
3948            } catch (Exception e) {
3949                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3950                    loge("Exception in addRoute for non-gateway: " + e);
3951                }
3952            }
3953        }
3954        for (RouteInfo route : routeDiff.added) {
3955            if (route.hasGateway() == false) continue;
3956            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3957            try {
3958                mNetd.addRoute(netId, route);
3959            } catch (Exception e) {
3960                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3961                    loge("Exception in addRoute for gateway: " + e);
3962                }
3963            }
3964        }
3965
3966        for (RouteInfo route : routeDiff.removed) {
3967            if (DBG) log("Removing Route [" + route + "] from network " + netId);
3968            try {
3969                mNetd.removeRoute(netId, route);
3970            } catch (Exception e) {
3971                loge("Exception in removeRoute: " + e);
3972            }
3973        }
3974        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
3975    }
3976    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3977                             boolean flush, boolean useDefaultDns) {
3978        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
3979            Collection<InetAddress> dnses = newLp.getDnsServers();
3980            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
3981                dnses = new ArrayList();
3982                dnses.add(mDefaultDns);
3983                if (DBG) {
3984                    loge("no dns provided for netId " + netId + ", so using defaults");
3985                }
3986            }
3987            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
3988            try {
3989                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3990                    newLp.getDomains());
3991            } catch (Exception e) {
3992                loge("Exception in setDnsServersForNetwork: " + e);
3993            }
3994            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3995            if (defaultNai != null && defaultNai.network.netId == netId) {
3996                setDefaultDnsSystemProperties(dnses);
3997            }
3998            flushVmDnsCache();
3999        } else if (flush) {
4000            try {
4001                mNetd.flushNetworkDnsCache(netId);
4002            } catch (Exception e) {
4003                loge("Exception in flushNetworkDnsCache: " + e);
4004            }
4005            flushVmDnsCache();
4006        }
4007    }
4008
4009    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4010        int last = 0;
4011        for (InetAddress dns : dnses) {
4012            ++last;
4013            String key = "net.dns" + last;
4014            String value = dns.getHostAddress();
4015            SystemProperties.set(key, value);
4016        }
4017        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4018            String key = "net.dns" + i;
4019            SystemProperties.set(key, "");
4020        }
4021        mNumDnsEntries = last;
4022    }
4023
4024    private void updateCapabilities(NetworkAgentInfo networkAgent,
4025            NetworkCapabilities networkCapabilities) {
4026        if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4027            synchronized (networkAgent) {
4028                networkAgent.networkCapabilities = networkCapabilities;
4029            }
4030            if (networkAgent.lastValidated) {
4031                networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4032                // There's no need to remove the capability if we think the network is unvalidated,
4033                // because NetworkAgents don't set the validated capability.
4034            }
4035            rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
4036            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
4037        }
4038    }
4039
4040    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4041        for (int i = 0; i < nai.networkRequests.size(); i++) {
4042            NetworkRequest nr = nai.networkRequests.valueAt(i);
4043            // Don't send listening requests to factories. b/17393458
4044            if (!isRequest(nr)) continue;
4045            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4046        }
4047    }
4048
4049    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4050        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4051        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4052            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4053                    networkRequest);
4054        }
4055    }
4056
4057    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4058            int notificationType) {
4059        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4060            Intent intent = new Intent();
4061            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4062            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4063            nri.mPendingIntentSent = true;
4064            sendIntent(nri.mPendingIntent, intent);
4065        }
4066        // else not handled
4067    }
4068
4069    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4070        mPendingIntentWakeLock.acquire();
4071        try {
4072            if (DBG) log("Sending " + pendingIntent);
4073            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4074        } catch (PendingIntent.CanceledException e) {
4075            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4076            mPendingIntentWakeLock.release();
4077            releasePendingNetworkRequest(pendingIntent);
4078        }
4079        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4080    }
4081
4082    @Override
4083    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4084            String resultData, Bundle resultExtras) {
4085        if (DBG) log("Finished sending " + pendingIntent);
4086        mPendingIntentWakeLock.release();
4087        // Release with a delay so the receiving client has an opportunity to put in its
4088        // own request.
4089        releasePendingNetworkRequestWithDelay(pendingIntent);
4090    }
4091
4092    private void callCallbackForRequest(NetworkRequestInfo nri,
4093            NetworkAgentInfo networkAgent, int notificationType) {
4094        if (nri.messenger == null) return;  // Default request has no msgr
4095        Bundle bundle = new Bundle();
4096        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4097                new NetworkRequest(nri.request));
4098        Message msg = Message.obtain();
4099        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4100                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4101            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4102        }
4103        switch (notificationType) {
4104            case ConnectivityManager.CALLBACK_LOSING: {
4105                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4106                break;
4107            }
4108            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4109                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4110                        new NetworkCapabilities(networkAgent.networkCapabilities));
4111                break;
4112            }
4113            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4114                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4115                        new LinkProperties(networkAgent.linkProperties));
4116                break;
4117            }
4118        }
4119        msg.what = notificationType;
4120        msg.setData(bundle);
4121        try {
4122            if (VDBG) {
4123                log("sending notification " + notifyTypeToName(notificationType) +
4124                        " for " + nri.request);
4125            }
4126            nri.messenger.send(msg);
4127        } catch (RemoteException e) {
4128            // may occur naturally in the race of binder death.
4129            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4130        }
4131    }
4132
4133    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4134        for (int i = 0; i < nai.networkRequests.size(); i++) {
4135            NetworkRequest nr = nai.networkRequests.valueAt(i);
4136            // Ignore listening requests.
4137            if (!isRequest(nr)) continue;
4138            loge("Dead network still had at least " + nr);
4139            break;
4140        }
4141        nai.asyncChannel.disconnect();
4142    }
4143
4144    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4145        if (oldNetwork == null) {
4146            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4147            return;
4148        }
4149        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4150        teardownUnneededNetwork(oldNetwork);
4151    }
4152
4153    private void makeDefault(NetworkAgentInfo newNetwork) {
4154        if (DBG) log("Switching to new default network: " + newNetwork);
4155        setupDataActivityTracking(newNetwork);
4156        try {
4157            mNetd.setDefaultNetId(newNetwork.network.netId);
4158        } catch (Exception e) {
4159            loge("Exception setting default network :" + e);
4160        }
4161        notifyLockdownVpn(newNetwork);
4162        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4163        updateTcpBufferSizes(newNetwork);
4164        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4165    }
4166
4167    // Handles a network appearing or improving its score.
4168    //
4169    // - Evaluates all current NetworkRequests that can be
4170    //   satisfied by newNetwork, and reassigns to newNetwork
4171    //   any such requests for which newNetwork is the best.
4172    //
4173    // - Lingers any validated Networks that as a result are no longer
4174    //   needed. A network is needed if it is the best network for
4175    //   one or more NetworkRequests, or if it is a VPN.
4176    //
4177    // - Tears down newNetwork if it just became validated
4178    //   (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4179    //
4180    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4181    //   networks that have no chance (i.e. even if validated)
4182    //   of becoming the highest scoring network.
4183    //
4184    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4185    // it does not remove NetworkRequests that other Networks could better satisfy.
4186    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4187    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4188    // as it performs better by a factor of the number of Networks.
4189    //
4190    // @param newNetwork is the network to be matched against NetworkRequests.
4191    // @param nascent indicates if newNetwork just became validated, in which case it should be
4192    //               torn down if unneeded.
4193    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4194    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4195    //               validated) of becoming the highest scoring network.
4196    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4197            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4198        if (!newNetwork.created) return;
4199        if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
4200            loge("ERROR: nascent network not validated.");
4201        }
4202        boolean keep = newNetwork.isVPN();
4203        boolean isNewDefault = false;
4204        NetworkAgentInfo oldDefaultNetwork = null;
4205        if (DBG) log("rematching " + newNetwork.name());
4206        // Find and migrate to this Network any NetworkRequests for
4207        // which this network is now the best.
4208        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4209        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4210        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4211            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4212            if (newNetwork == currentNetwork) {
4213                if (DBG) {
4214                    log("Network " + newNetwork.name() + " was already satisfying" +
4215                            " request " + nri.request.requestId + ". No change.");
4216                }
4217                keep = true;
4218                continue;
4219            }
4220
4221            // check if it satisfies the NetworkCapabilities
4222            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4223            if (newNetwork.satisfies(nri.request)) {
4224                if (!nri.isRequest) {
4225                    // This is not a request, it's a callback listener.
4226                    // Add it to newNetwork regardless of score.
4227                    newNetwork.addRequest(nri.request);
4228                    continue;
4229                }
4230
4231                // next check if it's better than any current network we're using for
4232                // this request
4233                if (VDBG) {
4234                    log("currentScore = " +
4235                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4236                            ", newScore = " + newNetwork.getCurrentScore());
4237                }
4238                if (currentNetwork == null ||
4239                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4240                    if (currentNetwork != null) {
4241                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4242                        currentNetwork.networkRequests.remove(nri.request.requestId);
4243                        currentNetwork.networkLingered.add(nri.request);
4244                        affectedNetworks.add(currentNetwork);
4245                    } else {
4246                        if (DBG) log("   accepting network in place of null");
4247                    }
4248                    unlinger(newNetwork);
4249                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4250                    newNetwork.addRequest(nri.request);
4251                    keep = true;
4252                    // Tell NetworkFactories about the new score, so they can stop
4253                    // trying to connect if they know they cannot match it.
4254                    // TODO - this could get expensive if we have alot of requests for this
4255                    // network.  Think about if there is a way to reduce this.  Push
4256                    // netid->request mapping to each factory?
4257                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4258                    if (mDefaultRequest.requestId == nri.request.requestId) {
4259                        isNewDefault = true;
4260                        oldDefaultNetwork = currentNetwork;
4261                    }
4262                }
4263            }
4264        }
4265        // Linger any networks that are no longer needed.
4266        for (NetworkAgentInfo nai : affectedNetworks) {
4267            if (nai.everValidated && unneeded(nai)) {
4268                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4269                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4270            } else {
4271                unlinger(nai);
4272            }
4273        }
4274        if (keep) {
4275            if (isNewDefault) {
4276                // Notify system services that this network is up.
4277                makeDefault(newNetwork);
4278                synchronized (ConnectivityService.this) {
4279                    // have a new default network, release the transition wakelock in
4280                    // a second if it's held.  The second pause is to allow apps
4281                    // to reconnect over the new network
4282                    if (mNetTransitionWakeLock.isHeld()) {
4283                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4284                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4285                                mNetTransitionWakeLockSerialNumber, 0),
4286                                1000);
4287                    }
4288                }
4289            }
4290
4291            // do this after the default net is switched, but
4292            // before LegacyTypeTracker sends legacy broadcasts
4293            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4294
4295            if (isNewDefault) {
4296                // Maintain the illusion: since the legacy API only
4297                // understands one network at a time, we must pretend
4298                // that the current default network disconnected before
4299                // the new one connected.
4300                if (oldDefaultNetwork != null) {
4301                    mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4302                                              oldDefaultNetwork, true);
4303                }
4304                mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
4305                mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4306                notifyLockdownVpn(newNetwork);
4307            }
4308
4309            // Notify battery stats service about this network, both the normal
4310            // interface and any stacked links.
4311            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4312            try {
4313                final IBatteryStats bs = BatteryStatsService.getService();
4314                final int type = newNetwork.networkInfo.getType();
4315
4316                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4317                bs.noteNetworkInterfaceType(baseIface, type);
4318                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4319                    final String stackedIface = stacked.getInterfaceName();
4320                    bs.noteNetworkInterfaceType(stackedIface, type);
4321                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4322                }
4323            } catch (RemoteException ignored) {
4324            }
4325
4326            // This has to happen after the notifyNetworkCallbacks as that tickles each
4327            // ConnectivityManager instance so that legacy requests correctly bind dns
4328            // requests to this network.  The legacy users are listening for this bcast
4329            // and will generally do a dns request so they can ensureRouteToHost and if
4330            // they do that before the callbacks happen they'll use the default network.
4331            //
4332            // TODO: Is there still a race here? We send the broadcast
4333            // after sending the callback, but if the app can receive the
4334            // broadcast before the callback, it might still break.
4335            //
4336            // This *does* introduce a race where if the user uses the new api
4337            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4338            // they may get old info.  Reverse this after the old startUsing api is removed.
4339            // This is on top of the multiple intent sequencing referenced in the todo above.
4340            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4341                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4342                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4343                    // legacy type tracker filters out repeat adds
4344                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4345                }
4346            }
4347
4348            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4349            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4350            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4351            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4352            if (newNetwork.isVPN()) {
4353                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4354            }
4355        } else if (nascent == NascentState.JUST_VALIDATED) {
4356            // Only tear down newly validated networks here.  Leave unvalidated to either become
4357            // validated (and get evaluated against peers, one losing here), or get reaped (see
4358            // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4359            // network.  Networks that have been up for a while and are validated should be torn
4360            // down via the lingering process so communication on that network is given time to
4361            // wrap up.
4362            if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
4363            teardownUnneededNetwork(newNetwork);
4364        }
4365        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4366            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4367                if (!nai.everValidated && unneeded(nai)) {
4368                    if (DBG) log("Reaping " + nai.name());
4369                    teardownUnneededNetwork(nai);
4370                }
4371            }
4372        }
4373    }
4374
4375    // Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4376    // being disconnected.
4377    // If only one Network's score or capabilities have been modified since the last time
4378    // this function was called, pass this Network in via the "changed" arugment, otherwise
4379    // pass null.
4380    // If only one Network has been changed but its NetworkCapabilities have not changed,
4381    // pass in the Network's score (from getCurrentScore()) prior to the change via
4382    // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4383    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4384        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4385        // to avoid the slowness.  It is not simply enough to process just "changed", for
4386        // example in the case where "changed"'s score decreases and another network should begin
4387        // satifying a NetworkRequest that "changed" currently satisfies.
4388
4389        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4390        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4391        // rematchNetworkAndRequests() handles.
4392        if (changed != null && oldScore < changed.getCurrentScore()) {
4393            rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4394                    ReapUnvalidatedNetworks.REAP);
4395        } else {
4396            for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4397                rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4398                        NascentState.NOT_JUST_VALIDATED,
4399                        // Only reap the last time through the loop.  Reaping before all rematching
4400                        // is complete could incorrectly teardown a network that hasn't yet been
4401                        // rematched.
4402                        i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4403                                : ReapUnvalidatedNetworks.REAP);
4404            }
4405        }
4406    }
4407
4408    private void updateInetCondition(NetworkAgentInfo nai) {
4409        // Don't bother updating until we've graduated to validated at least once.
4410        if (!nai.everValidated) return;
4411        // For now only update icons for default connection.
4412        // TODO: Update WiFi and cellular icons separately. b/17237507
4413        if (!isDefaultNetwork(nai)) return;
4414
4415        int newInetCondition = nai.lastValidated ? 100 : 0;
4416        // Don't repeat publish.
4417        if (newInetCondition == mDefaultInetConditionPublished) return;
4418
4419        mDefaultInetConditionPublished = newInetCondition;
4420        sendInetConditionBroadcast(nai.networkInfo);
4421    }
4422
4423    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4424        if (mLockdownTracker != null) {
4425            if (nai != null && nai.isVPN()) {
4426                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4427            } else {
4428                mLockdownTracker.onNetworkInfoChanged();
4429            }
4430        }
4431    }
4432
4433    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4434        NetworkInfo.State state = newInfo.getState();
4435        NetworkInfo oldInfo = null;
4436        synchronized (networkAgent) {
4437            oldInfo = networkAgent.networkInfo;
4438            networkAgent.networkInfo = newInfo;
4439        }
4440        notifyLockdownVpn(networkAgent);
4441
4442        if (oldInfo != null && oldInfo.getState() == state) {
4443            if (VDBG) log("ignoring duplicate network state non-change");
4444            return;
4445        }
4446        if (DBG) {
4447            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4448                    (oldInfo == null ? "null" : oldInfo.getState()) +
4449                    " to " + state);
4450        }
4451
4452        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4453            try {
4454                // This should never fail.  Specifying an already in use NetID will cause failure.
4455                if (networkAgent.isVPN()) {
4456                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4457                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4458                            (networkAgent.networkMisc == null ||
4459                                !networkAgent.networkMisc.allowBypass));
4460                } else {
4461                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4462                }
4463            } catch (Exception e) {
4464                loge("Error creating network " + networkAgent.network.netId + ": "
4465                        + e.getMessage());
4466                return;
4467            }
4468            networkAgent.created = true;
4469            updateLinkProperties(networkAgent, null);
4470            notifyIfacesChanged();
4471
4472            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4473            scheduleUnvalidatedPrompt(networkAgent);
4474
4475            if (networkAgent.isVPN()) {
4476                // Temporarily disable the default proxy (not global).
4477                synchronized (mProxyLock) {
4478                    if (!mDefaultProxyDisabled) {
4479                        mDefaultProxyDisabled = true;
4480                        if (mGlobalProxy == null && mDefaultProxy != null) {
4481                            sendProxyBroadcast(null);
4482                        }
4483                    }
4484                }
4485                // TODO: support proxy per network.
4486            }
4487
4488            // Consider network even though it is not yet validated.
4489            rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4490                    ReapUnvalidatedNetworks.REAP);
4491
4492            // This has to happen after matching the requests, because callbacks are just requests.
4493            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4494        } else if (state == NetworkInfo.State.DISCONNECTED ||
4495                state == NetworkInfo.State.SUSPENDED) {
4496            networkAgent.asyncChannel.disconnect();
4497            if (networkAgent.isVPN()) {
4498                synchronized (mProxyLock) {
4499                    if (mDefaultProxyDisabled) {
4500                        mDefaultProxyDisabled = false;
4501                        if (mGlobalProxy == null && mDefaultProxy != null) {
4502                            sendProxyBroadcast(mDefaultProxy);
4503                        }
4504                    }
4505                }
4506            }
4507        }
4508    }
4509
4510    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4511        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4512        if (score < 0) {
4513            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4514                    ").  Bumping score to min of 0");
4515            score = 0;
4516        }
4517
4518        final int oldScore = nai.getCurrentScore();
4519        nai.setCurrentScore(score);
4520
4521        rematchAllNetworksAndRequests(nai, oldScore);
4522
4523        sendUpdatedScoreToFactories(nai);
4524    }
4525
4526    // notify only this one new request of the current state
4527    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4528        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4529        // TODO - read state from monitor to decide what to send.
4530//        if (nai.networkMonitor.isLingering()) {
4531//            notifyType = NetworkCallbacks.LOSING;
4532//        } else if (nai.networkMonitor.isEvaluating()) {
4533//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4534//        }
4535        if (nri.mPendingIntent == null) {
4536            callCallbackForRequest(nri, nai, notifyType);
4537        } else {
4538            sendPendingIntentForRequest(nri, nai, notifyType);
4539        }
4540    }
4541
4542    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4543        // The NetworkInfo we actually send out has no bearing on the real
4544        // state of affairs. For example, if the default connection is mobile,
4545        // and a request for HIPRI has just gone away, we need to pretend that
4546        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4547        // the state to DISCONNECTED, even though the network is of type MOBILE
4548        // and is still connected.
4549        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4550        info.setType(type);
4551        if (connected) {
4552            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4553            sendConnectedBroadcast(info);
4554        } else {
4555            info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
4556            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4557            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4558            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4559            if (info.isFailover()) {
4560                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4561                nai.networkInfo.setFailover(false);
4562            }
4563            if (info.getReason() != null) {
4564                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4565            }
4566            if (info.getExtraInfo() != null) {
4567                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4568            }
4569            NetworkAgentInfo newDefaultAgent = null;
4570            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4571                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4572                if (newDefaultAgent != null) {
4573                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4574                            newDefaultAgent.networkInfo);
4575                } else {
4576                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4577                }
4578            }
4579            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4580                    mDefaultInetConditionPublished);
4581            sendStickyBroadcast(intent);
4582            if (newDefaultAgent != null) {
4583                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4584            }
4585        }
4586    }
4587
4588    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4589        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4590        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4591            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4592            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4593            if (VDBG) log(" sending notification for " + nr);
4594            if (nri.mPendingIntent == null) {
4595                callCallbackForRequest(nri, networkAgent, notifyType);
4596            } else {
4597                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4598            }
4599        }
4600    }
4601
4602    private String notifyTypeToName(int notifyType) {
4603        switch (notifyType) {
4604            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4605            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4606            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4607            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4608            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4609            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4610            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4611            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4612        }
4613        return "UNKNOWN";
4614    }
4615
4616    /**
4617     * Notify other system services that set of active ifaces has changed.
4618     */
4619    private void notifyIfacesChanged() {
4620        try {
4621            mStatsService.forceUpdateIfaces();
4622        } catch (Exception ignored) {
4623        }
4624    }
4625
4626    @Override
4627    public boolean addVpnAddress(String address, int prefixLength) {
4628        throwIfLockdownEnabled();
4629        int user = UserHandle.getUserId(Binder.getCallingUid());
4630        synchronized (mVpns) {
4631            return mVpns.get(user).addAddress(address, prefixLength);
4632        }
4633    }
4634
4635    @Override
4636    public boolean removeVpnAddress(String address, int prefixLength) {
4637        throwIfLockdownEnabled();
4638        int user = UserHandle.getUserId(Binder.getCallingUid());
4639        synchronized (mVpns) {
4640            return mVpns.get(user).removeAddress(address, prefixLength);
4641        }
4642    }
4643
4644    @Override
4645    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4646        throwIfLockdownEnabled();
4647        int user = UserHandle.getUserId(Binder.getCallingUid());
4648        boolean success;
4649        synchronized (mVpns) {
4650            success = mVpns.get(user).setUnderlyingNetworks(networks);
4651        }
4652        if (success) {
4653            notifyIfacesChanged();
4654        }
4655        return success;
4656    }
4657
4658    @Override
4659    public void factoryReset() {
4660        enforceConnectivityInternalPermission();
4661
4662        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4663            return;
4664        }
4665
4666        final int userId = UserHandle.getCallingUserId();
4667
4668        // Turn airplane mode off
4669        setAirplaneMode(false);
4670
4671        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4672            // Untether
4673            for (String tether : getTetheredIfaces()) {
4674                untether(tether);
4675            }
4676        }
4677
4678        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4679            // Turn VPN off
4680            VpnConfig vpnConfig = getVpnConfig(userId);
4681            if (vpnConfig != null) {
4682                if (vpnConfig.legacy) {
4683                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4684                } else {
4685                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4686                    // in the future without user intervention.
4687                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
4688
4689                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4690                }
4691            }
4692        }
4693    }
4694}
4695