ConnectivityService.java revision aa281e2bc054cfccaef80eb48342382e79dfeaba
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) != 0
952                || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
953            return true;
954        }
955
956        // no restrictive rules; network is visible
957        return false;
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            int user = UserHandle.getUserId(Binder.getCallingUid());
3219            synchronized(mVpns) {
3220                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3221                            profile));
3222            }
3223        } else {
3224            setLockdownTracker(null);
3225        }
3226
3227        return true;
3228    }
3229
3230    /**
3231     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3232     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3233     */
3234    private void setLockdownTracker(LockdownVpnTracker tracker) {
3235        // Shutdown any existing tracker
3236        final LockdownVpnTracker existing = mLockdownTracker;
3237        mLockdownTracker = null;
3238        if (existing != null) {
3239            existing.shutdown();
3240        }
3241
3242        try {
3243            if (tracker != null) {
3244                mNetd.setFirewallEnabled(true);
3245                mNetd.setFirewallInterfaceRule("lo", true);
3246                mLockdownTracker = tracker;
3247                mLockdownTracker.init();
3248            } else {
3249                mNetd.setFirewallEnabled(false);
3250            }
3251        } catch (RemoteException e) {
3252            // ignored; NMS lives inside system_server
3253        }
3254    }
3255
3256    private void throwIfLockdownEnabled() {
3257        if (mLockdownEnabled) {
3258            throw new IllegalStateException("Unavailable in lockdown mode");
3259        }
3260    }
3261
3262    @Override
3263    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3264        // TODO: Remove?  Any reason to trigger a provisioning check?
3265        return -1;
3266    }
3267
3268    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3269    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3270
3271    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3272        if (DBG) {
3273            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3274                + " action=" + action);
3275        }
3276        Intent intent = new Intent(action);
3277        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3278        // Concatenate the range of types onto the range of NetIDs.
3279        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3280        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3281                networkType, null, pendingIntent, false);
3282    }
3283
3284    /**
3285     * Show or hide network provisioning notifications.
3286     *
3287     * We use notifications for two purposes: to notify that a network requires sign in
3288     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3289     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3290     * particular network we can display the notification type that was most recently requested.
3291     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3292     * might first display NO_INTERNET, and then when the captive portal check completes, display
3293     * SIGN_IN.
3294     *
3295     * @param id an identifier that uniquely identifies this notification.  This must match
3296     *         between show and hide calls.  We use the NetID value but for legacy callers
3297     *         we concatenate the range of types with the range of NetIDs.
3298     */
3299    private void setProvNotificationVisibleIntent(boolean visible, int id,
3300            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3301            boolean highPriority) {
3302        if (DBG) {
3303            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3304                    + " networkType=" + getNetworkTypeName(networkType)
3305                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3306        }
3307
3308        Resources r = Resources.getSystem();
3309        NotificationManager notificationManager = (NotificationManager) mContext
3310            .getSystemService(Context.NOTIFICATION_SERVICE);
3311
3312        if (visible) {
3313            CharSequence title;
3314            CharSequence details;
3315            int icon;
3316            if (notifyType == NotificationType.NO_INTERNET &&
3317                    networkType == ConnectivityManager.TYPE_WIFI) {
3318                title = r.getString(R.string.wifi_no_internet, 0);
3319                details = r.getString(R.string.wifi_no_internet_detailed);
3320                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3321            } else if (notifyType == NotificationType.SIGN_IN) {
3322                switch (networkType) {
3323                    case ConnectivityManager.TYPE_WIFI:
3324                        title = r.getString(R.string.wifi_available_sign_in, 0);
3325                        details = r.getString(R.string.network_available_sign_in_detailed,
3326                                extraInfo);
3327                        icon = R.drawable.stat_notify_wifi_in_range;
3328                        break;
3329                    case ConnectivityManager.TYPE_MOBILE:
3330                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3331                        title = r.getString(R.string.network_available_sign_in, 0);
3332                        // TODO: Change this to pull from NetworkInfo once a printable
3333                        // name has been added to it
3334                        details = mTelephonyManager.getNetworkOperatorName();
3335                        icon = R.drawable.stat_notify_rssi_in_range;
3336                        break;
3337                    default:
3338                        title = r.getString(R.string.network_available_sign_in, 0);
3339                        details = r.getString(R.string.network_available_sign_in_detailed,
3340                                extraInfo);
3341                        icon = R.drawable.stat_notify_rssi_in_range;
3342                        break;
3343                }
3344            } else {
3345                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3346                        + getNetworkTypeName(networkType));
3347                return;
3348            }
3349
3350            Notification notification = new Notification.Builder(mContext)
3351                    .setWhen(0)
3352                    .setSmallIcon(icon)
3353                    .setAutoCancel(true)
3354                    .setTicker(title)
3355                    .setColor(mContext.getColor(
3356                            com.android.internal.R.color.system_notification_accent_color))
3357                    .setContentTitle(title)
3358                    .setContentText(details)
3359                    .setContentIntent(intent)
3360                    .setLocalOnly(true)
3361                    .setPriority(highPriority ?
3362                            Notification.PRIORITY_HIGH :
3363                            Notification.PRIORITY_DEFAULT)
3364                    .setDefaults(Notification.DEFAULT_ALL)
3365                    .setOnlyAlertOnce(true)
3366                    .build();
3367
3368            try {
3369                notificationManager.notify(NOTIFICATION_ID, id, notification);
3370            } catch (NullPointerException npe) {
3371                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3372                npe.printStackTrace();
3373            }
3374        } else {
3375            try {
3376                notificationManager.cancel(NOTIFICATION_ID, id);
3377            } catch (NullPointerException npe) {
3378                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3379                npe.printStackTrace();
3380            }
3381        }
3382    }
3383
3384    /** Location to an updatable file listing carrier provisioning urls.
3385     *  An example:
3386     *
3387     * <?xml version="1.0" encoding="utf-8"?>
3388     *  <provisioningUrls>
3389     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3390     *  </provisioningUrls>
3391     */
3392    private static final String PROVISIONING_URL_PATH =
3393            "/data/misc/radio/provisioning_urls.xml";
3394    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3395
3396    /** XML tag for root element. */
3397    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3398    /** XML tag for individual url */
3399    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3400    /** XML attribute for mcc */
3401    private static final String ATTR_MCC = "mcc";
3402    /** XML attribute for mnc */
3403    private static final String ATTR_MNC = "mnc";
3404
3405    private String getProvisioningUrlBaseFromFile() {
3406        FileReader fileReader = null;
3407        XmlPullParser parser = null;
3408        Configuration config = mContext.getResources().getConfiguration();
3409
3410        try {
3411            fileReader = new FileReader(mProvisioningUrlFile);
3412            parser = Xml.newPullParser();
3413            parser.setInput(fileReader);
3414            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3415
3416            while (true) {
3417                XmlUtils.nextElement(parser);
3418
3419                String element = parser.getName();
3420                if (element == null) break;
3421
3422                if (element.equals(TAG_PROVISIONING_URL)) {
3423                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3424                    try {
3425                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3426                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3427                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3428                                parser.next();
3429                                if (parser.getEventType() == XmlPullParser.TEXT) {
3430                                    return parser.getText();
3431                                }
3432                            }
3433                        }
3434                    } catch (NumberFormatException e) {
3435                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3436                    }
3437                }
3438            }
3439            return null;
3440        } catch (FileNotFoundException e) {
3441            loge("Carrier Provisioning Urls file not found");
3442        } catch (XmlPullParserException e) {
3443            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3444        } catch (IOException e) {
3445            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3446        } finally {
3447            if (fileReader != null) {
3448                try {
3449                    fileReader.close();
3450                } catch (IOException e) {}
3451            }
3452        }
3453        return null;
3454    }
3455
3456    @Override
3457    public String getMobileProvisioningUrl() {
3458        enforceConnectivityInternalPermission();
3459        String url = getProvisioningUrlBaseFromFile();
3460        if (TextUtils.isEmpty(url)) {
3461            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3462            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3463        } else {
3464            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3465        }
3466        // populate the iccid, imei and phone number in the provisioning url.
3467        if (!TextUtils.isEmpty(url)) {
3468            String phoneNumber = mTelephonyManager.getLine1Number();
3469            if (TextUtils.isEmpty(phoneNumber)) {
3470                phoneNumber = "0000000000";
3471            }
3472            url = String.format(url,
3473                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3474                    mTelephonyManager.getDeviceId() /* IMEI */,
3475                    phoneNumber /* Phone numer */);
3476        }
3477
3478        return url;
3479    }
3480
3481    @Override
3482    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3483            String action) {
3484        enforceConnectivityInternalPermission();
3485        final long ident = Binder.clearCallingIdentity();
3486        try {
3487            setProvNotificationVisible(visible, networkType, action);
3488        } finally {
3489            Binder.restoreCallingIdentity(ident);
3490        }
3491    }
3492
3493    @Override
3494    public void setAirplaneMode(boolean enable) {
3495        enforceConnectivityInternalPermission();
3496        final long ident = Binder.clearCallingIdentity();
3497        try {
3498            final ContentResolver cr = mContext.getContentResolver();
3499            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3500            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3501            intent.putExtra("state", enable);
3502            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3503        } finally {
3504            Binder.restoreCallingIdentity(ident);
3505        }
3506    }
3507
3508    private void onUserStart(int userId) {
3509        synchronized(mVpns) {
3510            Vpn userVpn = mVpns.get(userId);
3511            if (userVpn != null) {
3512                loge("Starting user already has a VPN");
3513                return;
3514            }
3515            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3516            mVpns.put(userId, userVpn);
3517        }
3518    }
3519
3520    private void onUserStop(int userId) {
3521        synchronized(mVpns) {
3522            Vpn userVpn = mVpns.get(userId);
3523            if (userVpn == null) {
3524                loge("Stopping user has no VPN");
3525                return;
3526            }
3527            mVpns.delete(userId);
3528        }
3529    }
3530
3531    private void onUserAdded(int userId) {
3532        synchronized(mVpns) {
3533            final int vpnsSize = mVpns.size();
3534            for (int i = 0; i < vpnsSize; i++) {
3535                Vpn vpn = mVpns.valueAt(i);
3536                vpn.onUserAdded(userId);
3537            }
3538        }
3539    }
3540
3541    private void onUserRemoved(int userId) {
3542        synchronized(mVpns) {
3543            final int vpnsSize = mVpns.size();
3544            for (int i = 0; i < vpnsSize; i++) {
3545                Vpn vpn = mVpns.valueAt(i);
3546                vpn.onUserRemoved(userId);
3547            }
3548        }
3549    }
3550
3551    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3552        @Override
3553        public void onReceive(Context context, Intent intent) {
3554            final String action = intent.getAction();
3555            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3556            if (userId == UserHandle.USER_NULL) return;
3557
3558            if (Intent.ACTION_USER_STARTING.equals(action)) {
3559                onUserStart(userId);
3560            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3561                onUserStop(userId);
3562            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3563                onUserAdded(userId);
3564            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3565                onUserRemoved(userId);
3566            }
3567        }
3568    };
3569
3570    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3571            new HashMap<Messenger, NetworkFactoryInfo>();
3572    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3573            new HashMap<NetworkRequest, NetworkRequestInfo>();
3574
3575    private static class NetworkFactoryInfo {
3576        public final String name;
3577        public final Messenger messenger;
3578        public final AsyncChannel asyncChannel;
3579
3580        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3581            this.name = name;
3582            this.messenger = messenger;
3583            this.asyncChannel = asyncChannel;
3584        }
3585    }
3586
3587    /**
3588     * Tracks info about the requester.
3589     * Also used to notice when the calling process dies so we can self-expire
3590     */
3591    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3592        static final boolean REQUEST = true;
3593        static final boolean LISTEN = false;
3594
3595        final NetworkRequest request;
3596        final PendingIntent mPendingIntent;
3597        boolean mPendingIntentSent;
3598        private final IBinder mBinder;
3599        final int mPid;
3600        final int mUid;
3601        final Messenger messenger;
3602        final boolean isRequest;
3603
3604        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3605            request = r;
3606            mPendingIntent = pi;
3607            messenger = null;
3608            mBinder = null;
3609            mPid = getCallingPid();
3610            mUid = getCallingUid();
3611            this.isRequest = isRequest;
3612        }
3613
3614        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3615            super();
3616            messenger = m;
3617            request = r;
3618            mBinder = binder;
3619            mPid = getCallingPid();
3620            mUid = getCallingUid();
3621            this.isRequest = isRequest;
3622            mPendingIntent = null;
3623
3624            try {
3625                mBinder.linkToDeath(this, 0);
3626            } catch (RemoteException e) {
3627                binderDied();
3628            }
3629        }
3630
3631        void unlinkDeathRecipient() {
3632            if (mBinder != null) {
3633                mBinder.unlinkToDeath(this, 0);
3634            }
3635        }
3636
3637        public void binderDied() {
3638            log("ConnectivityService NetworkRequestInfo binderDied(" +
3639                    request + ", " + mBinder + ")");
3640            releaseNetworkRequest(request);
3641        }
3642
3643        public String toString() {
3644            return (isRequest ? "Request" : "Listen") +
3645                    " from uid/pid:" + mUid + "/" + mPid +
3646                    " for " + request +
3647                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3648        }
3649    }
3650
3651    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3652        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3653        if (badCapability != null) {
3654            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3655        }
3656    }
3657
3658    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3659        final SortedSet<Integer> thresholds = new TreeSet();
3660        synchronized (nai) {
3661            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3662                if (nri.request.networkCapabilities.hasSignalStrength() &&
3663                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3664                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3665                }
3666            }
3667        }
3668        return new ArrayList<Integer>(thresholds);
3669    }
3670
3671    private void updateSignalStrengthThresholds(
3672            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3673        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3674        Bundle thresholds = new Bundle();
3675        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3676
3677        // TODO: Switch to VDBG.
3678        if (DBG) {
3679            String detail;
3680            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3681                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3682            } else {
3683                detail = reason;
3684            }
3685            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3686                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3687        }
3688
3689        nai.asyncChannel.sendMessage(
3690                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3691                0, 0, thresholds);
3692    }
3693
3694    @Override
3695    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3696            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3697        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3698        enforceNetworkRequestPermissions(networkCapabilities);
3699        enforceMeteredApnPolicy(networkCapabilities);
3700        ensureRequestableCapabilities(networkCapabilities);
3701
3702        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3703            throw new IllegalArgumentException("Bad timeout specified");
3704        }
3705
3706        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3707                nextNetworkRequestId());
3708        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3709                NetworkRequestInfo.REQUEST);
3710        if (DBG) log("requestNetwork for " + nri);
3711
3712        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3713        if (timeoutMs > 0) {
3714            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3715                    nri), timeoutMs);
3716        }
3717        return networkRequest;
3718    }
3719
3720    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3721        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3722            enforceConnectivityInternalPermission();
3723        } else {
3724            enforceChangePermission();
3725        }
3726    }
3727
3728    @Override
3729    public boolean requestBandwidthUpdate(Network network) {
3730        enforceAccessPermission();
3731        NetworkAgentInfo nai = null;
3732        if (network == null) {
3733            return false;
3734        }
3735        synchronized (mNetworkForNetId) {
3736            nai = mNetworkForNetId.get(network.netId);
3737        }
3738        if (nai != null) {
3739            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3740            return true;
3741        }
3742        return false;
3743    }
3744
3745
3746    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3747        // if UID is restricted, don't allow them to bring up metered APNs
3748        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3749            final int uidRules;
3750            final int uid = Binder.getCallingUid();
3751            synchronized(mRulesLock) {
3752                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3753            }
3754            if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
3755                // we could silently fail or we can filter the available nets to only give
3756                // them those they have access to.  Chose the more useful
3757                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3758            }
3759        }
3760    }
3761
3762    @Override
3763    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3764            PendingIntent operation) {
3765        checkNotNull(operation, "PendingIntent cannot be null.");
3766        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3767        enforceNetworkRequestPermissions(networkCapabilities);
3768        enforceMeteredApnPolicy(networkCapabilities);
3769        ensureRequestableCapabilities(networkCapabilities);
3770
3771        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3772                nextNetworkRequestId());
3773        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3774                NetworkRequestInfo.REQUEST);
3775        if (DBG) log("pendingRequest for " + nri);
3776        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3777                nri));
3778        return networkRequest;
3779    }
3780
3781    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3782        mHandler.sendMessageDelayed(
3783                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3784                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3785    }
3786
3787    @Override
3788    public void releasePendingNetworkRequest(PendingIntent operation) {
3789        checkNotNull(operation, "PendingIntent cannot be null.");
3790        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3791                getCallingUid(), 0, operation));
3792    }
3793
3794    // In order to implement the compatibility measure for pre-M apps that call
3795    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3796    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3797    // This ensures it has permission to do so.
3798    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3799        if (nc == null) {
3800            return false;
3801        }
3802        int[] transportTypes = nc.getTransportTypes();
3803        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3804            return false;
3805        }
3806        try {
3807            mContext.enforceCallingOrSelfPermission(
3808                    android.Manifest.permission.ACCESS_WIFI_STATE,
3809                    "ConnectivityService");
3810        } catch (SecurityException e) {
3811            return false;
3812        }
3813        return true;
3814    }
3815
3816    @Override
3817    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3818            Messenger messenger, IBinder binder) {
3819        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3820            enforceAccessPermission();
3821        }
3822
3823        NetworkRequest networkRequest = new NetworkRequest(
3824                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3825        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3826                NetworkRequestInfo.LISTEN);
3827        if (DBG) log("listenForNetwork for " + nri);
3828
3829        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3830        return networkRequest;
3831    }
3832
3833    @Override
3834    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3835            PendingIntent operation) {
3836        checkNotNull(operation, "PendingIntent cannot be null.");
3837        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3838            enforceAccessPermission();
3839        }
3840
3841        NetworkRequest networkRequest = new NetworkRequest(
3842                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3843        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3844                NetworkRequestInfo.LISTEN);
3845        if (DBG) log("pendingListenForNetwork for " + nri);
3846
3847        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3848    }
3849
3850    @Override
3851    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3852        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3853                0, networkRequest));
3854    }
3855
3856    @Override
3857    public void registerNetworkFactory(Messenger messenger, String name) {
3858        enforceConnectivityInternalPermission();
3859        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3860        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3861    }
3862
3863    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3864        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3865        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3866        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3867    }
3868
3869    @Override
3870    public void unregisterNetworkFactory(Messenger messenger) {
3871        enforceConnectivityInternalPermission();
3872        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3873    }
3874
3875    private void handleUnregisterNetworkFactory(Messenger messenger) {
3876        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3877        if (nfi == null) {
3878            loge("Failed to find Messenger in unregisterNetworkFactory");
3879            return;
3880        }
3881        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3882    }
3883
3884    /**
3885     * NetworkAgentInfo supporting a request by requestId.
3886     * These have already been vetted (their Capabilities satisfy the request)
3887     * and the are the highest scored network available.
3888     * the are keyed off the Requests requestId.
3889     */
3890    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3891    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3892            new SparseArray<NetworkAgentInfo>();
3893
3894    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3895    @GuardedBy("mNetworkForNetId")
3896    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3897            new SparseArray<NetworkAgentInfo>();
3898    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3899    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3900    // there may not be a strict 1:1 correlation between the two.
3901    @GuardedBy("mNetworkForNetId")
3902    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3903
3904    // NetworkAgentInfo keyed off its connecting messenger
3905    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3906    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3907    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3908            new HashMap<Messenger, NetworkAgentInfo>();
3909
3910    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3911    private final NetworkRequest mDefaultRequest;
3912
3913    // Request used to optionally keep mobile data active even when higher
3914    // priority networks like Wi-Fi are active.
3915    private final NetworkRequest mDefaultMobileDataRequest;
3916
3917    private NetworkAgentInfo getDefaultNetwork() {
3918        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3919    }
3920
3921    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3922        return nai == getDefaultNetwork();
3923    }
3924
3925    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3926            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3927            int currentScore, NetworkMisc networkMisc) {
3928        enforceConnectivityInternalPermission();
3929
3930        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3931        // satisfies mDefaultRequest.
3932        final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3933                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3934                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3935                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
3936        synchronized (this) {
3937            nai.networkMonitor.systemReady = mSystemReady;
3938        }
3939        addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
3940        if (DBG) log("registerNetworkAgent " + nai);
3941        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3942        return nai.network.netId;
3943    }
3944
3945    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3946        if (VDBG) log("Got NetworkAgent Messenger");
3947        mNetworkAgentInfos.put(na.messenger, na);
3948        synchronized (mNetworkForNetId) {
3949            mNetworkForNetId.put(na.network.netId, na);
3950        }
3951        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3952        NetworkInfo networkInfo = na.networkInfo;
3953        na.networkInfo = null;
3954        updateNetworkInfo(na, networkInfo);
3955    }
3956
3957    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3958        LinkProperties newLp = networkAgent.linkProperties;
3959        int netId = networkAgent.network.netId;
3960
3961        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3962        // we do anything else, make sure its LinkProperties are accurate.
3963        if (networkAgent.clatd != null) {
3964            networkAgent.clatd.fixupLinkProperties(oldLp);
3965        }
3966
3967        updateInterfaces(newLp, oldLp, netId);
3968        updateMtu(newLp, oldLp);
3969        // TODO - figure out what to do for clat
3970//        for (LinkProperties lp : newLp.getStackedLinks()) {
3971//            updateMtu(lp, null);
3972//        }
3973        updateTcpBufferSizes(networkAgent);
3974
3975        // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3976        // In L, we used it only when the network had Internet access but provided no DNS servers.
3977        // For now, just disable it, and if disabling it doesn't break things, remove it.
3978        // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3979        //        NET_CAPABILITY_INTERNET);
3980        final boolean useDefaultDns = false;
3981        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3982        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3983
3984        updateClat(newLp, oldLp, networkAgent);
3985        if (isDefaultNetwork(networkAgent)) {
3986            handleApplyDefaultProxy(newLp.getHttpProxy());
3987        } else {
3988            updateProxy(newLp, oldLp, networkAgent);
3989        }
3990        // TODO - move this check to cover the whole function
3991        if (!Objects.equals(newLp, oldLp)) {
3992            notifyIfacesChanged();
3993            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3994        }
3995
3996        mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
3997    }
3998
3999    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4000        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4001        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
4002
4003        if (!wasRunningClat && shouldRunClat) {
4004            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4005            nai.clatd.start();
4006        } else if (wasRunningClat && !shouldRunClat) {
4007            nai.clatd.stop();
4008        }
4009    }
4010
4011    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4012        CompareResult<String> interfaceDiff = new CompareResult<String>();
4013        if (oldLp != null) {
4014            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4015        } else if (newLp != null) {
4016            interfaceDiff.added = newLp.getAllInterfaceNames();
4017        }
4018        for (String iface : interfaceDiff.added) {
4019            try {
4020                if (DBG) log("Adding iface " + iface + " to network " + netId);
4021                mNetd.addInterfaceToNetwork(iface, netId);
4022            } catch (Exception e) {
4023                loge("Exception adding interface: " + e);
4024            }
4025        }
4026        for (String iface : interfaceDiff.removed) {
4027            try {
4028                if (DBG) log("Removing iface " + iface + " from network " + netId);
4029                mNetd.removeInterfaceFromNetwork(iface, netId);
4030            } catch (Exception e) {
4031                loge("Exception removing interface: " + e);
4032            }
4033        }
4034    }
4035
4036    /**
4037     * Have netd update routes from oldLp to newLp.
4038     * @return true if routes changed between oldLp and newLp
4039     */
4040    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4041        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4042        if (oldLp != null) {
4043            routeDiff = oldLp.compareAllRoutes(newLp);
4044        } else if (newLp != null) {
4045            routeDiff.added = newLp.getAllRoutes();
4046        }
4047
4048        // add routes before removing old in case it helps with continuous connectivity
4049
4050        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4051        for (RouteInfo route : routeDiff.added) {
4052            if (route.hasGateway()) continue;
4053            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4054            try {
4055                mNetd.addRoute(netId, route);
4056            } catch (Exception e) {
4057                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4058                    loge("Exception in addRoute for non-gateway: " + e);
4059                }
4060            }
4061        }
4062        for (RouteInfo route : routeDiff.added) {
4063            if (route.hasGateway() == false) continue;
4064            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4065            try {
4066                mNetd.addRoute(netId, route);
4067            } catch (Exception e) {
4068                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4069                    loge("Exception in addRoute for gateway: " + e);
4070                }
4071            }
4072        }
4073
4074        for (RouteInfo route : routeDiff.removed) {
4075            if (DBG) log("Removing Route [" + route + "] from network " + netId);
4076            try {
4077                mNetd.removeRoute(netId, route);
4078            } catch (Exception e) {
4079                loge("Exception in removeRoute: " + e);
4080            }
4081        }
4082        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4083    }
4084
4085    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4086                             boolean flush, boolean useDefaultDns) {
4087        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4088            Collection<InetAddress> dnses = newLp.getDnsServers();
4089            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
4090                dnses = new ArrayList();
4091                dnses.add(mDefaultDns);
4092                if (DBG) {
4093                    loge("no dns provided for netId " + netId + ", so using defaults");
4094                }
4095            }
4096            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4097            try {
4098                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4099                    newLp.getDomains());
4100            } catch (Exception e) {
4101                loge("Exception in setDnsServersForNetwork: " + e);
4102            }
4103            final NetworkAgentInfo defaultNai = getDefaultNetwork();
4104            if (defaultNai != null && defaultNai.network.netId == netId) {
4105                setDefaultDnsSystemProperties(dnses);
4106            }
4107            flushVmDnsCache();
4108        } else if (flush) {
4109            try {
4110                mNetd.flushNetworkDnsCache(netId);
4111            } catch (Exception e) {
4112                loge("Exception in flushNetworkDnsCache: " + e);
4113            }
4114            flushVmDnsCache();
4115        }
4116    }
4117
4118    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4119        int last = 0;
4120        for (InetAddress dns : dnses) {
4121            ++last;
4122            String key = "net.dns" + last;
4123            String value = dns.getHostAddress();
4124            SystemProperties.set(key, value);
4125        }
4126        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4127            String key = "net.dns" + i;
4128            SystemProperties.set(key, "");
4129        }
4130        mNumDnsEntries = last;
4131    }
4132
4133    /**
4134     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4135     * augmented with any stateful capabilities implied from {@code networkAgent}
4136     * (e.g., validated status and captive portal status).
4137     *
4138     * @param nai the network having its capabilities updated.
4139     * @param networkCapabilities the new network capabilities.
4140     */
4141    private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
4142        // Don't modify caller's NetworkCapabilities.
4143        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4144        if (nai.lastValidated) {
4145            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4146        } else {
4147            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4148        }
4149        if (nai.lastCaptivePortalDetected) {
4150            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4151        } else {
4152            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4153        }
4154        if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4155            final int oldScore = nai.getCurrentScore();
4156            if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4157                    networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4158                try {
4159                    mNetd.setNetworkPermission(nai.network.netId,
4160                            networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4161                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4162                } catch (RemoteException e) {
4163                    loge("Exception in setNetworkPermission: " + e);
4164                }
4165            }
4166            synchronized (nai) {
4167                nai.networkCapabilities = networkCapabilities;
4168            }
4169            rematchAllNetworksAndRequests(nai, oldScore);
4170            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4171        }
4172    }
4173
4174    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4175        for (int i = 0; i < nai.networkRequests.size(); i++) {
4176            NetworkRequest nr = nai.networkRequests.valueAt(i);
4177            // Don't send listening requests to factories. b/17393458
4178            if (!isRequest(nr)) continue;
4179            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4180        }
4181    }
4182
4183    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4184        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4185        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4186            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4187                    networkRequest);
4188        }
4189    }
4190
4191    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4192            int notificationType) {
4193        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4194            Intent intent = new Intent();
4195            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4196            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4197            nri.mPendingIntentSent = true;
4198            sendIntent(nri.mPendingIntent, intent);
4199        }
4200        // else not handled
4201    }
4202
4203    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4204        mPendingIntentWakeLock.acquire();
4205        try {
4206            if (DBG) log("Sending " + pendingIntent);
4207            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4208        } catch (PendingIntent.CanceledException e) {
4209            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4210            mPendingIntentWakeLock.release();
4211            releasePendingNetworkRequest(pendingIntent);
4212        }
4213        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4214    }
4215
4216    @Override
4217    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4218            String resultData, Bundle resultExtras) {
4219        if (DBG) log("Finished sending " + pendingIntent);
4220        mPendingIntentWakeLock.release();
4221        // Release with a delay so the receiving client has an opportunity to put in its
4222        // own request.
4223        releasePendingNetworkRequestWithDelay(pendingIntent);
4224    }
4225
4226    private void callCallbackForRequest(NetworkRequestInfo nri,
4227            NetworkAgentInfo networkAgent, int notificationType) {
4228        if (nri.messenger == null) return;  // Default request has no msgr
4229        Bundle bundle = new Bundle();
4230        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4231                new NetworkRequest(nri.request));
4232        Message msg = Message.obtain();
4233        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4234                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4235            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4236        }
4237        switch (notificationType) {
4238            case ConnectivityManager.CALLBACK_LOSING: {
4239                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4240                break;
4241            }
4242            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4243                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4244                        new NetworkCapabilities(networkAgent.networkCapabilities));
4245                break;
4246            }
4247            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4248                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4249                        new LinkProperties(networkAgent.linkProperties));
4250                break;
4251            }
4252        }
4253        msg.what = notificationType;
4254        msg.setData(bundle);
4255        try {
4256            if (VDBG) {
4257                log("sending notification " + notifyTypeToName(notificationType) +
4258                        " for " + nri.request);
4259            }
4260            nri.messenger.send(msg);
4261        } catch (RemoteException e) {
4262            // may occur naturally in the race of binder death.
4263            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4264        }
4265    }
4266
4267    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4268        for (int i = 0; i < nai.networkRequests.size(); i++) {
4269            NetworkRequest nr = nai.networkRequests.valueAt(i);
4270            // Ignore listening requests.
4271            if (!isRequest(nr)) continue;
4272            loge("Dead network still had at least " + nr);
4273            break;
4274        }
4275        nai.asyncChannel.disconnect();
4276    }
4277
4278    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4279        if (oldNetwork == null) {
4280            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4281            return;
4282        }
4283        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4284        teardownUnneededNetwork(oldNetwork);
4285    }
4286
4287    private void makeDefault(NetworkAgentInfo newNetwork) {
4288        if (DBG) log("Switching to new default network: " + newNetwork);
4289        setupDataActivityTracking(newNetwork);
4290        try {
4291            mNetd.setDefaultNetId(newNetwork.network.netId);
4292        } catch (Exception e) {
4293            loge("Exception setting default network :" + e);
4294        }
4295        notifyLockdownVpn(newNetwork);
4296        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4297        updateTcpBufferSizes(newNetwork);
4298        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4299    }
4300
4301    // Handles a network appearing or improving its score.
4302    //
4303    // - Evaluates all current NetworkRequests that can be
4304    //   satisfied by newNetwork, and reassigns to newNetwork
4305    //   any such requests for which newNetwork is the best.
4306    //
4307    // - Lingers any validated Networks that as a result are no longer
4308    //   needed. A network is needed if it is the best network for
4309    //   one or more NetworkRequests, or if it is a VPN.
4310    //
4311    // - Tears down newNetwork if it just became validated
4312    //   but turns out to be unneeded.
4313    //
4314    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4315    //   networks that have no chance (i.e. even if validated)
4316    //   of becoming the highest scoring network.
4317    //
4318    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4319    // it does not remove NetworkRequests that other Networks could better satisfy.
4320    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4321    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4322    // as it performs better by a factor of the number of Networks.
4323    //
4324    // @param newNetwork is the network to be matched against NetworkRequests.
4325    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4326    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4327    //               validated) of becoming the highest scoring network.
4328    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
4329            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4330        if (!newNetwork.created) return;
4331        boolean keep = newNetwork.isVPN();
4332        boolean isNewDefault = false;
4333        NetworkAgentInfo oldDefaultNetwork = null;
4334        if (VDBG) log("rematching " + newNetwork.name());
4335        // Find and migrate to this Network any NetworkRequests for
4336        // which this network is now the best.
4337        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4338        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4339        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4340        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4341            final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4342            final boolean satisfies = newNetwork.satisfies(nri.request);
4343            if (newNetwork == currentNetwork && satisfies) {
4344                if (VDBG) {
4345                    log("Network " + newNetwork.name() + " was already satisfying" +
4346                            " request " + nri.request.requestId + ". No change.");
4347                }
4348                keep = true;
4349                continue;
4350            }
4351
4352            // check if it satisfies the NetworkCapabilities
4353            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4354            if (satisfies) {
4355                if (!nri.isRequest) {
4356                    // This is not a request, it's a callback listener.
4357                    // Add it to newNetwork regardless of score.
4358                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4359                    continue;
4360                }
4361
4362                // next check if it's better than any current network we're using for
4363                // this request
4364                if (VDBG) {
4365                    log("currentScore = " +
4366                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4367                            ", newScore = " + newNetwork.getCurrentScore());
4368                }
4369                if (currentNetwork == null ||
4370                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4371                    if (DBG) log("rematch for " + newNetwork.name());
4372                    if (currentNetwork != null) {
4373                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4374                        currentNetwork.networkRequests.remove(nri.request.requestId);
4375                        currentNetwork.networkLingered.add(nri.request);
4376                        affectedNetworks.add(currentNetwork);
4377                    } else {
4378                        if (DBG) log("   accepting network in place of null");
4379                    }
4380                    unlinger(newNetwork);
4381                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4382                    if (!newNetwork.addRequest(nri.request)) {
4383                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4384                    }
4385                    addedRequests.add(nri);
4386                    keep = true;
4387                    // Tell NetworkFactories about the new score, so they can stop
4388                    // trying to connect if they know they cannot match it.
4389                    // TODO - this could get expensive if we have alot of requests for this
4390                    // network.  Think about if there is a way to reduce this.  Push
4391                    // netid->request mapping to each factory?
4392                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4393                    if (mDefaultRequest.requestId == nri.request.requestId) {
4394                        isNewDefault = true;
4395                        oldDefaultNetwork = currentNetwork;
4396                    }
4397                }
4398            } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4399                // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4400                // mark it as no longer satisfying "nri".  Because networks are processed by
4401                // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4402                // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4403                // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4404                // This means this code doesn't have to handle the case where "currentNetwork" no
4405                // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4406                if (DBG) {
4407                    log("Network " + newNetwork.name() + " stopped satisfying" +
4408                            " request " + nri.request.requestId);
4409                }
4410                newNetwork.networkRequests.remove(nri.request.requestId);
4411                if (currentNetwork == newNetwork) {
4412                    mNetworkForRequestId.remove(nri.request.requestId);
4413                    sendUpdatedScoreToFactories(nri.request, 0);
4414                } else {
4415                    if (nri.isRequest == true) {
4416                        Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4417                                newNetwork.name() +
4418                                " without updating mNetworkForRequestId or factories!");
4419                    }
4420                }
4421                // TODO: technically, sending CALLBACK_LOST here is
4422                // incorrect if nri is a request (not a listen) and there
4423                // is a replacement network currently connected that can
4424                // satisfy it. However, the only capability that can both
4425                // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4426                // so this code is only incorrect for a network that loses
4427                // the TRUSTED capability, which is a rare case.
4428                callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
4429            }
4430        }
4431        // Linger any networks that are no longer needed.
4432        for (NetworkAgentInfo nai : affectedNetworks) {
4433            if (nai.lingering) {
4434                // Already lingered.  Nothing to do.  This can only happen if "nai" is in
4435                // "affectedNetworks" twice.  The reasoning being that to get added to
4436                // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4437                // (i.e. not lingered) so it could have only been lingered by this loop.
4438                // unneeded(nai) will be false and we'll call unlinger() below which would
4439                // be bad, so handle it here.
4440            } else if (unneeded(nai)) {
4441                linger(nai);
4442            } else {
4443                // Clear nai.networkLingered we might have added above.
4444                unlinger(nai);
4445            }
4446        }
4447        if (isNewDefault) {
4448            // Notify system services that this network is up.
4449            makeDefault(newNetwork);
4450            synchronized (ConnectivityService.this) {
4451                // have a new default network, release the transition wakelock in
4452                // a second if it's held.  The second pause is to allow apps
4453                // to reconnect over the new network
4454                if (mNetTransitionWakeLock.isHeld()) {
4455                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
4456                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4457                            mNetTransitionWakeLockSerialNumber, 0),
4458                            1000);
4459                }
4460            }
4461        }
4462
4463        // do this after the default net is switched, but
4464        // before LegacyTypeTracker sends legacy broadcasts
4465        for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4466
4467        if (isNewDefault) {
4468            // Maintain the illusion: since the legacy API only
4469            // understands one network at a time, we must pretend
4470            // that the current default network disconnected before
4471            // the new one connected.
4472            if (oldDefaultNetwork != null) {
4473                mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4474                                          oldDefaultNetwork, true);
4475            }
4476            mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4477            mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4478            notifyLockdownVpn(newNetwork);
4479        }
4480
4481        if (keep) {
4482            // Notify battery stats service about this network, both the normal
4483            // interface and any stacked links.
4484            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4485            try {
4486                final IBatteryStats bs = BatteryStatsService.getService();
4487                final int type = newNetwork.networkInfo.getType();
4488
4489                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4490                bs.noteNetworkInterfaceType(baseIface, type);
4491                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4492                    final String stackedIface = stacked.getInterfaceName();
4493                    bs.noteNetworkInterfaceType(stackedIface, type);
4494                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4495                }
4496            } catch (RemoteException ignored) {
4497            }
4498
4499            // This has to happen after the notifyNetworkCallbacks as that tickles each
4500            // ConnectivityManager instance so that legacy requests correctly bind dns
4501            // requests to this network.  The legacy users are listening for this bcast
4502            // and will generally do a dns request so they can ensureRouteToHost and if
4503            // they do that before the callbacks happen they'll use the default network.
4504            //
4505            // TODO: Is there still a race here? We send the broadcast
4506            // after sending the callback, but if the app can receive the
4507            // broadcast before the callback, it might still break.
4508            //
4509            // This *does* introduce a race where if the user uses the new api
4510            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4511            // they may get old info.  Reverse this after the old startUsing api is removed.
4512            // This is on top of the multiple intent sequencing referenced in the todo above.
4513            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4514                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4515                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4516                    // legacy type tracker filters out repeat adds
4517                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4518                }
4519            }
4520
4521            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4522            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4523            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4524            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4525            if (newNetwork.isVPN()) {
4526                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4527            }
4528        }
4529        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4530            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4531                if (unneeded(nai)) {
4532                    if (DBG) log("Reaping " + nai.name());
4533                    teardownUnneededNetwork(nai);
4534                }
4535            }
4536        }
4537    }
4538
4539    /**
4540     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4541     * being disconnected.
4542     * @param changed If only one Network's score or capabilities have been modified since the last
4543     *         time this function was called, pass this Network in this argument, otherwise pass
4544     *         null.
4545     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4546     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4547     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4548     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4549     *         network's score.
4550     */
4551    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4552        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4553        // to avoid the slowness.  It is not simply enough to process just "changed", for
4554        // example in the case where "changed"'s score decreases and another network should begin
4555        // satifying a NetworkRequest that "changed" currently satisfies.
4556
4557        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4558        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4559        // rematchNetworkAndRequests() handles.
4560        if (changed != null && oldScore < changed.getCurrentScore()) {
4561            rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
4562        } else {
4563            final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4564                    new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4565            // Rematch higher scoring networks first to prevent requests first matching a lower
4566            // scoring network and then a higher scoring network, which could produce multiple
4567            // callbacks and inadvertently unlinger networks.
4568            Arrays.sort(nais);
4569            for (NetworkAgentInfo nai : nais) {
4570                rematchNetworkAndRequests(nai,
4571                        // Only reap the last time through the loop.  Reaping before all rematching
4572                        // is complete could incorrectly teardown a network that hasn't yet been
4573                        // rematched.
4574                        (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
4575                                : ReapUnvalidatedNetworks.REAP);
4576            }
4577        }
4578    }
4579
4580    private void updateInetCondition(NetworkAgentInfo nai) {
4581        // Don't bother updating until we've graduated to validated at least once.
4582        if (!nai.everValidated) return;
4583        // For now only update icons for default connection.
4584        // TODO: Update WiFi and cellular icons separately. b/17237507
4585        if (!isDefaultNetwork(nai)) return;
4586
4587        int newInetCondition = nai.lastValidated ? 100 : 0;
4588        // Don't repeat publish.
4589        if (newInetCondition == mDefaultInetConditionPublished) return;
4590
4591        mDefaultInetConditionPublished = newInetCondition;
4592        sendInetConditionBroadcast(nai.networkInfo);
4593    }
4594
4595    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4596        if (mLockdownTracker != null) {
4597            if (nai != null && nai.isVPN()) {
4598                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4599            } else {
4600                mLockdownTracker.onNetworkInfoChanged();
4601            }
4602        }
4603    }
4604
4605    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4606        NetworkInfo.State state = newInfo.getState();
4607        NetworkInfo oldInfo = null;
4608        final int oldScore = networkAgent.getCurrentScore();
4609        synchronized (networkAgent) {
4610            oldInfo = networkAgent.networkInfo;
4611            networkAgent.networkInfo = newInfo;
4612        }
4613        notifyLockdownVpn(networkAgent);
4614
4615        if (oldInfo != null && oldInfo.getState() == state) {
4616            if (VDBG) log("ignoring duplicate network state non-change");
4617            return;
4618        }
4619        if (DBG) {
4620            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4621                    (oldInfo == null ? "null" : oldInfo.getState()) +
4622                    " to " + state);
4623        }
4624
4625        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4626            try {
4627                // This should never fail.  Specifying an already in use NetID will cause failure.
4628                if (networkAgent.isVPN()) {
4629                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4630                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4631                            (networkAgent.networkMisc == null ||
4632                                !networkAgent.networkMisc.allowBypass));
4633                } else {
4634                    mNetd.createPhysicalNetwork(networkAgent.network.netId,
4635                            networkAgent.networkCapabilities.hasCapability(
4636                                    NET_CAPABILITY_NOT_RESTRICTED) ?
4637                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4638                }
4639            } catch (Exception e) {
4640                loge("Error creating network " + networkAgent.network.netId + ": "
4641                        + e.getMessage());
4642                return;
4643            }
4644            networkAgent.created = true;
4645            updateLinkProperties(networkAgent, null);
4646            notifyIfacesChanged();
4647
4648            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4649            scheduleUnvalidatedPrompt(networkAgent);
4650
4651            if (networkAgent.isVPN()) {
4652                // Temporarily disable the default proxy (not global).
4653                synchronized (mProxyLock) {
4654                    if (!mDefaultProxyDisabled) {
4655                        mDefaultProxyDisabled = true;
4656                        if (mGlobalProxy == null && mDefaultProxy != null) {
4657                            sendProxyBroadcast(null);
4658                        }
4659                    }
4660                }
4661                // TODO: support proxy per network.
4662            }
4663
4664            // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4665            // be communicated to a particular NetworkAgent depends only on the network's immutable,
4666            // capabilities, so it only needs to be done once on initial connect, not every time the
4667            // network's capabilities change. Note that we do this before rematching the network,
4668            // so we could decide to tear it down immediately afterwards. That's fine though - on
4669            // disconnection NetworkAgents should stop any signal strength monitoring they have been
4670            // doing.
4671            updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
4672
4673            // Consider network even though it is not yet validated.
4674            rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
4675
4676            // This has to happen after matching the requests, because callbacks are just requests.
4677            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4678        } else if (state == NetworkInfo.State.DISCONNECTED) {
4679            networkAgent.asyncChannel.disconnect();
4680            if (networkAgent.isVPN()) {
4681                synchronized (mProxyLock) {
4682                    if (mDefaultProxyDisabled) {
4683                        mDefaultProxyDisabled = false;
4684                        if (mGlobalProxy == null && mDefaultProxy != null) {
4685                            sendProxyBroadcast(mDefaultProxy);
4686                        }
4687                    }
4688                }
4689            }
4690        } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4691                state == NetworkInfo.State.SUSPENDED) {
4692            // going into or coming out of SUSPEND: rescore and notify
4693            if (networkAgent.getCurrentScore() != oldScore) {
4694                rematchAllNetworksAndRequests(networkAgent, oldScore);
4695            }
4696            notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4697                    ConnectivityManager.CALLBACK_SUSPENDED :
4698                    ConnectivityManager.CALLBACK_RESUMED));
4699            mLegacyTypeTracker.update(networkAgent);
4700        }
4701    }
4702
4703    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4704        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4705        if (score < 0) {
4706            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4707                    ").  Bumping score to min of 0");
4708            score = 0;
4709        }
4710
4711        final int oldScore = nai.getCurrentScore();
4712        nai.setCurrentScore(score);
4713
4714        rematchAllNetworksAndRequests(nai, oldScore);
4715
4716        sendUpdatedScoreToFactories(nai);
4717    }
4718
4719    // notify only this one new request of the current state
4720    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4721        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4722        // TODO - read state from monitor to decide what to send.
4723//        if (nai.networkMonitor.isLingering()) {
4724//            notifyType = NetworkCallbacks.LOSING;
4725//        } else if (nai.networkMonitor.isEvaluating()) {
4726//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4727//        }
4728        if (nri.mPendingIntent == null) {
4729            callCallbackForRequest(nri, nai, notifyType);
4730        } else {
4731            sendPendingIntentForRequest(nri, nai, notifyType);
4732        }
4733    }
4734
4735    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
4736        // The NetworkInfo we actually send out has no bearing on the real
4737        // state of affairs. For example, if the default connection is mobile,
4738        // and a request for HIPRI has just gone away, we need to pretend that
4739        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4740        // the state to DISCONNECTED, even though the network is of type MOBILE
4741        // and is still connected.
4742        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4743        info.setType(type);
4744        if (state != DetailedState.DISCONNECTED) {
4745            info.setDetailedState(state, null, info.getExtraInfo());
4746            sendConnectedBroadcast(info);
4747        } else {
4748            info.setDetailedState(state, info.getReason(), info.getExtraInfo());
4749            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4750            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4751            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4752            if (info.isFailover()) {
4753                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4754                nai.networkInfo.setFailover(false);
4755            }
4756            if (info.getReason() != null) {
4757                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4758            }
4759            if (info.getExtraInfo() != null) {
4760                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4761            }
4762            NetworkAgentInfo newDefaultAgent = null;
4763            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4764                newDefaultAgent = getDefaultNetwork();
4765                if (newDefaultAgent != null) {
4766                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4767                            newDefaultAgent.networkInfo);
4768                } else {
4769                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4770                }
4771            }
4772            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4773                    mDefaultInetConditionPublished);
4774            sendStickyBroadcast(intent);
4775            if (newDefaultAgent != null) {
4776                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4777            }
4778        }
4779    }
4780
4781    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4782        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4783        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4784            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4785            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4786            if (VDBG) log(" sending notification for " + nr);
4787            if (nri.mPendingIntent == null) {
4788                callCallbackForRequest(nri, networkAgent, notifyType);
4789            } else {
4790                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4791            }
4792        }
4793    }
4794
4795    private String notifyTypeToName(int notifyType) {
4796        switch (notifyType) {
4797            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4798            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4799            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4800            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4801            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4802            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4803            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4804            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4805        }
4806        return "UNKNOWN";
4807    }
4808
4809    /**
4810     * Notify other system services that set of active ifaces has changed.
4811     */
4812    private void notifyIfacesChanged() {
4813        try {
4814            mStatsService.forceUpdateIfaces();
4815        } catch (Exception ignored) {
4816        }
4817    }
4818
4819    @Override
4820    public boolean addVpnAddress(String address, int prefixLength) {
4821        throwIfLockdownEnabled();
4822        int user = UserHandle.getUserId(Binder.getCallingUid());
4823        synchronized (mVpns) {
4824            return mVpns.get(user).addAddress(address, prefixLength);
4825        }
4826    }
4827
4828    @Override
4829    public boolean removeVpnAddress(String address, int prefixLength) {
4830        throwIfLockdownEnabled();
4831        int user = UserHandle.getUserId(Binder.getCallingUid());
4832        synchronized (mVpns) {
4833            return mVpns.get(user).removeAddress(address, prefixLength);
4834        }
4835    }
4836
4837    @Override
4838    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4839        throwIfLockdownEnabled();
4840        int user = UserHandle.getUserId(Binder.getCallingUid());
4841        boolean success;
4842        synchronized (mVpns) {
4843            success = mVpns.get(user).setUnderlyingNetworks(networks);
4844        }
4845        if (success) {
4846            notifyIfacesChanged();
4847        }
4848        return success;
4849    }
4850
4851    @Override
4852    public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4853            IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4854        enforceKeepalivePermission();
4855        mKeepaliveTracker.startNattKeepalive(
4856                getNetworkAgentInfoForNetwork(network),
4857                intervalSeconds, messenger, binder,
4858                srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4859    }
4860
4861    @Override
4862    public void stopKeepalive(Network network, int slot) {
4863        mHandler.sendMessage(mHandler.obtainMessage(
4864                NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4865    }
4866
4867    @Override
4868    public void factoryReset() {
4869        enforceConnectivityInternalPermission();
4870
4871        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4872            return;
4873        }
4874
4875        final int userId = UserHandle.getCallingUserId();
4876
4877        // Turn airplane mode off
4878        setAirplaneMode(false);
4879
4880        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4881            // Untether
4882            for (String tether : getTetheredIfaces()) {
4883                untether(tether);
4884            }
4885        }
4886
4887        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4888            // Turn VPN off
4889            VpnConfig vpnConfig = getVpnConfig(userId);
4890            if (vpnConfig != null) {
4891                if (vpnConfig.legacy) {
4892                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4893                } else {
4894                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4895                    // in the future without user intervention.
4896                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
4897
4898                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4899                }
4900            }
4901        }
4902    }
4903
4904    @VisibleForTesting
4905    public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4906            NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4907        return new NetworkMonitor(context, handler, nai, defaultRequest);
4908    }
4909
4910}
4911