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