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