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