ConnectivityService.java revision 8e21d29f7e8691c5798ef613c2ccc4112c649421
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                    if (!network.addRequest(nri.request)) {
2189                        Slog.wtf(TAG, "BUG: " + network.name() + " already has " + nri.request);
2190                    }
2191                    notifyNetworkCallback(network, nri);
2192                } else if (bestNetwork == null ||
2193                        bestNetwork.getCurrentScore() < network.getCurrentScore()) {
2194                    bestNetwork = network;
2195                }
2196            }
2197        }
2198        if (bestNetwork != null) {
2199            if (DBG) log("using " + bestNetwork.name());
2200            unlinger(bestNetwork);
2201            if (!bestNetwork.addRequest(nri.request)) {
2202                Slog.wtf(TAG, "BUG: " + bestNetwork.name() + " already has " + nri.request);
2203            }
2204            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
2205            notifyNetworkCallback(bestNetwork, nri);
2206            if (nri.request.legacyType != TYPE_NONE) {
2207                mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2208            }
2209        }
2210
2211        if (nri.isRequest) {
2212            if (DBG) log("sending new NetworkRequest to factories");
2213            final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
2214            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2215                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
2216                        0, nri.request);
2217            }
2218        }
2219    }
2220
2221    private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2222            int callingUid) {
2223        NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2224        if (nri != null) {
2225            handleReleaseNetworkRequest(nri.request, callingUid);
2226        }
2227    }
2228
2229    // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2230    // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2231    // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2232    // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2233    private boolean unneeded(NetworkAgentInfo nai) {
2234        if (!nai.created || nai.isVPN()) return false;
2235        boolean unneeded = true;
2236        if (nai.everValidated) {
2237            for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2238                final NetworkRequest nr = nai.networkRequests.valueAt(i);
2239                try {
2240                    if (isRequest(nr)) unneeded = false;
2241                } catch (Exception e) {
2242                    loge("Request " + nr + " not found in mNetworkRequests.");
2243                    loge("  it came from request list  of " + nai.name());
2244                }
2245            }
2246        } else {
2247            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2248                // If this Network is already the highest scoring Network for a request, or if
2249                // there is hope for it to become one if it validated, then it is needed.
2250                if (nri.isRequest && nai.satisfies(nri.request) &&
2251                        (nai.networkRequests.get(nri.request.requestId) != null ||
2252                        // Note that this catches two important cases:
2253                        // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2254                        //    is currently satisfying the request.  This is desirable when
2255                        //    cellular ends up validating but WiFi does not.
2256                        // 2. Unvalidated WiFi will not be reaped when validated cellular
2257                        //    is currently satsifying the request.  This is desirable when
2258                        //    WiFi ends up validating and out scoring cellular.
2259                        mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2260                                nai.getCurrentScoreAsValidated())) {
2261                    unneeded = false;
2262                    break;
2263                }
2264            }
2265        }
2266        return unneeded;
2267    }
2268
2269    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2270        NetworkRequestInfo nri = mNetworkRequests.get(request);
2271        if (nri != null) {
2272            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2273                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2274                return;
2275            }
2276            if (DBG) log("releasing NetworkRequest " + request);
2277            nri.unlinkDeathRecipient();
2278            mNetworkRequests.remove(request);
2279            if (nri.isRequest) {
2280                // Find all networks that are satisfying this request and remove the request
2281                // from their request lists.
2282                // TODO - it's my understanding that for a request there is only a single
2283                // network satisfying it, so this loop is wasteful
2284                boolean wasKept = false;
2285                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2286                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2287                        nai.networkRequests.remove(nri.request.requestId);
2288                        if (DBG) {
2289                            log(" Removing from current network " + nai.name() +
2290                                    ", leaving " + nai.networkRequests.size() +
2291                                    " requests.");
2292                        }
2293                        if (unneeded(nai)) {
2294                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2295                            teardownUnneededNetwork(nai);
2296                        } else {
2297                            // suspect there should only be one pass through here
2298                            // but if any were kept do the check below
2299                            wasKept |= true;
2300                        }
2301                    }
2302                }
2303
2304                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2305                if (nai != null) {
2306                    mNetworkForRequestId.remove(nri.request.requestId);
2307                }
2308                // Maintain the illusion.  When this request arrived, we might have pretended
2309                // that a network connected to serve it, even though the network was already
2310                // connected.  Now that this request has gone away, we might have to pretend
2311                // that the network disconnected.  LegacyTypeTracker will generate that
2312                // phantom disconnect for this type.
2313                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2314                    boolean doRemove = true;
2315                    if (wasKept) {
2316                        // check if any of the remaining requests for this network are for the
2317                        // same legacy type - if so, don't remove the nai
2318                        for (int i = 0; i < nai.networkRequests.size(); i++) {
2319                            NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2320                            if (otherRequest.legacyType == nri.request.legacyType &&
2321                                    isRequest(otherRequest)) {
2322                                if (DBG) log(" still have other legacy request - leaving");
2323                                doRemove = false;
2324                            }
2325                        }
2326                    }
2327
2328                    if (doRemove) {
2329                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2330                    }
2331                }
2332
2333                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2334                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2335                            nri.request);
2336                }
2337            } else {
2338                // listens don't have a singular affectedNetwork.  Check all networks to see
2339                // if this listen request applies and remove it.
2340                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2341                    nai.networkRequests.remove(nri.request.requestId);
2342                }
2343            }
2344            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2345        }
2346    }
2347
2348    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2349        enforceConnectivityInternalPermission();
2350        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2351                accept ? 1 : 0, always ? 1: 0, network));
2352    }
2353
2354    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2355        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2356                " accept=" + accept + " always=" + always);
2357
2358        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2359        if (nai == null) {
2360            // Nothing to do.
2361            return;
2362        }
2363
2364        if (nai.everValidated) {
2365            // The network validated while the dialog box was up. Take no action.
2366            return;
2367        }
2368
2369        if (!nai.networkMisc.explicitlySelected) {
2370            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2371        }
2372
2373        if (accept != nai.networkMisc.acceptUnvalidated) {
2374            int oldScore = nai.getCurrentScore();
2375            nai.networkMisc.acceptUnvalidated = accept;
2376            rematchAllNetworksAndRequests(nai, oldScore);
2377            sendUpdatedScoreToFactories(nai);
2378        }
2379
2380        if (always) {
2381            nai.asyncChannel.sendMessage(
2382                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2383        }
2384
2385        if (!accept) {
2386            // Tell the NetworkAgent that the network does not have Internet access (because that's
2387            // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2388            // the future. We do this now because NetworkMonitor might not yet have finished
2389            // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2390            nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2391                    NetworkAgent.INVALID_NETWORK, 0, null);
2392            // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2393            // to reconnect to it immediately. http://b/20739299
2394        }
2395
2396    }
2397
2398    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2399        if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
2400        mHandler.sendMessageDelayed(
2401                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2402                PROMPT_UNVALIDATED_DELAY_MS);
2403    }
2404
2405    private void handlePromptUnvalidated(Network network) {
2406        if (DBG) log("handlePromptUnvalidated " + network);
2407        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2408
2409        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2410        // we haven't already been told to switch to it regardless of whether it validated or not.
2411        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2412        if (nai == null || nai.everValidated || nai.captivePortalDetected ||
2413                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2414            return;
2415        }
2416
2417        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2418        intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
2419        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2420        intent.setClassName("com.android.settings",
2421                "com.android.settings.wifi.WifiNoInternetDialog");
2422
2423        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2424                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2425        setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2426                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent);
2427    }
2428
2429    private class InternalHandler extends Handler {
2430        public InternalHandler(Looper looper) {
2431            super(looper);
2432        }
2433
2434        @Override
2435        public void handleMessage(Message msg) {
2436            switch (msg.what) {
2437                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2438                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2439                    String causedBy = null;
2440                    synchronized (ConnectivityService.this) {
2441                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2442                                mNetTransitionWakeLock.isHeld()) {
2443                            mNetTransitionWakeLock.release();
2444                            causedBy = mNetTransitionWakeLockCausedBy;
2445                        } else {
2446                            break;
2447                        }
2448                    }
2449                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2450                        log("Failed to find a new network - expiring NetTransition Wakelock");
2451                    } else {
2452                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2453                                " cleared because we found a replacement network");
2454                    }
2455                    break;
2456                }
2457                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2458                    handleDeprecatedGlobalHttpProxy();
2459                    break;
2460                }
2461                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
2462                    Intent intent = (Intent)msg.obj;
2463                    sendStickyBroadcast(intent);
2464                    break;
2465                }
2466                case EVENT_PROXY_HAS_CHANGED: {
2467                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2468                    break;
2469                }
2470                case EVENT_REGISTER_NETWORK_FACTORY: {
2471                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2472                    break;
2473                }
2474                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2475                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2476                    break;
2477                }
2478                case EVENT_REGISTER_NETWORK_AGENT: {
2479                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2480                    break;
2481                }
2482                case EVENT_REGISTER_NETWORK_REQUEST:
2483                case EVENT_REGISTER_NETWORK_LISTENER: {
2484                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2485                    break;
2486                }
2487                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2488                    handleRegisterNetworkRequestWithIntent(msg);
2489                    break;
2490                }
2491                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2492                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2493                    break;
2494                }
2495                case EVENT_RELEASE_NETWORK_REQUEST: {
2496                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2497                    break;
2498                }
2499                case EVENT_SET_ACCEPT_UNVALIDATED: {
2500                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2501                    break;
2502                }
2503                case EVENT_PROMPT_UNVALIDATED: {
2504                    handlePromptUnvalidated((Network) msg.obj);
2505                    break;
2506                }
2507                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2508                    handleMobileDataAlwaysOn();
2509                    break;
2510                }
2511                case EVENT_SYSTEM_READY: {
2512                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2513                        nai.networkMonitor.systemReady = true;
2514                    }
2515                    break;
2516                }
2517            }
2518        }
2519    }
2520
2521    // javadoc from interface
2522    public int tether(String iface) {
2523        ConnectivityManager.enforceTetherChangePermission(mContext);
2524        if (isTetheringSupported()) {
2525            return mTethering.tether(iface);
2526        } else {
2527            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2528        }
2529    }
2530
2531    // javadoc from interface
2532    public int untether(String iface) {
2533        ConnectivityManager.enforceTetherChangePermission(mContext);
2534
2535        if (isTetheringSupported()) {
2536            return mTethering.untether(iface);
2537        } else {
2538            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2539        }
2540    }
2541
2542    // javadoc from interface
2543    public int getLastTetherError(String iface) {
2544        enforceTetherAccessPermission();
2545
2546        if (isTetheringSupported()) {
2547            return mTethering.getLastTetherError(iface);
2548        } else {
2549            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2550        }
2551    }
2552
2553    // TODO - proper iface API for selection by property, inspection, etc
2554    public String[] getTetherableUsbRegexs() {
2555        enforceTetherAccessPermission();
2556        if (isTetheringSupported()) {
2557            return mTethering.getTetherableUsbRegexs();
2558        } else {
2559            return new String[0];
2560        }
2561    }
2562
2563    public String[] getTetherableWifiRegexs() {
2564        enforceTetherAccessPermission();
2565        if (isTetheringSupported()) {
2566            return mTethering.getTetherableWifiRegexs();
2567        } else {
2568            return new String[0];
2569        }
2570    }
2571
2572    public String[] getTetherableBluetoothRegexs() {
2573        enforceTetherAccessPermission();
2574        if (isTetheringSupported()) {
2575            return mTethering.getTetherableBluetoothRegexs();
2576        } else {
2577            return new String[0];
2578        }
2579    }
2580
2581    public int setUsbTethering(boolean enable) {
2582        ConnectivityManager.enforceTetherChangePermission(mContext);
2583        if (isTetheringSupported()) {
2584            return mTethering.setUsbTethering(enable);
2585        } else {
2586            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2587        }
2588    }
2589
2590    // TODO - move iface listing, queries, etc to new module
2591    // javadoc from interface
2592    public String[] getTetherableIfaces() {
2593        enforceTetherAccessPermission();
2594        return mTethering.getTetherableIfaces();
2595    }
2596
2597    public String[] getTetheredIfaces() {
2598        enforceTetherAccessPermission();
2599        return mTethering.getTetheredIfaces();
2600    }
2601
2602    public String[] getTetheringErroredIfaces() {
2603        enforceTetherAccessPermission();
2604        return mTethering.getErroredIfaces();
2605    }
2606
2607    public String[] getTetheredDhcpRanges() {
2608        enforceConnectivityInternalPermission();
2609        return mTethering.getTetheredDhcpRanges();
2610    }
2611
2612    // if ro.tether.denied = true we default to no tethering
2613    // gservices could set the secure setting to 1 though to enable it on a build where it
2614    // had previously been turned off.
2615    public boolean isTetheringSupported() {
2616        enforceTetherAccessPermission();
2617        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2618        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2619                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2620                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2621        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2622                mTethering.getTetherableWifiRegexs().length != 0 ||
2623                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2624                mTethering.getUpstreamIfaceTypes().length != 0);
2625    }
2626
2627    // Called when we lose the default network and have no replacement yet.
2628    // This will automatically be cleared after X seconds or a new default network
2629    // becomes CONNECTED, whichever happens first.  The timer is started by the
2630    // first caller and not restarted by subsequent callers.
2631    private void requestNetworkTransitionWakelock(String forWhom) {
2632        int serialNum = 0;
2633        synchronized (this) {
2634            if (mNetTransitionWakeLock.isHeld()) return;
2635            serialNum = ++mNetTransitionWakeLockSerialNumber;
2636            mNetTransitionWakeLock.acquire();
2637            mNetTransitionWakeLockCausedBy = forWhom;
2638        }
2639        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2640                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2641                mNetTransitionWakeLockTimeout);
2642        return;
2643    }
2644
2645    // 100 percent is full good, 0 is full bad.
2646    public void reportInetCondition(int networkType, int percentage) {
2647        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2648        if (nai == null) return;
2649        reportNetworkConnectivity(nai.network, percentage > 50);
2650    }
2651
2652    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2653        enforceAccessPermission();
2654        enforceInternetPermission();
2655
2656        NetworkAgentInfo nai;
2657        if (network == null) {
2658            nai = getDefaultNetwork();
2659        } else {
2660            nai = getNetworkAgentInfoForNetwork(network);
2661        }
2662        if (nai == null) return;
2663        // Revalidate if the app report does not match our current validated state.
2664        if (hasConnectivity == nai.lastValidated) return;
2665        final int uid = Binder.getCallingUid();
2666        if (DBG) {
2667            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2668                    ") by " + uid);
2669        }
2670        synchronized (nai) {
2671            // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2672            // which isn't meant to work on uncreated networks.
2673            if (!nai.created) return;
2674
2675            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
2676
2677            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2678        }
2679    }
2680
2681    public void captivePortalAppResponse(Network network, int response, String actionToken) {
2682        if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2683            enforceConnectivityInternalPermission();
2684        }
2685        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2686        if (nai == null) return;
2687        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2688                actionToken);
2689    }
2690
2691    private ProxyInfo getDefaultProxy() {
2692        // this information is already available as a world read/writable jvm property
2693        // so this API change wouldn't have a benifit.  It also breaks the passing
2694        // of proxy info to all the JVMs.
2695        // enforceAccessPermission();
2696        synchronized (mProxyLock) {
2697            ProxyInfo ret = mGlobalProxy;
2698            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2699            return ret;
2700        }
2701    }
2702
2703    public ProxyInfo getProxyForNetwork(Network network) {
2704        if (network == null) return getDefaultProxy();
2705        final ProxyInfo globalProxy = getGlobalProxy();
2706        if (globalProxy != null) return globalProxy;
2707        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2708        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2709        // caller may not have.
2710        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2711        if (nai == null) return null;
2712        synchronized (nai) {
2713            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2714            if (proxyInfo == null) return null;
2715            return new ProxyInfo(proxyInfo);
2716        }
2717    }
2718
2719    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2720    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2721    // proxy is null then there is no proxy in place).
2722    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2723        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2724                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2725            proxy = null;
2726        }
2727        return proxy;
2728    }
2729
2730    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2731    // better for determining if a new proxy broadcast is necessary:
2732    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2733    //    avoid unnecessary broadcasts.
2734    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2735    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2736    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2737    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2738    //    all set.
2739    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2740        a = canonicalizeProxyInfo(a);
2741        b = canonicalizeProxyInfo(b);
2742        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2743        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2744        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2745    }
2746
2747    public void setGlobalProxy(ProxyInfo proxyProperties) {
2748        enforceConnectivityInternalPermission();
2749
2750        synchronized (mProxyLock) {
2751            if (proxyProperties == mGlobalProxy) return;
2752            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2753            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2754
2755            String host = "";
2756            int port = 0;
2757            String exclList = "";
2758            String pacFileUrl = "";
2759            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2760                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2761                if (!proxyProperties.isValid()) {
2762                    if (DBG)
2763                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2764                    return;
2765                }
2766                mGlobalProxy = new ProxyInfo(proxyProperties);
2767                host = mGlobalProxy.getHost();
2768                port = mGlobalProxy.getPort();
2769                exclList = mGlobalProxy.getExclusionListAsString();
2770                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2771                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2772                }
2773            } else {
2774                mGlobalProxy = null;
2775            }
2776            ContentResolver res = mContext.getContentResolver();
2777            final long token = Binder.clearCallingIdentity();
2778            try {
2779                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2780                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2781                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2782                        exclList);
2783                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2784            } finally {
2785                Binder.restoreCallingIdentity(token);
2786            }
2787
2788            if (mGlobalProxy == null) {
2789                proxyProperties = mDefaultProxy;
2790            }
2791            sendProxyBroadcast(proxyProperties);
2792        }
2793    }
2794
2795    private void loadGlobalProxy() {
2796        ContentResolver res = mContext.getContentResolver();
2797        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2798        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2799        String exclList = Settings.Global.getString(res,
2800                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2801        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2802        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2803            ProxyInfo proxyProperties;
2804            if (!TextUtils.isEmpty(pacFileUrl)) {
2805                proxyProperties = new ProxyInfo(pacFileUrl);
2806            } else {
2807                proxyProperties = new ProxyInfo(host, port, exclList);
2808            }
2809            if (!proxyProperties.isValid()) {
2810                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2811                return;
2812            }
2813
2814            synchronized (mProxyLock) {
2815                mGlobalProxy = proxyProperties;
2816            }
2817        }
2818    }
2819
2820    public ProxyInfo getGlobalProxy() {
2821        // this information is already available as a world read/writable jvm property
2822        // so this API change wouldn't have a benifit.  It also breaks the passing
2823        // of proxy info to all the JVMs.
2824        // enforceAccessPermission();
2825        synchronized (mProxyLock) {
2826            return mGlobalProxy;
2827        }
2828    }
2829
2830    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2831        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2832                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2833            proxy = null;
2834        }
2835        synchronized (mProxyLock) {
2836            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2837            if (mDefaultProxy == proxy) return; // catches repeated nulls
2838            if (proxy != null &&  !proxy.isValid()) {
2839                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2840                return;
2841            }
2842
2843            // This call could be coming from the PacManager, containing the port of the local
2844            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2845            // global (to get the correct local port), and send a broadcast.
2846            // TODO: Switch PacManager to have its own message to send back rather than
2847            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2848            if ((mGlobalProxy != null) && (proxy != null)
2849                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2850                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2851                mGlobalProxy = proxy;
2852                sendProxyBroadcast(mGlobalProxy);
2853                return;
2854            }
2855            mDefaultProxy = proxy;
2856
2857            if (mGlobalProxy != null) return;
2858            if (!mDefaultProxyDisabled) {
2859                sendProxyBroadcast(proxy);
2860            }
2861        }
2862    }
2863
2864    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2865    // This method gets called when any network changes proxy, but the broadcast only ever contains
2866    // the default proxy (even if it hasn't changed).
2867    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2868    // world where an app might be bound to a non-default network.
2869    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2870        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2871        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2872
2873        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2874            sendProxyBroadcast(getDefaultProxy());
2875        }
2876    }
2877
2878    private void handleDeprecatedGlobalHttpProxy() {
2879        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2880                Settings.Global.HTTP_PROXY);
2881        if (!TextUtils.isEmpty(proxy)) {
2882            String data[] = proxy.split(":");
2883            if (data.length == 0) {
2884                return;
2885            }
2886
2887            String proxyHost =  data[0];
2888            int proxyPort = 8080;
2889            if (data.length > 1) {
2890                try {
2891                    proxyPort = Integer.parseInt(data[1]);
2892                } catch (NumberFormatException e) {
2893                    return;
2894                }
2895            }
2896            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2897            setGlobalProxy(p);
2898        }
2899    }
2900
2901    private void sendProxyBroadcast(ProxyInfo proxy) {
2902        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2903        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2904        if (DBG) log("sending Proxy Broadcast for " + proxy);
2905        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2906        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2907            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2908        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2909        final long ident = Binder.clearCallingIdentity();
2910        try {
2911            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2912        } finally {
2913            Binder.restoreCallingIdentity(ident);
2914        }
2915    }
2916
2917    private static class SettingsObserver extends ContentObserver {
2918        final private HashMap<Uri, Integer> mUriEventMap;
2919        final private Context mContext;
2920        final private Handler mHandler;
2921
2922        SettingsObserver(Context context, Handler handler) {
2923            super(null);
2924            mUriEventMap = new HashMap<Uri, Integer>();
2925            mContext = context;
2926            mHandler = handler;
2927        }
2928
2929        void observe(Uri uri, int what) {
2930            mUriEventMap.put(uri, what);
2931            final ContentResolver resolver = mContext.getContentResolver();
2932            resolver.registerContentObserver(uri, false, this);
2933        }
2934
2935        @Override
2936        public void onChange(boolean selfChange) {
2937            Slog.wtf(TAG, "Should never be reached.");
2938        }
2939
2940        @Override
2941        public void onChange(boolean selfChange, Uri uri) {
2942            final Integer what = mUriEventMap.get(uri);
2943            if (what != null) {
2944                mHandler.obtainMessage(what.intValue()).sendToTarget();
2945            } else {
2946                loge("No matching event to send for URI=" + uri);
2947            }
2948        }
2949    }
2950
2951    private static void log(String s) {
2952        Slog.d(TAG, s);
2953    }
2954
2955    private static void loge(String s) {
2956        Slog.e(TAG, s);
2957    }
2958
2959    private static <T> T checkNotNull(T value, String message) {
2960        if (value == null) {
2961            throw new NullPointerException(message);
2962        }
2963        return value;
2964    }
2965
2966    /**
2967     * Prepare for a VPN application.
2968     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2969     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2970     *
2971     * @param oldPackage Package name of the application which currently controls VPN, which will
2972     *                   be replaced. If there is no such application, this should should either be
2973     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
2974     * @param newPackage Package name of the application which should gain control of VPN, or
2975     *                   {@code null} to disable.
2976     * @param userId User for whom to prepare the new VPN.
2977     *
2978     * @hide
2979     */
2980    @Override
2981    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2982            int userId) {
2983        enforceCrossUserPermission(userId);
2984        throwIfLockdownEnabled();
2985
2986        synchronized(mVpns) {
2987            Vpn vpn = mVpns.get(userId);
2988            if (vpn != null) {
2989                return vpn.prepare(oldPackage, newPackage);
2990            } else {
2991                return false;
2992            }
2993        }
2994    }
2995
2996    /**
2997     * Set whether the VPN package has the ability to launch VPNs without user intervention.
2998     * This method is used by system-privileged apps.
2999     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3000     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3001     *
3002     * @param packageName The package for which authorization state should change.
3003     * @param userId User for whom {@code packageName} is installed.
3004     * @param authorized {@code true} if this app should be able to start a VPN connection without
3005     *                   explicit user approval, {@code false} if not.
3006     *
3007     * @hide
3008     */
3009    @Override
3010    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3011        enforceCrossUserPermission(userId);
3012
3013        synchronized(mVpns) {
3014            Vpn vpn = mVpns.get(userId);
3015            if (vpn != null) {
3016                vpn.setPackageAuthorization(packageName, authorized);
3017            }
3018        }
3019    }
3020
3021    /**
3022     * Configure a TUN interface and return its file descriptor. Parameters
3023     * are encoded and opaque to this class. This method is used by VpnBuilder
3024     * and not available in ConnectivityManager. Permissions are checked in
3025     * Vpn class.
3026     * @hide
3027     */
3028    @Override
3029    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3030        throwIfLockdownEnabled();
3031        int user = UserHandle.getUserId(Binder.getCallingUid());
3032        synchronized(mVpns) {
3033            return mVpns.get(user).establish(config);
3034        }
3035    }
3036
3037    /**
3038     * Start legacy VPN, controlling native daemons as needed. Creates a
3039     * secondary thread to perform connection work, returning quickly.
3040     */
3041    @Override
3042    public void startLegacyVpn(VpnProfile profile) {
3043        throwIfLockdownEnabled();
3044        final LinkProperties egress = getActiveLinkProperties();
3045        if (egress == null) {
3046            throw new IllegalStateException("Missing active network connection");
3047        }
3048        int user = UserHandle.getUserId(Binder.getCallingUid());
3049        synchronized(mVpns) {
3050            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3051        }
3052    }
3053
3054    /**
3055     * Return the information of the ongoing legacy VPN. This method is used
3056     * by VpnSettings and not available in ConnectivityManager. Permissions
3057     * are checked in Vpn class.
3058     */
3059    @Override
3060    public LegacyVpnInfo getLegacyVpnInfo() {
3061        throwIfLockdownEnabled();
3062        int user = UserHandle.getUserId(Binder.getCallingUid());
3063        synchronized(mVpns) {
3064            return mVpns.get(user).getLegacyVpnInfo();
3065        }
3066    }
3067
3068    /**
3069     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3070     * and not available in ConnectivityManager.
3071     */
3072    @Override
3073    public VpnInfo[] getAllVpnInfo() {
3074        enforceConnectivityInternalPermission();
3075        if (mLockdownEnabled) {
3076            return new VpnInfo[0];
3077        }
3078
3079        synchronized(mVpns) {
3080            List<VpnInfo> infoList = new ArrayList<>();
3081            for (int i = 0; i < mVpns.size(); i++) {
3082                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3083                if (info != null) {
3084                    infoList.add(info);
3085                }
3086            }
3087            return infoList.toArray(new VpnInfo[infoList.size()]);
3088        }
3089    }
3090
3091    /**
3092     * @return VPN information for accounting, or null if we can't retrieve all required
3093     *         information, e.g primary underlying iface.
3094     */
3095    @Nullable
3096    private VpnInfo createVpnInfo(Vpn vpn) {
3097        VpnInfo info = vpn.getVpnInfo();
3098        if (info == null) {
3099            return null;
3100        }
3101        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3102        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3103        // the underlyingNetworks list.
3104        if (underlyingNetworks == null) {
3105            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3106            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3107                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3108            }
3109        } else if (underlyingNetworks.length > 0) {
3110            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3111            if (linkProperties != null) {
3112                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3113            }
3114        }
3115        return info.primaryUnderlyingIface == null ? null : info;
3116    }
3117
3118    /**
3119     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3120     * VpnDialogs and not available in ConnectivityManager.
3121     * Permissions are checked in Vpn class.
3122     * @hide
3123     */
3124    @Override
3125    public VpnConfig getVpnConfig(int userId) {
3126        enforceCrossUserPermission(userId);
3127        synchronized(mVpns) {
3128            Vpn vpn = mVpns.get(userId);
3129            if (vpn != null) {
3130                return vpn.getVpnConfig();
3131            } else {
3132                return null;
3133            }
3134        }
3135    }
3136
3137    @Override
3138    public boolean updateLockdownVpn() {
3139        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3140            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3141            return false;
3142        }
3143
3144        // Tear down existing lockdown if profile was removed
3145        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3146        if (mLockdownEnabled) {
3147            if (!mKeyStore.isUnlocked()) {
3148                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3149                return false;
3150            }
3151
3152            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3153            final VpnProfile profile = VpnProfile.decode(
3154                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3155            int user = UserHandle.getUserId(Binder.getCallingUid());
3156            synchronized(mVpns) {
3157                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3158                            profile));
3159            }
3160        } else {
3161            setLockdownTracker(null);
3162        }
3163
3164        return true;
3165    }
3166
3167    /**
3168     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3169     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3170     */
3171    private void setLockdownTracker(LockdownVpnTracker tracker) {
3172        // Shutdown any existing tracker
3173        final LockdownVpnTracker existing = mLockdownTracker;
3174        mLockdownTracker = null;
3175        if (existing != null) {
3176            existing.shutdown();
3177        }
3178
3179        try {
3180            if (tracker != null) {
3181                mNetd.setFirewallEnabled(true);
3182                mNetd.setFirewallInterfaceRule("lo", true);
3183                mLockdownTracker = tracker;
3184                mLockdownTracker.init();
3185            } else {
3186                mNetd.setFirewallEnabled(false);
3187            }
3188        } catch (RemoteException e) {
3189            // ignored; NMS lives inside system_server
3190        }
3191    }
3192
3193    private void throwIfLockdownEnabled() {
3194        if (mLockdownEnabled) {
3195            throw new IllegalStateException("Unavailable in lockdown mode");
3196        }
3197    }
3198
3199    @Override
3200    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3201        // TODO: Remove?  Any reason to trigger a provisioning check?
3202        return -1;
3203    }
3204
3205    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3206    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3207
3208    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3209        if (DBG) {
3210            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3211                + " action=" + action);
3212        }
3213        Intent intent = new Intent(action);
3214        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3215        // Concatenate the range of types onto the range of NetIDs.
3216        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3217        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3218                networkType, null, pendingIntent);
3219    }
3220
3221    /**
3222     * Show or hide network provisioning notifications.
3223     *
3224     * We use notifications for two purposes: to notify that a network requires sign in
3225     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3226     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3227     * particular network we can display the notification type that was most recently requested.
3228     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3229     * might first display NO_INTERNET, and then when the captive portal check completes, display
3230     * SIGN_IN.
3231     *
3232     * @param id an identifier that uniquely identifies this notification.  This must match
3233     *         between show and hide calls.  We use the NetID value but for legacy callers
3234     *         we concatenate the range of types with the range of NetIDs.
3235     */
3236    private void setProvNotificationVisibleIntent(boolean visible, int id,
3237            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent) {
3238        if (DBG) {
3239            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3240                    + " networkType=" + getNetworkTypeName(networkType)
3241                    + " extraInfo=" + extraInfo);
3242        }
3243
3244        Resources r = Resources.getSystem();
3245        NotificationManager notificationManager = (NotificationManager) mContext
3246            .getSystemService(Context.NOTIFICATION_SERVICE);
3247
3248        if (visible) {
3249            CharSequence title;
3250            CharSequence details;
3251            int icon;
3252            if (notifyType == NotificationType.NO_INTERNET &&
3253                    networkType == ConnectivityManager.TYPE_WIFI) {
3254                title = r.getString(R.string.wifi_no_internet, 0);
3255                details = r.getString(R.string.wifi_no_internet_detailed);
3256                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3257            } else if (notifyType == NotificationType.SIGN_IN) {
3258                switch (networkType) {
3259                    case ConnectivityManager.TYPE_WIFI:
3260                        title = r.getString(R.string.wifi_available_sign_in, 0);
3261                        details = r.getString(R.string.network_available_sign_in_detailed,
3262                                extraInfo);
3263                        icon = R.drawable.stat_notify_wifi_in_range;
3264                        break;
3265                    case ConnectivityManager.TYPE_MOBILE:
3266                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3267                        title = r.getString(R.string.network_available_sign_in, 0);
3268                        // TODO: Change this to pull from NetworkInfo once a printable
3269                        // name has been added to it
3270                        details = mTelephonyManager.getNetworkOperatorName();
3271                        icon = R.drawable.stat_notify_rssi_in_range;
3272                        break;
3273                    default:
3274                        title = r.getString(R.string.network_available_sign_in, 0);
3275                        details = r.getString(R.string.network_available_sign_in_detailed,
3276                                extraInfo);
3277                        icon = R.drawable.stat_notify_rssi_in_range;
3278                        break;
3279                }
3280            } else {
3281                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3282                        + getNetworkTypeName(networkType));
3283                return;
3284            }
3285
3286            Notification notification = new Notification.Builder(mContext)
3287                    .setWhen(0)
3288                    .setSmallIcon(icon)
3289                    .setAutoCancel(true)
3290                    .setTicker(title)
3291                    .setColor(mContext.getColor(
3292                            com.android.internal.R.color.system_notification_accent_color))
3293                    .setContentTitle(title)
3294                    .setContentText(details)
3295                    .setContentIntent(intent)
3296                    .build();
3297
3298            try {
3299                notificationManager.notify(NOTIFICATION_ID, id, notification);
3300            } catch (NullPointerException npe) {
3301                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3302                npe.printStackTrace();
3303            }
3304        } else {
3305            try {
3306                notificationManager.cancel(NOTIFICATION_ID, id);
3307            } catch (NullPointerException npe) {
3308                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3309                npe.printStackTrace();
3310            }
3311        }
3312    }
3313
3314    /** Location to an updatable file listing carrier provisioning urls.
3315     *  An example:
3316     *
3317     * <?xml version="1.0" encoding="utf-8"?>
3318     *  <provisioningUrls>
3319     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3320     *  </provisioningUrls>
3321     */
3322    private static final String PROVISIONING_URL_PATH =
3323            "/data/misc/radio/provisioning_urls.xml";
3324    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3325
3326    /** XML tag for root element. */
3327    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3328    /** XML tag for individual url */
3329    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3330    /** XML attribute for mcc */
3331    private static final String ATTR_MCC = "mcc";
3332    /** XML attribute for mnc */
3333    private static final String ATTR_MNC = "mnc";
3334
3335    private String getProvisioningUrlBaseFromFile() {
3336        FileReader fileReader = null;
3337        XmlPullParser parser = null;
3338        Configuration config = mContext.getResources().getConfiguration();
3339
3340        try {
3341            fileReader = new FileReader(mProvisioningUrlFile);
3342            parser = Xml.newPullParser();
3343            parser.setInput(fileReader);
3344            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3345
3346            while (true) {
3347                XmlUtils.nextElement(parser);
3348
3349                String element = parser.getName();
3350                if (element == null) break;
3351
3352                if (element.equals(TAG_PROVISIONING_URL)) {
3353                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3354                    try {
3355                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3356                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3357                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3358                                parser.next();
3359                                if (parser.getEventType() == XmlPullParser.TEXT) {
3360                                    return parser.getText();
3361                                }
3362                            }
3363                        }
3364                    } catch (NumberFormatException e) {
3365                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3366                    }
3367                }
3368            }
3369            return null;
3370        } catch (FileNotFoundException e) {
3371            loge("Carrier Provisioning Urls file not found");
3372        } catch (XmlPullParserException e) {
3373            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3374        } catch (IOException e) {
3375            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3376        } finally {
3377            if (fileReader != null) {
3378                try {
3379                    fileReader.close();
3380                } catch (IOException e) {}
3381            }
3382        }
3383        return null;
3384    }
3385
3386    @Override
3387    public String getMobileProvisioningUrl() {
3388        enforceConnectivityInternalPermission();
3389        String url = getProvisioningUrlBaseFromFile();
3390        if (TextUtils.isEmpty(url)) {
3391            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3392            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3393        } else {
3394            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3395        }
3396        // populate the iccid, imei and phone number in the provisioning url.
3397        if (!TextUtils.isEmpty(url)) {
3398            String phoneNumber = mTelephonyManager.getLine1Number();
3399            if (TextUtils.isEmpty(phoneNumber)) {
3400                phoneNumber = "0000000000";
3401            }
3402            url = String.format(url,
3403                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3404                    mTelephonyManager.getDeviceId() /* IMEI */,
3405                    phoneNumber /* Phone numer */);
3406        }
3407
3408        return url;
3409    }
3410
3411    @Override
3412    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3413            String action) {
3414        enforceConnectivityInternalPermission();
3415        final long ident = Binder.clearCallingIdentity();
3416        try {
3417            setProvNotificationVisible(visible, networkType, action);
3418        } finally {
3419            Binder.restoreCallingIdentity(ident);
3420        }
3421    }
3422
3423    @Override
3424    public void setAirplaneMode(boolean enable) {
3425        enforceConnectivityInternalPermission();
3426        final long ident = Binder.clearCallingIdentity();
3427        try {
3428            final ContentResolver cr = mContext.getContentResolver();
3429            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3430            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3431            intent.putExtra("state", enable);
3432            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3433        } finally {
3434            Binder.restoreCallingIdentity(ident);
3435        }
3436    }
3437
3438    private void onUserStart(int userId) {
3439        synchronized(mVpns) {
3440            Vpn userVpn = mVpns.get(userId);
3441            if (userVpn != null) {
3442                loge("Starting user already has a VPN");
3443                return;
3444            }
3445            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3446            mVpns.put(userId, userVpn);
3447        }
3448    }
3449
3450    private void onUserStop(int userId) {
3451        synchronized(mVpns) {
3452            Vpn userVpn = mVpns.get(userId);
3453            if (userVpn == null) {
3454                loge("Stopping user has no VPN");
3455                return;
3456            }
3457            mVpns.delete(userId);
3458        }
3459    }
3460
3461    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3462        @Override
3463        public void onReceive(Context context, Intent intent) {
3464            final String action = intent.getAction();
3465            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3466            if (userId == UserHandle.USER_NULL) return;
3467
3468            if (Intent.ACTION_USER_STARTING.equals(action)) {
3469                onUserStart(userId);
3470            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3471                onUserStop(userId);
3472            }
3473        }
3474    };
3475
3476    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3477            new HashMap<Messenger, NetworkFactoryInfo>();
3478    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3479            new HashMap<NetworkRequest, NetworkRequestInfo>();
3480
3481    private static class NetworkFactoryInfo {
3482        public final String name;
3483        public final Messenger messenger;
3484        public final AsyncChannel asyncChannel;
3485
3486        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3487            this.name = name;
3488            this.messenger = messenger;
3489            this.asyncChannel = asyncChannel;
3490        }
3491    }
3492
3493    /**
3494     * Tracks info about the requester.
3495     * Also used to notice when the calling process dies so we can self-expire
3496     */
3497    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3498        static final boolean REQUEST = true;
3499        static final boolean LISTEN = false;
3500
3501        final NetworkRequest request;
3502        final PendingIntent mPendingIntent;
3503        boolean mPendingIntentSent;
3504        private final IBinder mBinder;
3505        final int mPid;
3506        final int mUid;
3507        final Messenger messenger;
3508        final boolean isRequest;
3509
3510        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3511            request = r;
3512            mPendingIntent = pi;
3513            messenger = null;
3514            mBinder = null;
3515            mPid = getCallingPid();
3516            mUid = getCallingUid();
3517            this.isRequest = isRequest;
3518        }
3519
3520        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3521            super();
3522            messenger = m;
3523            request = r;
3524            mBinder = binder;
3525            mPid = getCallingPid();
3526            mUid = getCallingUid();
3527            this.isRequest = isRequest;
3528            mPendingIntent = null;
3529
3530            try {
3531                mBinder.linkToDeath(this, 0);
3532            } catch (RemoteException e) {
3533                binderDied();
3534            }
3535        }
3536
3537        void unlinkDeathRecipient() {
3538            if (mBinder != null) {
3539                mBinder.unlinkToDeath(this, 0);
3540            }
3541        }
3542
3543        public void binderDied() {
3544            log("ConnectivityService NetworkRequestInfo binderDied(" +
3545                    request + ", " + mBinder + ")");
3546            releaseNetworkRequest(request);
3547        }
3548
3549        public String toString() {
3550            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
3551                    mPid + " for " + request +
3552                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3553        }
3554    }
3555
3556    @Override
3557    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3558            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3559        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3560        enforceNetworkRequestPermissions(networkCapabilities);
3561        enforceMeteredApnPolicy(networkCapabilities);
3562
3563        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3564            throw new IllegalArgumentException("Bad timeout specified");
3565        }
3566
3567        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3568                nextNetworkRequestId());
3569        if (DBG) log("requestNetwork for " + networkRequest);
3570        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3571                NetworkRequestInfo.REQUEST);
3572
3573        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3574        if (timeoutMs > 0) {
3575            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3576                    nri), timeoutMs);
3577        }
3578        return networkRequest;
3579    }
3580
3581    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3582        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3583            enforceConnectivityInternalPermission();
3584        } else {
3585            enforceChangePermission();
3586        }
3587    }
3588
3589    @Override
3590    public boolean requestBandwidthUpdate(Network network) {
3591        enforceAccessPermission();
3592        NetworkAgentInfo nai = null;
3593        if (network == null) {
3594            return false;
3595        }
3596        synchronized (mNetworkForNetId) {
3597            nai = mNetworkForNetId.get(network.netId);
3598        }
3599        if (nai != null) {
3600            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3601            return true;
3602        }
3603        return false;
3604    }
3605
3606
3607    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3608        // if UID is restricted, don't allow them to bring up metered APNs
3609        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3610            final int uidRules;
3611            final int uid = Binder.getCallingUid();
3612            synchronized(mRulesLock) {
3613                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3614            }
3615            if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
3616                // we could silently fail or we can filter the available nets to only give
3617                // them those they have access to.  Chose the more useful
3618                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3619            }
3620        }
3621    }
3622
3623    @Override
3624    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3625            PendingIntent operation) {
3626        checkNotNull(operation, "PendingIntent cannot be null.");
3627        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3628        enforceNetworkRequestPermissions(networkCapabilities);
3629        enforceMeteredApnPolicy(networkCapabilities);
3630
3631        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3632                nextNetworkRequestId());
3633        if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3634        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3635                NetworkRequestInfo.REQUEST);
3636        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3637                nri));
3638        return networkRequest;
3639    }
3640
3641    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3642        mHandler.sendMessageDelayed(
3643                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3644                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3645    }
3646
3647    @Override
3648    public void releasePendingNetworkRequest(PendingIntent operation) {
3649        checkNotNull(operation, "PendingIntent cannot be null.");
3650        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3651                getCallingUid(), 0, operation));
3652    }
3653
3654    // In order to implement the compatibility measure for pre-M apps that call
3655    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3656    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3657    // This ensures it has permission to do so.
3658    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3659        if (nc == null) {
3660            return false;
3661        }
3662        int[] transportTypes = nc.getTransportTypes();
3663        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3664            return false;
3665        }
3666        try {
3667            mContext.enforceCallingOrSelfPermission(
3668                    android.Manifest.permission.ACCESS_WIFI_STATE,
3669                    "ConnectivityService");
3670        } catch (SecurityException e) {
3671            return false;
3672        }
3673        return true;
3674    }
3675
3676    @Override
3677    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3678            Messenger messenger, IBinder binder) {
3679        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3680            enforceAccessPermission();
3681        }
3682
3683        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3684                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3685        if (DBG) log("listenForNetwork for " + networkRequest);
3686        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3687                NetworkRequestInfo.LISTEN);
3688
3689        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3690        return networkRequest;
3691    }
3692
3693    @Override
3694    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3695            PendingIntent operation) {
3696    }
3697
3698    @Override
3699    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3700        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3701                0, networkRequest));
3702    }
3703
3704    @Override
3705    public void registerNetworkFactory(Messenger messenger, String name) {
3706        enforceConnectivityInternalPermission();
3707        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3708        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3709    }
3710
3711    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3712        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3713        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3714        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3715    }
3716
3717    @Override
3718    public void unregisterNetworkFactory(Messenger messenger) {
3719        enforceConnectivityInternalPermission();
3720        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3721    }
3722
3723    private void handleUnregisterNetworkFactory(Messenger messenger) {
3724        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3725        if (nfi == null) {
3726            loge("Failed to find Messenger in unregisterNetworkFactory");
3727            return;
3728        }
3729        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3730    }
3731
3732    /**
3733     * NetworkAgentInfo supporting a request by requestId.
3734     * These have already been vetted (their Capabilities satisfy the request)
3735     * and the are the highest scored network available.
3736     * the are keyed off the Requests requestId.
3737     */
3738    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3739    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3740            new SparseArray<NetworkAgentInfo>();
3741
3742    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3743    @GuardedBy("mNetworkForNetId")
3744    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3745            new SparseArray<NetworkAgentInfo>();
3746    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3747    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3748    // there may not be a strict 1:1 correlation between the two.
3749    @GuardedBy("mNetworkForNetId")
3750    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3751
3752    // NetworkAgentInfo keyed off its connecting messenger
3753    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3754    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3755    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3756            new HashMap<Messenger, NetworkAgentInfo>();
3757
3758    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3759    private final NetworkRequest mDefaultRequest;
3760
3761    // Request used to optionally keep mobile data active even when higher
3762    // priority networks like Wi-Fi are active.
3763    private final NetworkRequest mDefaultMobileDataRequest;
3764
3765    private NetworkAgentInfo getDefaultNetwork() {
3766        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3767    }
3768
3769    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3770        return nai == getDefaultNetwork();
3771    }
3772
3773    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3774            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3775            int currentScore, NetworkMisc networkMisc) {
3776        enforceConnectivityInternalPermission();
3777
3778        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3779        // satisfies mDefaultRequest.
3780        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3781                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3782                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3783                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
3784        synchronized (this) {
3785            nai.networkMonitor.systemReady = mSystemReady;
3786        }
3787        if (DBG) log("registerNetworkAgent " + nai);
3788        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3789        return nai.network.netId;
3790    }
3791
3792    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3793        if (VDBG) log("Got NetworkAgent Messenger");
3794        mNetworkAgentInfos.put(na.messenger, na);
3795        synchronized (mNetworkForNetId) {
3796            mNetworkForNetId.put(na.network.netId, na);
3797        }
3798        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3799        NetworkInfo networkInfo = na.networkInfo;
3800        na.networkInfo = null;
3801        updateNetworkInfo(na, networkInfo);
3802    }
3803
3804    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3805        LinkProperties newLp = networkAgent.linkProperties;
3806        int netId = networkAgent.network.netId;
3807
3808        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3809        // we do anything else, make sure its LinkProperties are accurate.
3810        if (networkAgent.clatd != null) {
3811            networkAgent.clatd.fixupLinkProperties(oldLp);
3812        }
3813
3814        updateInterfaces(newLp, oldLp, netId);
3815        updateMtu(newLp, oldLp);
3816        // TODO - figure out what to do for clat
3817//        for (LinkProperties lp : newLp.getStackedLinks()) {
3818//            updateMtu(lp, null);
3819//        }
3820        updateTcpBufferSizes(networkAgent);
3821
3822        // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3823        // In L, we used it only when the network had Internet access but provided no DNS servers.
3824        // For now, just disable it, and if disabling it doesn't break things, remove it.
3825        // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3826        //        NET_CAPABILITY_INTERNET);
3827        final boolean useDefaultDns = false;
3828        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3829        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3830
3831        updateClat(newLp, oldLp, networkAgent);
3832        if (isDefaultNetwork(networkAgent)) {
3833            handleApplyDefaultProxy(newLp.getHttpProxy());
3834        } else {
3835            updateProxy(newLp, oldLp, networkAgent);
3836        }
3837        // TODO - move this check to cover the whole function
3838        if (!Objects.equals(newLp, oldLp)) {
3839            notifyIfacesChanged();
3840            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3841        }
3842    }
3843
3844    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3845        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3846        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
3847
3848        if (!wasRunningClat && shouldRunClat) {
3849            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3850            nai.clatd.start();
3851        } else if (wasRunningClat && !shouldRunClat) {
3852            nai.clatd.stop();
3853        }
3854    }
3855
3856    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3857        CompareResult<String> interfaceDiff = new CompareResult<String>();
3858        if (oldLp != null) {
3859            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3860        } else if (newLp != null) {
3861            interfaceDiff.added = newLp.getAllInterfaceNames();
3862        }
3863        for (String iface : interfaceDiff.added) {
3864            try {
3865                if (DBG) log("Adding iface " + iface + " to network " + netId);
3866                mNetd.addInterfaceToNetwork(iface, netId);
3867            } catch (Exception e) {
3868                loge("Exception adding interface: " + e);
3869            }
3870        }
3871        for (String iface : interfaceDiff.removed) {
3872            try {
3873                if (DBG) log("Removing iface " + iface + " from network " + netId);
3874                mNetd.removeInterfaceFromNetwork(iface, netId);
3875            } catch (Exception e) {
3876                loge("Exception removing interface: " + e);
3877            }
3878        }
3879    }
3880
3881    /**
3882     * Have netd update routes from oldLp to newLp.
3883     * @return true if routes changed between oldLp and newLp
3884     */
3885    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
3886        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3887        if (oldLp != null) {
3888            routeDiff = oldLp.compareAllRoutes(newLp);
3889        } else if (newLp != null) {
3890            routeDiff.added = newLp.getAllRoutes();
3891        }
3892
3893        // add routes before removing old in case it helps with continuous connectivity
3894
3895        // do this twice, adding non-nexthop routes first, then routes they are dependent on
3896        for (RouteInfo route : routeDiff.added) {
3897            if (route.hasGateway()) continue;
3898            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3899            try {
3900                mNetd.addRoute(netId, route);
3901            } catch (Exception e) {
3902                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3903                    loge("Exception in addRoute for non-gateway: " + e);
3904                }
3905            }
3906        }
3907        for (RouteInfo route : routeDiff.added) {
3908            if (route.hasGateway() == false) continue;
3909            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3910            try {
3911                mNetd.addRoute(netId, route);
3912            } catch (Exception e) {
3913                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3914                    loge("Exception in addRoute for gateway: " + e);
3915                }
3916            }
3917        }
3918
3919        for (RouteInfo route : routeDiff.removed) {
3920            if (DBG) log("Removing Route [" + route + "] from network " + netId);
3921            try {
3922                mNetd.removeRoute(netId, route);
3923            } catch (Exception e) {
3924                loge("Exception in removeRoute: " + e);
3925            }
3926        }
3927        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
3928    }
3929
3930    // TODO: investigate moving this into LinkProperties, if only to make more accurate
3931    // the isProvisioned() checks.
3932    private static Collection<InetAddress> getLikelyReachableDnsServers(LinkProperties lp) {
3933        final ArrayList<InetAddress> dnsServers = new ArrayList<InetAddress>();
3934        final List<RouteInfo> allRoutes = lp.getAllRoutes();
3935        for (InetAddress nameserver : lp.getDnsServers()) {
3936            // If the LinkProperties doesn't include a route to the nameserver, ignore it.
3937            final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, nameserver);
3938            if (bestRoute == null) {
3939                continue;
3940            }
3941
3942            // TODO: better source address evaluation for destination addresses.
3943            if (nameserver instanceof Inet4Address) {
3944                if (!lp.hasIPv4Address()) {
3945                    continue;
3946                }
3947            } else if (nameserver instanceof Inet6Address) {
3948                if (nameserver.isLinkLocalAddress()) {
3949                    if (((Inet6Address)nameserver).getScopeId() == 0) {
3950                        // For now, just make sure link-local DNS servers have
3951                        // scopedIds set, since DNS lookups will fail otherwise.
3952                        // TODO: verify the scopeId matches that of lp's interface.
3953                        continue;
3954                    }
3955                }  else {
3956                    if (bestRoute.isIPv6Default() && !lp.hasGlobalIPv6Address()) {
3957                        // TODO: reconsider all corner cases (disconnected ULA networks, ...).
3958                        continue;
3959                    }
3960                }
3961            }
3962
3963            dnsServers.add(nameserver);
3964        }
3965        return Collections.unmodifiableList(dnsServers);
3966    }
3967
3968    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3969                             boolean flush, boolean useDefaultDns) {
3970        // TODO: consider comparing the getLikelyReachableDnsServers() lists, in case the
3971        // route to a DNS server has been removed (only really applicable in special cases
3972        // where there is no default route).
3973        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
3974            Collection<InetAddress> dnses = getLikelyReachableDnsServers(newLp);
3975            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
3976                dnses = new ArrayList();
3977                dnses.add(mDefaultDns);
3978                if (DBG) {
3979                    loge("no dns provided for netId " + netId + ", so using defaults");
3980                }
3981            }
3982            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
3983            try {
3984                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3985                    newLp.getDomains());
3986            } catch (Exception e) {
3987                loge("Exception in setDnsServersForNetwork: " + e);
3988            }
3989            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3990            if (defaultNai != null && defaultNai.network.netId == netId) {
3991                setDefaultDnsSystemProperties(dnses);
3992            }
3993            flushVmDnsCache();
3994        } else if (flush) {
3995            try {
3996                mNetd.flushNetworkDnsCache(netId);
3997            } catch (Exception e) {
3998                loge("Exception in flushNetworkDnsCache: " + e);
3999            }
4000            flushVmDnsCache();
4001        }
4002    }
4003
4004    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4005        int last = 0;
4006        for (InetAddress dns : dnses) {
4007            ++last;
4008            String key = "net.dns" + last;
4009            String value = dns.getHostAddress();
4010            SystemProperties.set(key, value);
4011        }
4012        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4013            String key = "net.dns" + i;
4014            SystemProperties.set(key, "");
4015        }
4016        mNumDnsEntries = last;
4017    }
4018
4019    private void updateCapabilities(NetworkAgentInfo networkAgent,
4020            NetworkCapabilities networkCapabilities) {
4021        if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4022            synchronized (networkAgent) {
4023                networkAgent.networkCapabilities = networkCapabilities;
4024            }
4025            if (networkAgent.lastValidated) {
4026                networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4027                // There's no need to remove the capability if we think the network is unvalidated,
4028                // because NetworkAgents don't set the validated capability.
4029            }
4030            rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
4031            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
4032        }
4033    }
4034
4035    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4036        for (int i = 0; i < nai.networkRequests.size(); i++) {
4037            NetworkRequest nr = nai.networkRequests.valueAt(i);
4038            // Don't send listening requests to factories. b/17393458
4039            if (!isRequest(nr)) continue;
4040            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4041        }
4042    }
4043
4044    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4045        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4046        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4047            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4048                    networkRequest);
4049        }
4050    }
4051
4052    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4053            int notificationType) {
4054        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4055            Intent intent = new Intent();
4056            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4057            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4058            nri.mPendingIntentSent = true;
4059            sendIntent(nri.mPendingIntent, intent);
4060        }
4061        // else not handled
4062    }
4063
4064    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4065        mPendingIntentWakeLock.acquire();
4066        try {
4067            if (DBG) log("Sending " + pendingIntent);
4068            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4069        } catch (PendingIntent.CanceledException e) {
4070            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4071            mPendingIntentWakeLock.release();
4072            releasePendingNetworkRequest(pendingIntent);
4073        }
4074        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4075    }
4076
4077    @Override
4078    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4079            String resultData, Bundle resultExtras) {
4080        if (DBG) log("Finished sending " + pendingIntent);
4081        mPendingIntentWakeLock.release();
4082        // Release with a delay so the receiving client has an opportunity to put in its
4083        // own request.
4084        releasePendingNetworkRequestWithDelay(pendingIntent);
4085    }
4086
4087    private void callCallbackForRequest(NetworkRequestInfo nri,
4088            NetworkAgentInfo networkAgent, int notificationType) {
4089        if (nri.messenger == null) return;  // Default request has no msgr
4090        Bundle bundle = new Bundle();
4091        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4092                new NetworkRequest(nri.request));
4093        Message msg = Message.obtain();
4094        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4095                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4096            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4097        }
4098        switch (notificationType) {
4099            case ConnectivityManager.CALLBACK_LOSING: {
4100                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4101                break;
4102            }
4103            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4104                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4105                        new NetworkCapabilities(networkAgent.networkCapabilities));
4106                break;
4107            }
4108            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4109                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4110                        new LinkProperties(networkAgent.linkProperties));
4111                break;
4112            }
4113        }
4114        msg.what = notificationType;
4115        msg.setData(bundle);
4116        try {
4117            if (VDBG) {
4118                log("sending notification " + notifyTypeToName(notificationType) +
4119                        " for " + nri.request);
4120            }
4121            nri.messenger.send(msg);
4122        } catch (RemoteException e) {
4123            // may occur naturally in the race of binder death.
4124            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4125        }
4126    }
4127
4128    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4129        for (int i = 0; i < nai.networkRequests.size(); i++) {
4130            NetworkRequest nr = nai.networkRequests.valueAt(i);
4131            // Ignore listening requests.
4132            if (!isRequest(nr)) continue;
4133            loge("Dead network still had at least " + nr);
4134            break;
4135        }
4136        nai.asyncChannel.disconnect();
4137    }
4138
4139    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4140        if (oldNetwork == null) {
4141            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4142            return;
4143        }
4144        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4145        teardownUnneededNetwork(oldNetwork);
4146    }
4147
4148    private void makeDefault(NetworkAgentInfo newNetwork) {
4149        if (DBG) log("Switching to new default network: " + newNetwork);
4150        setupDataActivityTracking(newNetwork);
4151        try {
4152            mNetd.setDefaultNetId(newNetwork.network.netId);
4153        } catch (Exception e) {
4154            loge("Exception setting default network :" + e);
4155        }
4156        notifyLockdownVpn(newNetwork);
4157        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4158        updateTcpBufferSizes(newNetwork);
4159        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4160    }
4161
4162    // Handles a network appearing or improving its score.
4163    //
4164    // - Evaluates all current NetworkRequests that can be
4165    //   satisfied by newNetwork, and reassigns to newNetwork
4166    //   any such requests for which newNetwork is the best.
4167    //
4168    // - Lingers any validated Networks that as a result are no longer
4169    //   needed. A network is needed if it is the best network for
4170    //   one or more NetworkRequests, or if it is a VPN.
4171    //
4172    // - Tears down newNetwork if it just became validated
4173    //   (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4174    //
4175    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4176    //   networks that have no chance (i.e. even if validated)
4177    //   of becoming the highest scoring network.
4178    //
4179    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4180    // it does not remove NetworkRequests that other Networks could better satisfy.
4181    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4182    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4183    // as it performs better by a factor of the number of Networks.
4184    //
4185    // @param newNetwork is the network to be matched against NetworkRequests.
4186    // @param nascent indicates if newNetwork just became validated, in which case it should be
4187    //               torn down if unneeded.
4188    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4189    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4190    //               validated) of becoming the highest scoring network.
4191    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4192            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4193        if (!newNetwork.created) return;
4194        if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
4195            loge("ERROR: nascent network not validated.");
4196        }
4197        boolean keep = newNetwork.isVPN();
4198        boolean isNewDefault = false;
4199        NetworkAgentInfo oldDefaultNetwork = null;
4200        if (DBG) log("rematching " + newNetwork.name());
4201        // Find and migrate to this Network any NetworkRequests for
4202        // which this network is now the best.
4203        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4204        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4205        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4206        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4207            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4208            if (newNetwork == currentNetwork) {
4209                if (DBG) {
4210                    log("Network " + newNetwork.name() + " was already satisfying" +
4211                            " request " + nri.request.requestId + ". No change.");
4212                }
4213                keep = true;
4214                continue;
4215            }
4216
4217            // check if it satisfies the NetworkCapabilities
4218            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4219            if (newNetwork.satisfies(nri.request)) {
4220                if (!nri.isRequest) {
4221                    // This is not a request, it's a callback listener.
4222                    // Add it to newNetwork regardless of score.
4223                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4224                    continue;
4225                }
4226
4227                // next check if it's better than any current network we're using for
4228                // this request
4229                if (VDBG) {
4230                    log("currentScore = " +
4231                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4232                            ", newScore = " + newNetwork.getCurrentScore());
4233                }
4234                if (currentNetwork == null ||
4235                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4236                    if (currentNetwork != null) {
4237                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4238                        currentNetwork.networkRequests.remove(nri.request.requestId);
4239                        currentNetwork.networkLingered.add(nri.request);
4240                        affectedNetworks.add(currentNetwork);
4241                    } else {
4242                        if (DBG) log("   accepting network in place of null");
4243                    }
4244                    unlinger(newNetwork);
4245                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4246                    if (!newNetwork.addRequest(nri.request)) {
4247                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4248                    }
4249                    addedRequests.add(nri);
4250                    keep = true;
4251                    // Tell NetworkFactories about the new score, so they can stop
4252                    // trying to connect if they know they cannot match it.
4253                    // TODO - this could get expensive if we have alot of requests for this
4254                    // network.  Think about if there is a way to reduce this.  Push
4255                    // netid->request mapping to each factory?
4256                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4257                    if (mDefaultRequest.requestId == nri.request.requestId) {
4258                        isNewDefault = true;
4259                        oldDefaultNetwork = currentNetwork;
4260                    }
4261                }
4262            }
4263        }
4264        // Linger any networks that are no longer needed.
4265        for (NetworkAgentInfo nai : affectedNetworks) {
4266            if (nai.everValidated && unneeded(nai)) {
4267                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4268                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4269            } else {
4270                unlinger(nai);
4271            }
4272        }
4273        if (keep) {
4274            if (isNewDefault) {
4275                // Notify system services that this network is up.
4276                makeDefault(newNetwork);
4277                synchronized (ConnectivityService.this) {
4278                    // have a new default network, release the transition wakelock in
4279                    // a second if it's held.  The second pause is to allow apps
4280                    // to reconnect over the new network
4281                    if (mNetTransitionWakeLock.isHeld()) {
4282                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4283                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4284                                mNetTransitionWakeLockSerialNumber, 0),
4285                                1000);
4286                    }
4287                }
4288            }
4289
4290            // do this after the default net is switched, but
4291            // before LegacyTypeTracker sends legacy broadcasts
4292            for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4293
4294            if (isNewDefault) {
4295                // Maintain the illusion: since the legacy API only
4296                // understands one network at a time, we must pretend
4297                // that the current default network disconnected before
4298                // the new one connected.
4299                if (oldDefaultNetwork != null) {
4300                    mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4301                                              oldDefaultNetwork, true);
4302                }
4303                mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
4304                mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4305                notifyLockdownVpn(newNetwork);
4306            }
4307
4308            // Notify battery stats service about this network, both the normal
4309            // interface and any stacked links.
4310            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4311            try {
4312                final IBatteryStats bs = BatteryStatsService.getService();
4313                final int type = newNetwork.networkInfo.getType();
4314
4315                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4316                bs.noteNetworkInterfaceType(baseIface, type);
4317                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4318                    final String stackedIface = stacked.getInterfaceName();
4319                    bs.noteNetworkInterfaceType(stackedIface, type);
4320                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4321                }
4322            } catch (RemoteException ignored) {
4323            }
4324
4325            // This has to happen after the notifyNetworkCallbacks as that tickles each
4326            // ConnectivityManager instance so that legacy requests correctly bind dns
4327            // requests to this network.  The legacy users are listening for this bcast
4328            // and will generally do a dns request so they can ensureRouteToHost and if
4329            // they do that before the callbacks happen they'll use the default network.
4330            //
4331            // TODO: Is there still a race here? We send the broadcast
4332            // after sending the callback, but if the app can receive the
4333            // broadcast before the callback, it might still break.
4334            //
4335            // This *does* introduce a race where if the user uses the new api
4336            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4337            // they may get old info.  Reverse this after the old startUsing api is removed.
4338            // This is on top of the multiple intent sequencing referenced in the todo above.
4339            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4340                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4341                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4342                    // legacy type tracker filters out repeat adds
4343                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4344                }
4345            }
4346
4347            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4348            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4349            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4350            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4351            if (newNetwork.isVPN()) {
4352                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4353            }
4354        } else if (nascent == NascentState.JUST_VALIDATED) {
4355            // Only tear down newly validated networks here.  Leave unvalidated to either become
4356            // validated (and get evaluated against peers, one losing here), or get reaped (see
4357            // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4358            // network.  Networks that have been up for a while and are validated should be torn
4359            // down via the lingering process so communication on that network is given time to
4360            // wrap up.
4361            if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
4362            teardownUnneededNetwork(newNetwork);
4363        }
4364        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4365            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4366                if (!nai.everValidated && unneeded(nai)) {
4367                    if (DBG) log("Reaping " + nai.name());
4368                    teardownUnneededNetwork(nai);
4369                }
4370            }
4371        }
4372    }
4373
4374    // Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4375    // being disconnected.
4376    // If only one Network's score or capabilities have been modified since the last time
4377    // this function was called, pass this Network in via the "changed" arugment, otherwise
4378    // pass null.
4379    // If only one Network has been changed but its NetworkCapabilities have not changed,
4380    // pass in the Network's score (from getCurrentScore()) prior to the change via
4381    // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4382    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4383        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4384        // to avoid the slowness.  It is not simply enough to process just "changed", for
4385        // example in the case where "changed"'s score decreases and another network should begin
4386        // satifying a NetworkRequest that "changed" currently satisfies.
4387
4388        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4389        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4390        // rematchNetworkAndRequests() handles.
4391        if (changed != null && oldScore < changed.getCurrentScore()) {
4392            rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4393                    ReapUnvalidatedNetworks.REAP);
4394        } else {
4395            for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4396                rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4397                        NascentState.NOT_JUST_VALIDATED,
4398                        // Only reap the last time through the loop.  Reaping before all rematching
4399                        // is complete could incorrectly teardown a network that hasn't yet been
4400                        // rematched.
4401                        i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4402                                : ReapUnvalidatedNetworks.REAP);
4403            }
4404        }
4405    }
4406
4407    private void updateInetCondition(NetworkAgentInfo nai) {
4408        // Don't bother updating until we've graduated to validated at least once.
4409        if (!nai.everValidated) return;
4410        // For now only update icons for default connection.
4411        // TODO: Update WiFi and cellular icons separately. b/17237507
4412        if (!isDefaultNetwork(nai)) return;
4413
4414        int newInetCondition = nai.lastValidated ? 100 : 0;
4415        // Don't repeat publish.
4416        if (newInetCondition == mDefaultInetConditionPublished) return;
4417
4418        mDefaultInetConditionPublished = newInetCondition;
4419        sendInetConditionBroadcast(nai.networkInfo);
4420    }
4421
4422    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4423        if (mLockdownTracker != null) {
4424            if (nai != null && nai.isVPN()) {
4425                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4426            } else {
4427                mLockdownTracker.onNetworkInfoChanged();
4428            }
4429        }
4430    }
4431
4432    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4433        NetworkInfo.State state = newInfo.getState();
4434        NetworkInfo oldInfo = null;
4435        synchronized (networkAgent) {
4436            oldInfo = networkAgent.networkInfo;
4437            networkAgent.networkInfo = newInfo;
4438        }
4439        notifyLockdownVpn(networkAgent);
4440
4441        if (oldInfo != null && oldInfo.getState() == state) {
4442            if (VDBG) log("ignoring duplicate network state non-change");
4443            return;
4444        }
4445        if (DBG) {
4446            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4447                    (oldInfo == null ? "null" : oldInfo.getState()) +
4448                    " to " + state);
4449        }
4450
4451        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4452            try {
4453                // This should never fail.  Specifying an already in use NetID will cause failure.
4454                if (networkAgent.isVPN()) {
4455                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4456                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4457                            (networkAgent.networkMisc == null ||
4458                                !networkAgent.networkMisc.allowBypass));
4459                } else {
4460                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4461                }
4462            } catch (Exception e) {
4463                loge("Error creating network " + networkAgent.network.netId + ": "
4464                        + e.getMessage());
4465                return;
4466            }
4467            networkAgent.created = true;
4468            updateLinkProperties(networkAgent, null);
4469            notifyIfacesChanged();
4470
4471            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4472            scheduleUnvalidatedPrompt(networkAgent);
4473
4474            if (networkAgent.isVPN()) {
4475                // Temporarily disable the default proxy (not global).
4476                synchronized (mProxyLock) {
4477                    if (!mDefaultProxyDisabled) {
4478                        mDefaultProxyDisabled = true;
4479                        if (mGlobalProxy == null && mDefaultProxy != null) {
4480                            sendProxyBroadcast(null);
4481                        }
4482                    }
4483                }
4484                // TODO: support proxy per network.
4485            }
4486
4487            // Consider network even though it is not yet validated.
4488            rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4489                    ReapUnvalidatedNetworks.REAP);
4490
4491            // This has to happen after matching the requests, because callbacks are just requests.
4492            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4493        } else if (state == NetworkInfo.State.DISCONNECTED ||
4494                state == NetworkInfo.State.SUSPENDED) {
4495            networkAgent.asyncChannel.disconnect();
4496            if (networkAgent.isVPN()) {
4497                synchronized (mProxyLock) {
4498                    if (mDefaultProxyDisabled) {
4499                        mDefaultProxyDisabled = false;
4500                        if (mGlobalProxy == null && mDefaultProxy != null) {
4501                            sendProxyBroadcast(mDefaultProxy);
4502                        }
4503                    }
4504                }
4505            }
4506        }
4507    }
4508
4509    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4510        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4511        if (score < 0) {
4512            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4513                    ").  Bumping score to min of 0");
4514            score = 0;
4515        }
4516
4517        final int oldScore = nai.getCurrentScore();
4518        nai.setCurrentScore(score);
4519
4520        rematchAllNetworksAndRequests(nai, oldScore);
4521
4522        sendUpdatedScoreToFactories(nai);
4523    }
4524
4525    // notify only this one new request of the current state
4526    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4527        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4528        // TODO - read state from monitor to decide what to send.
4529//        if (nai.networkMonitor.isLingering()) {
4530//            notifyType = NetworkCallbacks.LOSING;
4531//        } else if (nai.networkMonitor.isEvaluating()) {
4532//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4533//        }
4534        if (nri.mPendingIntent == null) {
4535            callCallbackForRequest(nri, nai, notifyType);
4536        } else {
4537            sendPendingIntentForRequest(nri, nai, notifyType);
4538        }
4539    }
4540
4541    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4542        // The NetworkInfo we actually send out has no bearing on the real
4543        // state of affairs. For example, if the default connection is mobile,
4544        // and a request for HIPRI has just gone away, we need to pretend that
4545        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4546        // the state to DISCONNECTED, even though the network is of type MOBILE
4547        // and is still connected.
4548        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4549        info.setType(type);
4550        if (connected) {
4551            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4552            sendConnectedBroadcast(info);
4553        } else {
4554            info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
4555            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4556            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4557            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4558            if (info.isFailover()) {
4559                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4560                nai.networkInfo.setFailover(false);
4561            }
4562            if (info.getReason() != null) {
4563                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4564            }
4565            if (info.getExtraInfo() != null) {
4566                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4567            }
4568            NetworkAgentInfo newDefaultAgent = null;
4569            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4570                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4571                if (newDefaultAgent != null) {
4572                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4573                            newDefaultAgent.networkInfo);
4574                } else {
4575                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4576                }
4577            }
4578            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4579                    mDefaultInetConditionPublished);
4580            sendStickyBroadcast(intent);
4581            if (newDefaultAgent != null) {
4582                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4583            }
4584        }
4585    }
4586
4587    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4588        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4589        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4590            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4591            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4592            if (VDBG) log(" sending notification for " + nr);
4593            if (nri.mPendingIntent == null) {
4594                callCallbackForRequest(nri, networkAgent, notifyType);
4595            } else {
4596                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4597            }
4598        }
4599    }
4600
4601    private String notifyTypeToName(int notifyType) {
4602        switch (notifyType) {
4603            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4604            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4605            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4606            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4607            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4608            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4609            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4610            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4611        }
4612        return "UNKNOWN";
4613    }
4614
4615    /**
4616     * Notify other system services that set of active ifaces has changed.
4617     */
4618    private void notifyIfacesChanged() {
4619        try {
4620            mStatsService.forceUpdateIfaces();
4621        } catch (Exception ignored) {
4622        }
4623    }
4624
4625    @Override
4626    public boolean addVpnAddress(String address, int prefixLength) {
4627        throwIfLockdownEnabled();
4628        int user = UserHandle.getUserId(Binder.getCallingUid());
4629        synchronized (mVpns) {
4630            return mVpns.get(user).addAddress(address, prefixLength);
4631        }
4632    }
4633
4634    @Override
4635    public boolean removeVpnAddress(String address, int prefixLength) {
4636        throwIfLockdownEnabled();
4637        int user = UserHandle.getUserId(Binder.getCallingUid());
4638        synchronized (mVpns) {
4639            return mVpns.get(user).removeAddress(address, prefixLength);
4640        }
4641    }
4642
4643    @Override
4644    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4645        throwIfLockdownEnabled();
4646        int user = UserHandle.getUserId(Binder.getCallingUid());
4647        boolean success;
4648        synchronized (mVpns) {
4649            success = mVpns.get(user).setUnderlyingNetworks(networks);
4650        }
4651        if (success) {
4652            notifyIfacesChanged();
4653        }
4654        return success;
4655    }
4656
4657    @Override
4658    public void factoryReset() {
4659        enforceConnectivityInternalPermission();
4660
4661        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4662            return;
4663        }
4664
4665        final int userId = UserHandle.getCallingUserId();
4666
4667        // Turn airplane mode off
4668        setAirplaneMode(false);
4669
4670        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4671            // Untether
4672            for (String tether : getTetheredIfaces()) {
4673                untether(tether);
4674            }
4675        }
4676
4677        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4678            // Turn VPN off
4679            VpnConfig vpnConfig = getVpnConfig(userId);
4680            if (vpnConfig != null) {
4681                if (vpnConfig.legacy) {
4682                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4683                } else {
4684                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4685                    // in the future without user intervention.
4686                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
4687
4688                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4689                }
4690            }
4691        }
4692    }
4693}
4694