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