ConnectivityService.java revision 4e8050ed5fe48fb97e266a84baefd2638a8773eb
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                                             15);
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, false);
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, nai.networkMisc.explicitlySelected);
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, true);
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 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2688            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2689            return;
2690        }
2691        // Revalidate if the app report does not match our current validated state.
2692        if (hasConnectivity == nai.lastValidated) return;
2693        final int uid = Binder.getCallingUid();
2694        if (DBG) {
2695            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2696                    ") by " + uid);
2697        }
2698        synchronized (nai) {
2699            // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2700            // which isn't meant to work on uncreated networks.
2701            if (!nai.created) return;
2702
2703            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
2704
2705            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2706        }
2707    }
2708
2709    public void captivePortalAppResponse(Network network, int response, String actionToken) {
2710        if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2711            enforceConnectivityInternalPermission();
2712        }
2713        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2714        if (nai == null) return;
2715        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2716                actionToken);
2717    }
2718
2719    private ProxyInfo getDefaultProxy() {
2720        // this information is already available as a world read/writable jvm property
2721        // so this API change wouldn't have a benifit.  It also breaks the passing
2722        // of proxy info to all the JVMs.
2723        // enforceAccessPermission();
2724        synchronized (mProxyLock) {
2725            ProxyInfo ret = mGlobalProxy;
2726            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2727            return ret;
2728        }
2729    }
2730
2731    public ProxyInfo getProxyForNetwork(Network network) {
2732        if (network == null) return getDefaultProxy();
2733        final ProxyInfo globalProxy = getGlobalProxy();
2734        if (globalProxy != null) return globalProxy;
2735        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2736        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2737        // caller may not have.
2738        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2739        if (nai == null) return null;
2740        synchronized (nai) {
2741            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2742            if (proxyInfo == null) return null;
2743            return new ProxyInfo(proxyInfo);
2744        }
2745    }
2746
2747    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2748    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2749    // proxy is null then there is no proxy in place).
2750    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2751        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2752                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2753            proxy = null;
2754        }
2755        return proxy;
2756    }
2757
2758    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2759    // better for determining if a new proxy broadcast is necessary:
2760    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2761    //    avoid unnecessary broadcasts.
2762    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2763    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2764    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2765    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2766    //    all set.
2767    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2768        a = canonicalizeProxyInfo(a);
2769        b = canonicalizeProxyInfo(b);
2770        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2771        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2772        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2773    }
2774
2775    public void setGlobalProxy(ProxyInfo proxyProperties) {
2776        enforceConnectivityInternalPermission();
2777
2778        synchronized (mProxyLock) {
2779            if (proxyProperties == mGlobalProxy) return;
2780            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2781            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2782
2783            String host = "";
2784            int port = 0;
2785            String exclList = "";
2786            String pacFileUrl = "";
2787            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2788                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2789                if (!proxyProperties.isValid()) {
2790                    if (DBG)
2791                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2792                    return;
2793                }
2794                mGlobalProxy = new ProxyInfo(proxyProperties);
2795                host = mGlobalProxy.getHost();
2796                port = mGlobalProxy.getPort();
2797                exclList = mGlobalProxy.getExclusionListAsString();
2798                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2799                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2800                }
2801            } else {
2802                mGlobalProxy = null;
2803            }
2804            ContentResolver res = mContext.getContentResolver();
2805            final long token = Binder.clearCallingIdentity();
2806            try {
2807                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2808                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2809                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2810                        exclList);
2811                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2812            } finally {
2813                Binder.restoreCallingIdentity(token);
2814            }
2815
2816            if (mGlobalProxy == null) {
2817                proxyProperties = mDefaultProxy;
2818            }
2819            sendProxyBroadcast(proxyProperties);
2820        }
2821    }
2822
2823    private void loadGlobalProxy() {
2824        ContentResolver res = mContext.getContentResolver();
2825        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2826        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2827        String exclList = Settings.Global.getString(res,
2828                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2829        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2830        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2831            ProxyInfo proxyProperties;
2832            if (!TextUtils.isEmpty(pacFileUrl)) {
2833                proxyProperties = new ProxyInfo(pacFileUrl);
2834            } else {
2835                proxyProperties = new ProxyInfo(host, port, exclList);
2836            }
2837            if (!proxyProperties.isValid()) {
2838                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2839                return;
2840            }
2841
2842            synchronized (mProxyLock) {
2843                mGlobalProxy = proxyProperties;
2844            }
2845        }
2846    }
2847
2848    public ProxyInfo getGlobalProxy() {
2849        // this information is already available as a world read/writable jvm property
2850        // so this API change wouldn't have a benifit.  It also breaks the passing
2851        // of proxy info to all the JVMs.
2852        // enforceAccessPermission();
2853        synchronized (mProxyLock) {
2854            return mGlobalProxy;
2855        }
2856    }
2857
2858    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2859        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2860                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2861            proxy = null;
2862        }
2863        synchronized (mProxyLock) {
2864            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2865            if (mDefaultProxy == proxy) return; // catches repeated nulls
2866            if (proxy != null &&  !proxy.isValid()) {
2867                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2868                return;
2869            }
2870
2871            // This call could be coming from the PacManager, containing the port of the local
2872            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2873            // global (to get the correct local port), and send a broadcast.
2874            // TODO: Switch PacManager to have its own message to send back rather than
2875            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2876            if ((mGlobalProxy != null) && (proxy != null)
2877                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2878                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2879                mGlobalProxy = proxy;
2880                sendProxyBroadcast(mGlobalProxy);
2881                return;
2882            }
2883            mDefaultProxy = proxy;
2884
2885            if (mGlobalProxy != null) return;
2886            if (!mDefaultProxyDisabled) {
2887                sendProxyBroadcast(proxy);
2888            }
2889        }
2890    }
2891
2892    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2893    // This method gets called when any network changes proxy, but the broadcast only ever contains
2894    // the default proxy (even if it hasn't changed).
2895    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2896    // world where an app might be bound to a non-default network.
2897    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2898        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2899        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2900
2901        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2902            sendProxyBroadcast(getDefaultProxy());
2903        }
2904    }
2905
2906    private void handleDeprecatedGlobalHttpProxy() {
2907        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2908                Settings.Global.HTTP_PROXY);
2909        if (!TextUtils.isEmpty(proxy)) {
2910            String data[] = proxy.split(":");
2911            if (data.length == 0) {
2912                return;
2913            }
2914
2915            String proxyHost =  data[0];
2916            int proxyPort = 8080;
2917            if (data.length > 1) {
2918                try {
2919                    proxyPort = Integer.parseInt(data[1]);
2920                } catch (NumberFormatException e) {
2921                    return;
2922                }
2923            }
2924            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2925            setGlobalProxy(p);
2926        }
2927    }
2928
2929    private void sendProxyBroadcast(ProxyInfo proxy) {
2930        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2931        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2932        if (DBG) log("sending Proxy Broadcast for " + proxy);
2933        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2934        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2935            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2936        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2937        final long ident = Binder.clearCallingIdentity();
2938        try {
2939            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2940        } finally {
2941            Binder.restoreCallingIdentity(ident);
2942        }
2943    }
2944
2945    private static class SettingsObserver extends ContentObserver {
2946        final private HashMap<Uri, Integer> mUriEventMap;
2947        final private Context mContext;
2948        final private Handler mHandler;
2949
2950        SettingsObserver(Context context, Handler handler) {
2951            super(null);
2952            mUriEventMap = new HashMap<Uri, Integer>();
2953            mContext = context;
2954            mHandler = handler;
2955        }
2956
2957        void observe(Uri uri, int what) {
2958            mUriEventMap.put(uri, what);
2959            final ContentResolver resolver = mContext.getContentResolver();
2960            resolver.registerContentObserver(uri, false, this);
2961        }
2962
2963        @Override
2964        public void onChange(boolean selfChange) {
2965            Slog.wtf(TAG, "Should never be reached.");
2966        }
2967
2968        @Override
2969        public void onChange(boolean selfChange, Uri uri) {
2970            final Integer what = mUriEventMap.get(uri);
2971            if (what != null) {
2972                mHandler.obtainMessage(what.intValue()).sendToTarget();
2973            } else {
2974                loge("No matching event to send for URI=" + uri);
2975            }
2976        }
2977    }
2978
2979    private static void log(String s) {
2980        Slog.d(TAG, s);
2981    }
2982
2983    private static void loge(String s) {
2984        Slog.e(TAG, s);
2985    }
2986
2987    private static <T> T checkNotNull(T value, String message) {
2988        if (value == null) {
2989            throw new NullPointerException(message);
2990        }
2991        return value;
2992    }
2993
2994    /**
2995     * Prepare for a VPN application.
2996     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2997     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2998     *
2999     * @param oldPackage Package name of the application which currently controls VPN, which will
3000     *                   be replaced. If there is no such application, this should should either be
3001     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3002     * @param newPackage Package name of the application which should gain control of VPN, or
3003     *                   {@code null} to disable.
3004     * @param userId User for whom to prepare the new VPN.
3005     *
3006     * @hide
3007     */
3008    @Override
3009    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3010            int userId) {
3011        enforceCrossUserPermission(userId);
3012        throwIfLockdownEnabled();
3013
3014        synchronized(mVpns) {
3015            Vpn vpn = mVpns.get(userId);
3016            if (vpn != null) {
3017                return vpn.prepare(oldPackage, newPackage);
3018            } else {
3019                return false;
3020            }
3021        }
3022    }
3023
3024    /**
3025     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3026     * This method is used by system-privileged apps.
3027     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3028     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3029     *
3030     * @param packageName The package for which authorization state should change.
3031     * @param userId User for whom {@code packageName} is installed.
3032     * @param authorized {@code true} if this app should be able to start a VPN connection without
3033     *                   explicit user approval, {@code false} if not.
3034     *
3035     * @hide
3036     */
3037    @Override
3038    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3039        enforceCrossUserPermission(userId);
3040
3041        synchronized(mVpns) {
3042            Vpn vpn = mVpns.get(userId);
3043            if (vpn != null) {
3044                vpn.setPackageAuthorization(packageName, authorized);
3045            }
3046        }
3047    }
3048
3049    /**
3050     * Configure a TUN interface and return its file descriptor. Parameters
3051     * are encoded and opaque to this class. This method is used by VpnBuilder
3052     * and not available in ConnectivityManager. Permissions are checked in
3053     * Vpn class.
3054     * @hide
3055     */
3056    @Override
3057    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3058        throwIfLockdownEnabled();
3059        int user = UserHandle.getUserId(Binder.getCallingUid());
3060        synchronized(mVpns) {
3061            return mVpns.get(user).establish(config);
3062        }
3063    }
3064
3065    /**
3066     * Start legacy VPN, controlling native daemons as needed. Creates a
3067     * secondary thread to perform connection work, returning quickly.
3068     */
3069    @Override
3070    public void startLegacyVpn(VpnProfile profile) {
3071        throwIfLockdownEnabled();
3072        final LinkProperties egress = getActiveLinkProperties();
3073        if (egress == null) {
3074            throw new IllegalStateException("Missing active network connection");
3075        }
3076        int user = UserHandle.getUserId(Binder.getCallingUid());
3077        synchronized(mVpns) {
3078            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3079        }
3080    }
3081
3082    /**
3083     * Return the information of the ongoing legacy VPN. This method is used
3084     * by VpnSettings and not available in ConnectivityManager. Permissions
3085     * are checked in Vpn class.
3086     */
3087    @Override
3088    public LegacyVpnInfo getLegacyVpnInfo() {
3089        throwIfLockdownEnabled();
3090        int user = UserHandle.getUserId(Binder.getCallingUid());
3091        synchronized(mVpns) {
3092            return mVpns.get(user).getLegacyVpnInfo();
3093        }
3094    }
3095
3096    /**
3097     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3098     * and not available in ConnectivityManager.
3099     */
3100    @Override
3101    public VpnInfo[] getAllVpnInfo() {
3102        enforceConnectivityInternalPermission();
3103        if (mLockdownEnabled) {
3104            return new VpnInfo[0];
3105        }
3106
3107        synchronized(mVpns) {
3108            List<VpnInfo> infoList = new ArrayList<>();
3109            for (int i = 0; i < mVpns.size(); i++) {
3110                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3111                if (info != null) {
3112                    infoList.add(info);
3113                }
3114            }
3115            return infoList.toArray(new VpnInfo[infoList.size()]);
3116        }
3117    }
3118
3119    /**
3120     * @return VPN information for accounting, or null if we can't retrieve all required
3121     *         information, e.g primary underlying iface.
3122     */
3123    @Nullable
3124    private VpnInfo createVpnInfo(Vpn vpn) {
3125        VpnInfo info = vpn.getVpnInfo();
3126        if (info == null) {
3127            return null;
3128        }
3129        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3130        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3131        // the underlyingNetworks list.
3132        if (underlyingNetworks == null) {
3133            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3134            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3135                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3136            }
3137        } else if (underlyingNetworks.length > 0) {
3138            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3139            if (linkProperties != null) {
3140                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3141            }
3142        }
3143        return info.primaryUnderlyingIface == null ? null : info;
3144    }
3145
3146    /**
3147     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3148     * VpnDialogs and not available in ConnectivityManager.
3149     * Permissions are checked in Vpn class.
3150     * @hide
3151     */
3152    @Override
3153    public VpnConfig getVpnConfig(int userId) {
3154        enforceCrossUserPermission(userId);
3155        synchronized(mVpns) {
3156            Vpn vpn = mVpns.get(userId);
3157            if (vpn != null) {
3158                return vpn.getVpnConfig();
3159            } else {
3160                return null;
3161            }
3162        }
3163    }
3164
3165    @Override
3166    public boolean updateLockdownVpn() {
3167        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3168            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3169            return false;
3170        }
3171
3172        // Tear down existing lockdown if profile was removed
3173        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3174        if (mLockdownEnabled) {
3175            if (!mKeyStore.isUnlocked()) {
3176                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3177                return false;
3178            }
3179
3180            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3181            final VpnProfile profile = VpnProfile.decode(
3182                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3183            int user = UserHandle.getUserId(Binder.getCallingUid());
3184            synchronized(mVpns) {
3185                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3186                            profile));
3187            }
3188        } else {
3189            setLockdownTracker(null);
3190        }
3191
3192        return true;
3193    }
3194
3195    /**
3196     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3197     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3198     */
3199    private void setLockdownTracker(LockdownVpnTracker tracker) {
3200        // Shutdown any existing tracker
3201        final LockdownVpnTracker existing = mLockdownTracker;
3202        mLockdownTracker = null;
3203        if (existing != null) {
3204            existing.shutdown();
3205        }
3206
3207        try {
3208            if (tracker != null) {
3209                mNetd.setFirewallEnabled(true);
3210                mNetd.setFirewallInterfaceRule("lo", true);
3211                mLockdownTracker = tracker;
3212                mLockdownTracker.init();
3213            } else {
3214                mNetd.setFirewallEnabled(false);
3215            }
3216        } catch (RemoteException e) {
3217            // ignored; NMS lives inside system_server
3218        }
3219    }
3220
3221    private void throwIfLockdownEnabled() {
3222        if (mLockdownEnabled) {
3223            throw new IllegalStateException("Unavailable in lockdown mode");
3224        }
3225    }
3226
3227    @Override
3228    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3229        // TODO: Remove?  Any reason to trigger a provisioning check?
3230        return -1;
3231    }
3232
3233    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3234    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3235
3236    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3237        if (DBG) {
3238            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3239                + " action=" + action);
3240        }
3241        Intent intent = new Intent(action);
3242        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3243        // Concatenate the range of types onto the range of NetIDs.
3244        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3245        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3246                networkType, null, pendingIntent, false);
3247    }
3248
3249    /**
3250     * Show or hide network provisioning notifications.
3251     *
3252     * We use notifications for two purposes: to notify that a network requires sign in
3253     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3254     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3255     * particular network we can display the notification type that was most recently requested.
3256     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3257     * might first display NO_INTERNET, and then when the captive portal check completes, display
3258     * SIGN_IN.
3259     *
3260     * @param id an identifier that uniquely identifies this notification.  This must match
3261     *         between show and hide calls.  We use the NetID value but for legacy callers
3262     *         we concatenate the range of types with the range of NetIDs.
3263     */
3264    private void setProvNotificationVisibleIntent(boolean visible, int id,
3265            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3266            boolean highPriority) {
3267        if (DBG) {
3268            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3269                    + " networkType=" + getNetworkTypeName(networkType)
3270                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3271        }
3272
3273        Resources r = Resources.getSystem();
3274        NotificationManager notificationManager = (NotificationManager) mContext
3275            .getSystemService(Context.NOTIFICATION_SERVICE);
3276
3277        if (visible) {
3278            CharSequence title;
3279            CharSequence details;
3280            int icon;
3281            if (notifyType == NotificationType.NO_INTERNET &&
3282                    networkType == ConnectivityManager.TYPE_WIFI) {
3283                title = r.getString(R.string.wifi_no_internet, 0);
3284                details = r.getString(R.string.wifi_no_internet_detailed);
3285                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3286            } else if (notifyType == NotificationType.SIGN_IN) {
3287                switch (networkType) {
3288                    case ConnectivityManager.TYPE_WIFI:
3289                        title = r.getString(R.string.wifi_available_sign_in, 0);
3290                        details = r.getString(R.string.network_available_sign_in_detailed,
3291                                extraInfo);
3292                        icon = R.drawable.stat_notify_wifi_in_range;
3293                        break;
3294                    case ConnectivityManager.TYPE_MOBILE:
3295                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3296                        title = r.getString(R.string.network_available_sign_in, 0);
3297                        // TODO: Change this to pull from NetworkInfo once a printable
3298                        // name has been added to it
3299                        details = mTelephonyManager.getNetworkOperatorName();
3300                        icon = R.drawable.stat_notify_rssi_in_range;
3301                        break;
3302                    default:
3303                        title = r.getString(R.string.network_available_sign_in, 0);
3304                        details = r.getString(R.string.network_available_sign_in_detailed,
3305                                extraInfo);
3306                        icon = R.drawable.stat_notify_rssi_in_range;
3307                        break;
3308                }
3309            } else {
3310                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3311                        + getNetworkTypeName(networkType));
3312                return;
3313            }
3314
3315            Notification notification = new Notification.Builder(mContext)
3316                    .setWhen(0)
3317                    .setSmallIcon(icon)
3318                    .setAutoCancel(true)
3319                    .setTicker(title)
3320                    .setColor(mContext.getColor(
3321                            com.android.internal.R.color.system_notification_accent_color))
3322                    .setContentTitle(title)
3323                    .setContentText(details)
3324                    .setContentIntent(intent)
3325                    .setLocalOnly(true)
3326                    .setPriority(highPriority ?
3327                            Notification.PRIORITY_HIGH :
3328                            Notification.PRIORITY_DEFAULT)
3329                    .setDefaults(Notification.DEFAULT_ALL)
3330                    .setOnlyAlertOnce(true)
3331                    .build();
3332
3333            try {
3334                notificationManager.notify(NOTIFICATION_ID, id, notification);
3335            } catch (NullPointerException npe) {
3336                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3337                npe.printStackTrace();
3338            }
3339        } else {
3340            try {
3341                notificationManager.cancel(NOTIFICATION_ID, id);
3342            } catch (NullPointerException npe) {
3343                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3344                npe.printStackTrace();
3345            }
3346        }
3347    }
3348
3349    /** Location to an updatable file listing carrier provisioning urls.
3350     *  An example:
3351     *
3352     * <?xml version="1.0" encoding="utf-8"?>
3353     *  <provisioningUrls>
3354     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3355     *  </provisioningUrls>
3356     */
3357    private static final String PROVISIONING_URL_PATH =
3358            "/data/misc/radio/provisioning_urls.xml";
3359    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3360
3361    /** XML tag for root element. */
3362    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3363    /** XML tag for individual url */
3364    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3365    /** XML attribute for mcc */
3366    private static final String ATTR_MCC = "mcc";
3367    /** XML attribute for mnc */
3368    private static final String ATTR_MNC = "mnc";
3369
3370    private String getProvisioningUrlBaseFromFile() {
3371        FileReader fileReader = null;
3372        XmlPullParser parser = null;
3373        Configuration config = mContext.getResources().getConfiguration();
3374
3375        try {
3376            fileReader = new FileReader(mProvisioningUrlFile);
3377            parser = Xml.newPullParser();
3378            parser.setInput(fileReader);
3379            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3380
3381            while (true) {
3382                XmlUtils.nextElement(parser);
3383
3384                String element = parser.getName();
3385                if (element == null) break;
3386
3387                if (element.equals(TAG_PROVISIONING_URL)) {
3388                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3389                    try {
3390                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3391                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3392                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3393                                parser.next();
3394                                if (parser.getEventType() == XmlPullParser.TEXT) {
3395                                    return parser.getText();
3396                                }
3397                            }
3398                        }
3399                    } catch (NumberFormatException e) {
3400                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3401                    }
3402                }
3403            }
3404            return null;
3405        } catch (FileNotFoundException e) {
3406            loge("Carrier Provisioning Urls file not found");
3407        } catch (XmlPullParserException e) {
3408            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3409        } catch (IOException e) {
3410            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3411        } finally {
3412            if (fileReader != null) {
3413                try {
3414                    fileReader.close();
3415                } catch (IOException e) {}
3416            }
3417        }
3418        return null;
3419    }
3420
3421    @Override
3422    public String getMobileProvisioningUrl() {
3423        enforceConnectivityInternalPermission();
3424        String url = getProvisioningUrlBaseFromFile();
3425        if (TextUtils.isEmpty(url)) {
3426            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3427            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3428        } else {
3429            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3430        }
3431        // populate the iccid, imei and phone number in the provisioning url.
3432        if (!TextUtils.isEmpty(url)) {
3433            String phoneNumber = mTelephonyManager.getLine1Number();
3434            if (TextUtils.isEmpty(phoneNumber)) {
3435                phoneNumber = "0000000000";
3436            }
3437            url = String.format(url,
3438                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3439                    mTelephonyManager.getDeviceId() /* IMEI */,
3440                    phoneNumber /* Phone numer */);
3441        }
3442
3443        return url;
3444    }
3445
3446    @Override
3447    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3448            String action) {
3449        enforceConnectivityInternalPermission();
3450        final long ident = Binder.clearCallingIdentity();
3451        try {
3452            setProvNotificationVisible(visible, networkType, action);
3453        } finally {
3454            Binder.restoreCallingIdentity(ident);
3455        }
3456    }
3457
3458    @Override
3459    public void setAirplaneMode(boolean enable) {
3460        enforceConnectivityInternalPermission();
3461        final long ident = Binder.clearCallingIdentity();
3462        try {
3463            final ContentResolver cr = mContext.getContentResolver();
3464            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3465            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3466            intent.putExtra("state", enable);
3467            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3468        } finally {
3469            Binder.restoreCallingIdentity(ident);
3470        }
3471    }
3472
3473    private void onUserStart(int userId) {
3474        synchronized(mVpns) {
3475            Vpn userVpn = mVpns.get(userId);
3476            if (userVpn != null) {
3477                loge("Starting user already has a VPN");
3478                return;
3479            }
3480            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3481            mVpns.put(userId, userVpn);
3482        }
3483    }
3484
3485    private void onUserStop(int userId) {
3486        synchronized(mVpns) {
3487            Vpn userVpn = mVpns.get(userId);
3488            if (userVpn == null) {
3489                loge("Stopping user has no VPN");
3490                return;
3491            }
3492            mVpns.delete(userId);
3493        }
3494    }
3495
3496    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3497        @Override
3498        public void onReceive(Context context, Intent intent) {
3499            final String action = intent.getAction();
3500            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3501            if (userId == UserHandle.USER_NULL) return;
3502
3503            if (Intent.ACTION_USER_STARTING.equals(action)) {
3504                onUserStart(userId);
3505            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3506                onUserStop(userId);
3507            }
3508        }
3509    };
3510
3511    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3512            new HashMap<Messenger, NetworkFactoryInfo>();
3513    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3514            new HashMap<NetworkRequest, NetworkRequestInfo>();
3515
3516    private static class NetworkFactoryInfo {
3517        public final String name;
3518        public final Messenger messenger;
3519        public final AsyncChannel asyncChannel;
3520
3521        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3522            this.name = name;
3523            this.messenger = messenger;
3524            this.asyncChannel = asyncChannel;
3525        }
3526    }
3527
3528    /**
3529     * Tracks info about the requester.
3530     * Also used to notice when the calling process dies so we can self-expire
3531     */
3532    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3533        static final boolean REQUEST = true;
3534        static final boolean LISTEN = false;
3535
3536        final NetworkRequest request;
3537        final PendingIntent mPendingIntent;
3538        boolean mPendingIntentSent;
3539        private final IBinder mBinder;
3540        final int mPid;
3541        final int mUid;
3542        final Messenger messenger;
3543        final boolean isRequest;
3544
3545        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3546            request = r;
3547            mPendingIntent = pi;
3548            messenger = null;
3549            mBinder = null;
3550            mPid = getCallingPid();
3551            mUid = getCallingUid();
3552            this.isRequest = isRequest;
3553        }
3554
3555        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3556            super();
3557            messenger = m;
3558            request = r;
3559            mBinder = binder;
3560            mPid = getCallingPid();
3561            mUid = getCallingUid();
3562            this.isRequest = isRequest;
3563            mPendingIntent = null;
3564
3565            try {
3566                mBinder.linkToDeath(this, 0);
3567            } catch (RemoteException e) {
3568                binderDied();
3569            }
3570        }
3571
3572        void unlinkDeathRecipient() {
3573            if (mBinder != null) {
3574                mBinder.unlinkToDeath(this, 0);
3575            }
3576        }
3577
3578        public void binderDied() {
3579            log("ConnectivityService NetworkRequestInfo binderDied(" +
3580                    request + ", " + mBinder + ")");
3581            releaseNetworkRequest(request);
3582        }
3583
3584        public String toString() {
3585            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
3586                    mPid + " for " + request +
3587                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3588        }
3589    }
3590
3591    private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3592        if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3593            throw new IllegalArgumentException(
3594                    "Cannot request network with NET_CAPABILITY_VALIDATED");
3595        }
3596        if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3597            throw new IllegalArgumentException(
3598                    "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3599        }
3600    }
3601
3602    @Override
3603    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3604            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3605        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3606        enforceNetworkRequestPermissions(networkCapabilities);
3607        enforceMeteredApnPolicy(networkCapabilities);
3608        ensureImmutableCapabilities(networkCapabilities);
3609
3610        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3611            throw new IllegalArgumentException("Bad timeout specified");
3612        }
3613
3614        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3615                nextNetworkRequestId());
3616        if (DBG) log("requestNetwork for " + networkRequest);
3617        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3618                NetworkRequestInfo.REQUEST);
3619
3620        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3621        if (timeoutMs > 0) {
3622            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3623                    nri), timeoutMs);
3624        }
3625        return networkRequest;
3626    }
3627
3628    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3629        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3630            enforceConnectivityInternalPermission();
3631        } else {
3632            enforceChangePermission();
3633        }
3634    }
3635
3636    @Override
3637    public boolean requestBandwidthUpdate(Network network) {
3638        enforceAccessPermission();
3639        NetworkAgentInfo nai = null;
3640        if (network == null) {
3641            return false;
3642        }
3643        synchronized (mNetworkForNetId) {
3644            nai = mNetworkForNetId.get(network.netId);
3645        }
3646        if (nai != null) {
3647            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3648            return true;
3649        }
3650        return false;
3651    }
3652
3653
3654    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3655        // if UID is restricted, don't allow them to bring up metered APNs
3656        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3657            final int uidRules;
3658            final int uid = Binder.getCallingUid();
3659            synchronized(mRulesLock) {
3660                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3661            }
3662            if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
3663                // we could silently fail or we can filter the available nets to only give
3664                // them those they have access to.  Chose the more useful
3665                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3666            }
3667        }
3668    }
3669
3670    @Override
3671    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3672            PendingIntent operation) {
3673        checkNotNull(operation, "PendingIntent cannot be null.");
3674        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3675        enforceNetworkRequestPermissions(networkCapabilities);
3676        enforceMeteredApnPolicy(networkCapabilities);
3677        ensureImmutableCapabilities(networkCapabilities);
3678
3679        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3680                nextNetworkRequestId());
3681        if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3682        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3683                NetworkRequestInfo.REQUEST);
3684        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3685                nri));
3686        return networkRequest;
3687    }
3688
3689    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3690        mHandler.sendMessageDelayed(
3691                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3692                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3693    }
3694
3695    @Override
3696    public void releasePendingNetworkRequest(PendingIntent operation) {
3697        checkNotNull(operation, "PendingIntent cannot be null.");
3698        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3699                getCallingUid(), 0, operation));
3700    }
3701
3702    // In order to implement the compatibility measure for pre-M apps that call
3703    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3704    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3705    // This ensures it has permission to do so.
3706    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3707        if (nc == null) {
3708            return false;
3709        }
3710        int[] transportTypes = nc.getTransportTypes();
3711        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3712            return false;
3713        }
3714        try {
3715            mContext.enforceCallingOrSelfPermission(
3716                    android.Manifest.permission.ACCESS_WIFI_STATE,
3717                    "ConnectivityService");
3718        } catch (SecurityException e) {
3719            return false;
3720        }
3721        return true;
3722    }
3723
3724    @Override
3725    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3726            Messenger messenger, IBinder binder) {
3727        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3728            enforceAccessPermission();
3729        }
3730
3731        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3732                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3733        if (DBG) log("listenForNetwork for " + networkRequest);
3734        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3735                NetworkRequestInfo.LISTEN);
3736
3737        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3738        return networkRequest;
3739    }
3740
3741    @Override
3742    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3743            PendingIntent operation) {
3744        checkNotNull(operation, "PendingIntent cannot be null.");
3745        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3746            enforceAccessPermission();
3747        }
3748
3749        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3750                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3751        if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3752        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3753                NetworkRequestInfo.LISTEN);
3754
3755        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3756    }
3757
3758    @Override
3759    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3760        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3761                0, networkRequest));
3762    }
3763
3764    @Override
3765    public void registerNetworkFactory(Messenger messenger, String name) {
3766        enforceConnectivityInternalPermission();
3767        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3768        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3769    }
3770
3771    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3772        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3773        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3774        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3775    }
3776
3777    @Override
3778    public void unregisterNetworkFactory(Messenger messenger) {
3779        enforceConnectivityInternalPermission();
3780        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3781    }
3782
3783    private void handleUnregisterNetworkFactory(Messenger messenger) {
3784        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3785        if (nfi == null) {
3786            loge("Failed to find Messenger in unregisterNetworkFactory");
3787            return;
3788        }
3789        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3790    }
3791
3792    /**
3793     * NetworkAgentInfo supporting a request by requestId.
3794     * These have already been vetted (their Capabilities satisfy the request)
3795     * and the are the highest scored network available.
3796     * the are keyed off the Requests requestId.
3797     */
3798    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3799    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3800            new SparseArray<NetworkAgentInfo>();
3801
3802    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3803    @GuardedBy("mNetworkForNetId")
3804    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3805            new SparseArray<NetworkAgentInfo>();
3806    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3807    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3808    // there may not be a strict 1:1 correlation between the two.
3809    @GuardedBy("mNetworkForNetId")
3810    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3811
3812    // NetworkAgentInfo keyed off its connecting messenger
3813    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3814    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3815    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3816            new HashMap<Messenger, NetworkAgentInfo>();
3817
3818    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3819    private final NetworkRequest mDefaultRequest;
3820
3821    // Request used to optionally keep mobile data active even when higher
3822    // priority networks like Wi-Fi are active.
3823    private final NetworkRequest mDefaultMobileDataRequest;
3824
3825    private NetworkAgentInfo getDefaultNetwork() {
3826        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3827    }
3828
3829    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3830        return nai == getDefaultNetwork();
3831    }
3832
3833    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3834            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3835            int currentScore, NetworkMisc networkMisc) {
3836        enforceConnectivityInternalPermission();
3837
3838        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3839        // satisfies mDefaultRequest.
3840        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3841                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3842                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3843                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
3844        synchronized (this) {
3845            nai.networkMonitor.systemReady = mSystemReady;
3846        }
3847        if (DBG) log("registerNetworkAgent " + nai);
3848        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3849        return nai.network.netId;
3850    }
3851
3852    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3853        if (VDBG) log("Got NetworkAgent Messenger");
3854        mNetworkAgentInfos.put(na.messenger, na);
3855        synchronized (mNetworkForNetId) {
3856            mNetworkForNetId.put(na.network.netId, na);
3857        }
3858        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3859        NetworkInfo networkInfo = na.networkInfo;
3860        na.networkInfo = null;
3861        updateNetworkInfo(na, networkInfo);
3862    }
3863
3864    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3865        LinkProperties newLp = networkAgent.linkProperties;
3866        int netId = networkAgent.network.netId;
3867
3868        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3869        // we do anything else, make sure its LinkProperties are accurate.
3870        if (networkAgent.clatd != null) {
3871            networkAgent.clatd.fixupLinkProperties(oldLp);
3872        }
3873
3874        updateInterfaces(newLp, oldLp, netId);
3875        updateMtu(newLp, oldLp);
3876        // TODO - figure out what to do for clat
3877//        for (LinkProperties lp : newLp.getStackedLinks()) {
3878//            updateMtu(lp, null);
3879//        }
3880        updateTcpBufferSizes(networkAgent);
3881
3882        // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3883        // In L, we used it only when the network had Internet access but provided no DNS servers.
3884        // For now, just disable it, and if disabling it doesn't break things, remove it.
3885        // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3886        //        NET_CAPABILITY_INTERNET);
3887        final boolean useDefaultDns = false;
3888        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3889        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3890
3891        updateClat(newLp, oldLp, networkAgent);
3892        if (isDefaultNetwork(networkAgent)) {
3893            handleApplyDefaultProxy(newLp.getHttpProxy());
3894        } else {
3895            updateProxy(newLp, oldLp, networkAgent);
3896        }
3897        // TODO - move this check to cover the whole function
3898        if (!Objects.equals(newLp, oldLp)) {
3899            notifyIfacesChanged();
3900            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3901        }
3902    }
3903
3904    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3905        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3906        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
3907
3908        if (!wasRunningClat && shouldRunClat) {
3909            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3910            nai.clatd.start();
3911        } else if (wasRunningClat && !shouldRunClat) {
3912            nai.clatd.stop();
3913        }
3914    }
3915
3916    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3917        CompareResult<String> interfaceDiff = new CompareResult<String>();
3918        if (oldLp != null) {
3919            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3920        } else if (newLp != null) {
3921            interfaceDiff.added = newLp.getAllInterfaceNames();
3922        }
3923        for (String iface : interfaceDiff.added) {
3924            try {
3925                if (DBG) log("Adding iface " + iface + " to network " + netId);
3926                mNetd.addInterfaceToNetwork(iface, netId);
3927            } catch (Exception e) {
3928                loge("Exception adding interface: " + e);
3929            }
3930        }
3931        for (String iface : interfaceDiff.removed) {
3932            try {
3933                if (DBG) log("Removing iface " + iface + " from network " + netId);
3934                mNetd.removeInterfaceFromNetwork(iface, netId);
3935            } catch (Exception e) {
3936                loge("Exception removing interface: " + e);
3937            }
3938        }
3939    }
3940
3941    /**
3942     * Have netd update routes from oldLp to newLp.
3943     * @return true if routes changed between oldLp and newLp
3944     */
3945    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
3946        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3947        if (oldLp != null) {
3948            routeDiff = oldLp.compareAllRoutes(newLp);
3949        } else if (newLp != null) {
3950            routeDiff.added = newLp.getAllRoutes();
3951        }
3952
3953        // add routes before removing old in case it helps with continuous connectivity
3954
3955        // do this twice, adding non-nexthop routes first, then routes they are dependent on
3956        for (RouteInfo route : routeDiff.added) {
3957            if (route.hasGateway()) continue;
3958            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3959            try {
3960                mNetd.addRoute(netId, route);
3961            } catch (Exception e) {
3962                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3963                    loge("Exception in addRoute for non-gateway: " + e);
3964                }
3965            }
3966        }
3967        for (RouteInfo route : routeDiff.added) {
3968            if (route.hasGateway() == false) continue;
3969            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3970            try {
3971                mNetd.addRoute(netId, route);
3972            } catch (Exception e) {
3973                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3974                    loge("Exception in addRoute for gateway: " + e);
3975                }
3976            }
3977        }
3978
3979        for (RouteInfo route : routeDiff.removed) {
3980            if (DBG) log("Removing Route [" + route + "] from network " + netId);
3981            try {
3982                mNetd.removeRoute(netId, route);
3983            } catch (Exception e) {
3984                loge("Exception in removeRoute: " + e);
3985            }
3986        }
3987        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
3988    }
3989
3990    // TODO: investigate moving this into LinkProperties, if only to make more accurate
3991    // the isProvisioned() checks.
3992    private static Collection<InetAddress> getLikelyReachableDnsServers(LinkProperties lp) {
3993        final ArrayList<InetAddress> dnsServers = new ArrayList<InetAddress>();
3994        final List<RouteInfo> allRoutes = lp.getAllRoutes();
3995        for (InetAddress nameserver : lp.getDnsServers()) {
3996            // If the LinkProperties doesn't include a route to the nameserver, ignore it.
3997            final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, nameserver);
3998            if (bestRoute == null) {
3999                continue;
4000            }
4001
4002            // TODO: better source address evaluation for destination addresses.
4003            if (nameserver instanceof Inet4Address) {
4004                if (!lp.hasIPv4Address()) {
4005                    continue;
4006                }
4007            } else if (nameserver instanceof Inet6Address) {
4008                if (nameserver.isLinkLocalAddress()) {
4009                    if (((Inet6Address)nameserver).getScopeId() == 0) {
4010                        // For now, just make sure link-local DNS servers have
4011                        // scopedIds set, since DNS lookups will fail otherwise.
4012                        // TODO: verify the scopeId matches that of lp's interface.
4013                        continue;
4014                    }
4015                }  else {
4016                    if (bestRoute.isIPv6Default() && !lp.hasGlobalIPv6Address()) {
4017                        // TODO: reconsider all corner cases (disconnected ULA networks, ...).
4018                        continue;
4019                    }
4020                }
4021            }
4022
4023            dnsServers.add(nameserver);
4024        }
4025        return Collections.unmodifiableList(dnsServers);
4026    }
4027
4028    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4029                             boolean flush, boolean useDefaultDns) {
4030        // TODO: consider comparing the getLikelyReachableDnsServers() lists, in case the
4031        // route to a DNS server has been removed (only really applicable in special cases
4032        // where there is no default route).
4033        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4034            Collection<InetAddress> dnses = getLikelyReachableDnsServers(newLp);
4035            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
4036                dnses = new ArrayList();
4037                dnses.add(mDefaultDns);
4038                if (DBG) {
4039                    loge("no dns provided for netId " + netId + ", so using defaults");
4040                }
4041            }
4042            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4043            try {
4044                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4045                    newLp.getDomains());
4046            } catch (Exception e) {
4047                loge("Exception in setDnsServersForNetwork: " + e);
4048            }
4049            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4050            if (defaultNai != null && defaultNai.network.netId == netId) {
4051                setDefaultDnsSystemProperties(dnses);
4052            }
4053            flushVmDnsCache();
4054        } else if (flush) {
4055            try {
4056                mNetd.flushNetworkDnsCache(netId);
4057            } catch (Exception e) {
4058                loge("Exception in flushNetworkDnsCache: " + e);
4059            }
4060            flushVmDnsCache();
4061        }
4062    }
4063
4064    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4065        int last = 0;
4066        for (InetAddress dns : dnses) {
4067            ++last;
4068            String key = "net.dns" + last;
4069            String value = dns.getHostAddress();
4070            SystemProperties.set(key, value);
4071        }
4072        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4073            String key = "net.dns" + i;
4074            SystemProperties.set(key, "");
4075        }
4076        mNumDnsEntries = last;
4077    }
4078
4079    /**
4080     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4081     * augmented with any stateful capabilities implied from {@code networkAgent}
4082     * (e.g., validated status and captive portal status).
4083     *
4084     * @param networkAgent the network having its capabilities updated.
4085     * @param networkCapabilities the new network capabilities.
4086     * @param nascent indicates whether {@code networkAgent} was validated
4087     *         (i.e. had everValidated set for the first time) immediately prior to this call.
4088     */
4089    private void updateCapabilities(NetworkAgentInfo networkAgent,
4090            NetworkCapabilities networkCapabilities, NascentState nascent) {
4091        // Don't modify caller's NetworkCapabilities.
4092        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4093        if (networkAgent.lastValidated) {
4094            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4095        } else {
4096            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4097        }
4098        if (networkAgent.lastCaptivePortalDetected) {
4099            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4100        } else {
4101            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4102        }
4103        if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4104            synchronized (networkAgent) {
4105                networkAgent.networkCapabilities = networkCapabilities;
4106            }
4107            rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore(), nascent);
4108            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
4109        }
4110    }
4111
4112    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4113        for (int i = 0; i < nai.networkRequests.size(); i++) {
4114            NetworkRequest nr = nai.networkRequests.valueAt(i);
4115            // Don't send listening requests to factories. b/17393458
4116            if (!isRequest(nr)) continue;
4117            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4118        }
4119    }
4120
4121    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4122        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4123        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4124            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4125                    networkRequest);
4126        }
4127    }
4128
4129    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4130            int notificationType) {
4131        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4132            Intent intent = new Intent();
4133            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4134            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4135            nri.mPendingIntentSent = true;
4136            sendIntent(nri.mPendingIntent, intent);
4137        }
4138        // else not handled
4139    }
4140
4141    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4142        mPendingIntentWakeLock.acquire();
4143        try {
4144            if (DBG) log("Sending " + pendingIntent);
4145            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4146        } catch (PendingIntent.CanceledException e) {
4147            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4148            mPendingIntentWakeLock.release();
4149            releasePendingNetworkRequest(pendingIntent);
4150        }
4151        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4152    }
4153
4154    @Override
4155    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4156            String resultData, Bundle resultExtras) {
4157        if (DBG) log("Finished sending " + pendingIntent);
4158        mPendingIntentWakeLock.release();
4159        // Release with a delay so the receiving client has an opportunity to put in its
4160        // own request.
4161        releasePendingNetworkRequestWithDelay(pendingIntent);
4162    }
4163
4164    private void callCallbackForRequest(NetworkRequestInfo nri,
4165            NetworkAgentInfo networkAgent, int notificationType) {
4166        if (nri.messenger == null) return;  // Default request has no msgr
4167        Bundle bundle = new Bundle();
4168        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4169                new NetworkRequest(nri.request));
4170        Message msg = Message.obtain();
4171        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4172                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4173            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4174        }
4175        switch (notificationType) {
4176            case ConnectivityManager.CALLBACK_LOSING: {
4177                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4178                break;
4179            }
4180            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4181                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4182                        new NetworkCapabilities(networkAgent.networkCapabilities));
4183                break;
4184            }
4185            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4186                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4187                        new LinkProperties(networkAgent.linkProperties));
4188                break;
4189            }
4190        }
4191        msg.what = notificationType;
4192        msg.setData(bundle);
4193        try {
4194            if (VDBG) {
4195                log("sending notification " + notifyTypeToName(notificationType) +
4196                        " for " + nri.request);
4197            }
4198            nri.messenger.send(msg);
4199        } catch (RemoteException e) {
4200            // may occur naturally in the race of binder death.
4201            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4202        }
4203    }
4204
4205    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4206        for (int i = 0; i < nai.networkRequests.size(); i++) {
4207            NetworkRequest nr = nai.networkRequests.valueAt(i);
4208            // Ignore listening requests.
4209            if (!isRequest(nr)) continue;
4210            loge("Dead network still had at least " + nr);
4211            break;
4212        }
4213        nai.asyncChannel.disconnect();
4214    }
4215
4216    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4217        if (oldNetwork == null) {
4218            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4219            return;
4220        }
4221        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4222        teardownUnneededNetwork(oldNetwork);
4223    }
4224
4225    private void makeDefault(NetworkAgentInfo newNetwork) {
4226        if (DBG) log("Switching to new default network: " + newNetwork);
4227        setupDataActivityTracking(newNetwork);
4228        try {
4229            mNetd.setDefaultNetId(newNetwork.network.netId);
4230        } catch (Exception e) {
4231            loge("Exception setting default network :" + e);
4232        }
4233        notifyLockdownVpn(newNetwork);
4234        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4235        updateTcpBufferSizes(newNetwork);
4236        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4237    }
4238
4239    // Handles a network appearing or improving its score.
4240    //
4241    // - Evaluates all current NetworkRequests that can be
4242    //   satisfied by newNetwork, and reassigns to newNetwork
4243    //   any such requests for which newNetwork is the best.
4244    //
4245    // - Lingers any validated Networks that as a result are no longer
4246    //   needed. A network is needed if it is the best network for
4247    //   one or more NetworkRequests, or if it is a VPN.
4248    //
4249    // - Tears down newNetwork if it just became validated
4250    //   (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4251    //
4252    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4253    //   networks that have no chance (i.e. even if validated)
4254    //   of becoming the highest scoring network.
4255    //
4256    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4257    // it does not remove NetworkRequests that other Networks could better satisfy.
4258    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4259    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4260    // as it performs better by a factor of the number of Networks.
4261    //
4262    // @param newNetwork is the network to be matched against NetworkRequests.
4263    // @param nascent indicates if newNetwork just became validated, in which case it should be
4264    //               torn down if unneeded.
4265    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4266    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4267    //               validated) of becoming the highest scoring network.
4268    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4269            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4270        if (!newNetwork.created) return;
4271        if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
4272            loge("ERROR: nascent network not validated.");
4273        }
4274        boolean keep = newNetwork.isVPN();
4275        boolean isNewDefault = false;
4276        NetworkAgentInfo oldDefaultNetwork = null;
4277        if (DBG) log("rematching " + newNetwork.name());
4278        // Find and migrate to this Network any NetworkRequests for
4279        // which this network is now the best.
4280        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4281        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4282        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4283        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4284            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4285            if (newNetwork == currentNetwork) {
4286                if (DBG) {
4287                    log("Network " + newNetwork.name() + " was already satisfying" +
4288                            " request " + nri.request.requestId + ". No change.");
4289                }
4290                keep = true;
4291                continue;
4292            }
4293
4294            // check if it satisfies the NetworkCapabilities
4295            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4296            if (newNetwork.satisfies(nri.request)) {
4297                if (!nri.isRequest) {
4298                    // This is not a request, it's a callback listener.
4299                    // Add it to newNetwork regardless of score.
4300                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4301                    continue;
4302                }
4303
4304                // next check if it's better than any current network we're using for
4305                // this request
4306                if (VDBG) {
4307                    log("currentScore = " +
4308                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4309                            ", newScore = " + newNetwork.getCurrentScore());
4310                }
4311                if (currentNetwork == null ||
4312                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4313                    if (currentNetwork != null) {
4314                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4315                        currentNetwork.networkRequests.remove(nri.request.requestId);
4316                        currentNetwork.networkLingered.add(nri.request);
4317                        affectedNetworks.add(currentNetwork);
4318                    } else {
4319                        if (DBG) log("   accepting network in place of null");
4320                    }
4321                    unlinger(newNetwork);
4322                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4323                    if (!newNetwork.addRequest(nri.request)) {
4324                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4325                    }
4326                    addedRequests.add(nri);
4327                    keep = true;
4328                    // Tell NetworkFactories about the new score, so they can stop
4329                    // trying to connect if they know they cannot match it.
4330                    // TODO - this could get expensive if we have alot of requests for this
4331                    // network.  Think about if there is a way to reduce this.  Push
4332                    // netid->request mapping to each factory?
4333                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4334                    if (mDefaultRequest.requestId == nri.request.requestId) {
4335                        isNewDefault = true;
4336                        oldDefaultNetwork = currentNetwork;
4337                    }
4338                }
4339            }
4340        }
4341        // Linger any networks that are no longer needed.
4342        for (NetworkAgentInfo nai : affectedNetworks) {
4343            if (nai.everValidated && unneeded(nai)) {
4344                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4345                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4346            } else {
4347                unlinger(nai);
4348            }
4349        }
4350        if (keep) {
4351            if (isNewDefault) {
4352                // Notify system services that this network is up.
4353                makeDefault(newNetwork);
4354                synchronized (ConnectivityService.this) {
4355                    // have a new default network, release the transition wakelock in
4356                    // a second if it's held.  The second pause is to allow apps
4357                    // to reconnect over the new network
4358                    if (mNetTransitionWakeLock.isHeld()) {
4359                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4360                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4361                                mNetTransitionWakeLockSerialNumber, 0),
4362                                1000);
4363                    }
4364                }
4365            }
4366
4367            // do this after the default net is switched, but
4368            // before LegacyTypeTracker sends legacy broadcasts
4369            for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4370
4371            if (isNewDefault) {
4372                // Maintain the illusion: since the legacy API only
4373                // understands one network at a time, we must pretend
4374                // that the current default network disconnected before
4375                // the new one connected.
4376                if (oldDefaultNetwork != null) {
4377                    mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4378                                              oldDefaultNetwork, true);
4379                }
4380                mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
4381                mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4382                notifyLockdownVpn(newNetwork);
4383            }
4384
4385            // Notify battery stats service about this network, both the normal
4386            // interface and any stacked links.
4387            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4388            try {
4389                final IBatteryStats bs = BatteryStatsService.getService();
4390                final int type = newNetwork.networkInfo.getType();
4391
4392                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4393                bs.noteNetworkInterfaceType(baseIface, type);
4394                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4395                    final String stackedIface = stacked.getInterfaceName();
4396                    bs.noteNetworkInterfaceType(stackedIface, type);
4397                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4398                }
4399            } catch (RemoteException ignored) {
4400            }
4401
4402            // This has to happen after the notifyNetworkCallbacks as that tickles each
4403            // ConnectivityManager instance so that legacy requests correctly bind dns
4404            // requests to this network.  The legacy users are listening for this bcast
4405            // and will generally do a dns request so they can ensureRouteToHost and if
4406            // they do that before the callbacks happen they'll use the default network.
4407            //
4408            // TODO: Is there still a race here? We send the broadcast
4409            // after sending the callback, but if the app can receive the
4410            // broadcast before the callback, it might still break.
4411            //
4412            // This *does* introduce a race where if the user uses the new api
4413            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4414            // they may get old info.  Reverse this after the old startUsing api is removed.
4415            // This is on top of the multiple intent sequencing referenced in the todo above.
4416            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4417                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4418                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4419                    // legacy type tracker filters out repeat adds
4420                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4421                }
4422            }
4423
4424            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4425            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4426            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4427            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4428            if (newNetwork.isVPN()) {
4429                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4430            }
4431        } else if (nascent == NascentState.JUST_VALIDATED) {
4432            // Only tear down newly validated networks here.  Leave unvalidated to either become
4433            // validated (and get evaluated against peers, one losing here), or get reaped (see
4434            // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4435            // network.  Networks that have been up for a while and are validated should be torn
4436            // down via the lingering process so communication on that network is given time to
4437            // wrap up.
4438            if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
4439            teardownUnneededNetwork(newNetwork);
4440        }
4441        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4442            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4443                if (!nai.everValidated && unneeded(nai)) {
4444                    if (DBG) log("Reaping " + nai.name());
4445                    teardownUnneededNetwork(nai);
4446                }
4447            }
4448        }
4449    }
4450
4451    /**
4452     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4453     * being disconnected.
4454     * @param changed If only one Network's score or capabilities have been modified since the last
4455     *         time this function was called, pass this Network in this argument, otherwise pass
4456     *         null.
4457     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4458     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4459     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4460     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4461     *         network's score.
4462     * @param nascent indicates if {@code changed} has just been validated.
4463     */
4464    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore,
4465            NascentState nascent) {
4466        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4467        // to avoid the slowness.  It is not simply enough to process just "changed", for
4468        // example in the case where "changed"'s score decreases and another network should begin
4469        // satifying a NetworkRequest that "changed" currently satisfies.
4470
4471        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4472        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4473        // rematchNetworkAndRequests() handles.
4474        if (changed != null &&
4475                (oldScore < changed.getCurrentScore() || nascent == NascentState.JUST_VALIDATED)) {
4476            rematchNetworkAndRequests(changed, nascent, ReapUnvalidatedNetworks.REAP);
4477        } else {
4478            for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4479                rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4480                        NascentState.NOT_JUST_VALIDATED,
4481                        // Only reap the last time through the loop.  Reaping before all rematching
4482                        // is complete could incorrectly teardown a network that hasn't yet been
4483                        // rematched.
4484                        i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4485                                : ReapUnvalidatedNetworks.REAP);
4486            }
4487        }
4488    }
4489
4490    private void updateInetCondition(NetworkAgentInfo nai) {
4491        // Don't bother updating until we've graduated to validated at least once.
4492        if (!nai.everValidated) return;
4493        // For now only update icons for default connection.
4494        // TODO: Update WiFi and cellular icons separately. b/17237507
4495        if (!isDefaultNetwork(nai)) return;
4496
4497        int newInetCondition = nai.lastValidated ? 100 : 0;
4498        // Don't repeat publish.
4499        if (newInetCondition == mDefaultInetConditionPublished) return;
4500
4501        mDefaultInetConditionPublished = newInetCondition;
4502        sendInetConditionBroadcast(nai.networkInfo);
4503    }
4504
4505    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4506        if (mLockdownTracker != null) {
4507            if (nai != null && nai.isVPN()) {
4508                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4509            } else {
4510                mLockdownTracker.onNetworkInfoChanged();
4511            }
4512        }
4513    }
4514
4515    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4516        NetworkInfo.State state = newInfo.getState();
4517        NetworkInfo oldInfo = null;
4518        synchronized (networkAgent) {
4519            oldInfo = networkAgent.networkInfo;
4520            networkAgent.networkInfo = newInfo;
4521        }
4522        notifyLockdownVpn(networkAgent);
4523
4524        if (oldInfo != null && oldInfo.getState() == state) {
4525            if (VDBG) log("ignoring duplicate network state non-change");
4526            return;
4527        }
4528        if (DBG) {
4529            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4530                    (oldInfo == null ? "null" : oldInfo.getState()) +
4531                    " to " + state);
4532        }
4533
4534        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4535            try {
4536                // This should never fail.  Specifying an already in use NetID will cause failure.
4537                if (networkAgent.isVPN()) {
4538                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4539                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4540                            (networkAgent.networkMisc == null ||
4541                                !networkAgent.networkMisc.allowBypass));
4542                } else {
4543                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4544                }
4545            } catch (Exception e) {
4546                loge("Error creating network " + networkAgent.network.netId + ": "
4547                        + e.getMessage());
4548                return;
4549            }
4550            networkAgent.created = true;
4551            updateLinkProperties(networkAgent, null);
4552            notifyIfacesChanged();
4553
4554            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4555            scheduleUnvalidatedPrompt(networkAgent);
4556
4557            if (networkAgent.isVPN()) {
4558                // Temporarily disable the default proxy (not global).
4559                synchronized (mProxyLock) {
4560                    if (!mDefaultProxyDisabled) {
4561                        mDefaultProxyDisabled = true;
4562                        if (mGlobalProxy == null && mDefaultProxy != null) {
4563                            sendProxyBroadcast(null);
4564                        }
4565                    }
4566                }
4567                // TODO: support proxy per network.
4568            }
4569
4570            // Consider network even though it is not yet validated.
4571            rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4572                    ReapUnvalidatedNetworks.REAP);
4573
4574            // This has to happen after matching the requests, because callbacks are just requests.
4575            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4576        } else if (state == NetworkInfo.State.DISCONNECTED ||
4577                state == NetworkInfo.State.SUSPENDED) {
4578            networkAgent.asyncChannel.disconnect();
4579            if (networkAgent.isVPN()) {
4580                synchronized (mProxyLock) {
4581                    if (mDefaultProxyDisabled) {
4582                        mDefaultProxyDisabled = false;
4583                        if (mGlobalProxy == null && mDefaultProxy != null) {
4584                            sendProxyBroadcast(mDefaultProxy);
4585                        }
4586                    }
4587                }
4588            }
4589        }
4590    }
4591
4592    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4593        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4594        if (score < 0) {
4595            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4596                    ").  Bumping score to min of 0");
4597            score = 0;
4598        }
4599
4600        final int oldScore = nai.getCurrentScore();
4601        nai.setCurrentScore(score);
4602
4603        rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
4604
4605        sendUpdatedScoreToFactories(nai);
4606    }
4607
4608    // notify only this one new request of the current state
4609    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4610        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4611        // TODO - read state from monitor to decide what to send.
4612//        if (nai.networkMonitor.isLingering()) {
4613//            notifyType = NetworkCallbacks.LOSING;
4614//        } else if (nai.networkMonitor.isEvaluating()) {
4615//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4616//        }
4617        if (nri.mPendingIntent == null) {
4618            callCallbackForRequest(nri, nai, notifyType);
4619        } else {
4620            sendPendingIntentForRequest(nri, nai, notifyType);
4621        }
4622    }
4623
4624    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4625        // The NetworkInfo we actually send out has no bearing on the real
4626        // state of affairs. For example, if the default connection is mobile,
4627        // and a request for HIPRI has just gone away, we need to pretend that
4628        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4629        // the state to DISCONNECTED, even though the network is of type MOBILE
4630        // and is still connected.
4631        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4632        info.setType(type);
4633        if (connected) {
4634            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4635            sendConnectedBroadcast(info);
4636        } else {
4637            info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
4638            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4639            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4640            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4641            if (info.isFailover()) {
4642                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4643                nai.networkInfo.setFailover(false);
4644            }
4645            if (info.getReason() != null) {
4646                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4647            }
4648            if (info.getExtraInfo() != null) {
4649                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4650            }
4651            NetworkAgentInfo newDefaultAgent = null;
4652            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4653                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4654                if (newDefaultAgent != null) {
4655                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4656                            newDefaultAgent.networkInfo);
4657                } else {
4658                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4659                }
4660            }
4661            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4662                    mDefaultInetConditionPublished);
4663            sendStickyBroadcast(intent);
4664            if (newDefaultAgent != null) {
4665                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4666            }
4667        }
4668    }
4669
4670    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4671        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4672        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4673            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4674            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4675            if (VDBG) log(" sending notification for " + nr);
4676            if (nri.mPendingIntent == null) {
4677                callCallbackForRequest(nri, networkAgent, notifyType);
4678            } else {
4679                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4680            }
4681        }
4682    }
4683
4684    private String notifyTypeToName(int notifyType) {
4685        switch (notifyType) {
4686            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4687            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4688            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4689            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4690            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4691            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4692            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4693            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4694        }
4695        return "UNKNOWN";
4696    }
4697
4698    /**
4699     * Notify other system services that set of active ifaces has changed.
4700     */
4701    private void notifyIfacesChanged() {
4702        try {
4703            mStatsService.forceUpdateIfaces();
4704        } catch (Exception ignored) {
4705        }
4706    }
4707
4708    @Override
4709    public boolean addVpnAddress(String address, int prefixLength) {
4710        throwIfLockdownEnabled();
4711        int user = UserHandle.getUserId(Binder.getCallingUid());
4712        synchronized (mVpns) {
4713            return mVpns.get(user).addAddress(address, prefixLength);
4714        }
4715    }
4716
4717    @Override
4718    public boolean removeVpnAddress(String address, int prefixLength) {
4719        throwIfLockdownEnabled();
4720        int user = UserHandle.getUserId(Binder.getCallingUid());
4721        synchronized (mVpns) {
4722            return mVpns.get(user).removeAddress(address, prefixLength);
4723        }
4724    }
4725
4726    @Override
4727    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4728        throwIfLockdownEnabled();
4729        int user = UserHandle.getUserId(Binder.getCallingUid());
4730        boolean success;
4731        synchronized (mVpns) {
4732            success = mVpns.get(user).setUnderlyingNetworks(networks);
4733        }
4734        if (success) {
4735            notifyIfacesChanged();
4736        }
4737        return success;
4738    }
4739
4740    @Override
4741    public void factoryReset() {
4742        enforceConnectivityInternalPermission();
4743
4744        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4745            return;
4746        }
4747
4748        final int userId = UserHandle.getCallingUserId();
4749
4750        // Turn airplane mode off
4751        setAirplaneMode(false);
4752
4753        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4754            // Untether
4755            for (String tether : getTetheredIfaces()) {
4756                untether(tether);
4757            }
4758        }
4759
4760        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4761            // Turn VPN off
4762            VpnConfig vpnConfig = getVpnConfig(userId);
4763            if (vpnConfig != null) {
4764                if (vpnConfig.legacy) {
4765                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4766                } else {
4767                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4768                    // in the future without user intervention.
4769                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
4770
4771                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4772                }
4773            }
4774        }
4775    }
4776}
4777