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