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