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