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