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