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