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