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