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