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