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