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