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