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