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