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