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