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