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