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