ConnectivityService.java revision 323f29df583e9338e3b2bf90fc8c0785a934a61b
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_STARTED);
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.everConnected && !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                                "; everConnected=" + nai.everConnected);
1958                    }
1959                    LinkProperties oldLp = nai.linkProperties;
1960                    synchronized (nai) {
1961                        nai.linkProperties = (LinkProperties)msg.obj;
1962                    }
1963                    if (nai.everConnected) updateLinkProperties(nai, oldLp);
1964                    break;
1965                }
1966                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1967                    NetworkInfo info = (NetworkInfo) msg.obj;
1968                    updateNetworkInfo(nai, info);
1969                    break;
1970                }
1971                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1972                    Integer score = (Integer) msg.obj;
1973                    if (score != null) updateNetworkScore(nai, score.intValue());
1974                    break;
1975                }
1976                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1977                    try {
1978                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1979                    } catch (Exception e) {
1980                        // Never crash!
1981                        loge("Exception in addVpnUidRanges: " + e);
1982                    }
1983                    break;
1984                }
1985                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1986                    try {
1987                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1988                    } catch (Exception e) {
1989                        // Never crash!
1990                        loge("Exception in removeVpnUidRanges: " + e);
1991                    }
1992                    break;
1993                }
1994                case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1995                    if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
1996                        loge("ERROR: already-connected network explicitly selected.");
1997                    }
1998                    nai.networkMisc.explicitlySelected = true;
1999                    nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
2000                    break;
2001                }
2002                case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2003                    mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2004                    break;
2005                }
2006            }
2007        }
2008
2009        private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2010            switch (msg.what) {
2011                default:
2012                    return false;
2013                case NetworkMonitor.EVENT_NETWORK_TESTED: {
2014                    final NetworkAgentInfo nai;
2015                    synchronized (mNetworkForNetId) {
2016                        nai = mNetworkForNetId.get(msg.arg2);
2017                    }
2018                    if (nai != null) {
2019                        final boolean valid =
2020                                (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2021                        if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2022                                (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
2023                        if (valid != nai.lastValidated) {
2024                            final int oldScore = nai.getCurrentScore();
2025                            nai.lastValidated = valid;
2026                            nai.everValidated |= valid;
2027                            updateCapabilities(nai, nai.networkCapabilities);
2028                            // If score has changed, rebroadcast to NetworkFactories. b/17726566
2029                            if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2030                        }
2031                        updateInetCondition(nai);
2032                        // Let the NetworkAgent know the state of its network
2033                        Bundle redirectUrlBundle = new Bundle();
2034                        redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
2035                        nai.asyncChannel.sendMessage(
2036                                NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2037                                (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2038                                0, redirectUrlBundle);
2039                    }
2040                    break;
2041                }
2042                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
2043                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2044                    if (isLiveNetworkAgent(nai, msg.what)) {
2045                        handleLingerComplete(nai);
2046                    }
2047                    break;
2048                }
2049                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
2050                    final int netId = msg.arg2;
2051                    final boolean visible = (msg.arg1 != 0);
2052                    final NetworkAgentInfo nai;
2053                    synchronized (mNetworkForNetId) {
2054                        nai = mNetworkForNetId.get(netId);
2055                    }
2056                    // If captive portal status has changed, update capabilities.
2057                    if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2058                        nai.lastCaptivePortalDetected = visible;
2059                        nai.everCaptivePortalDetected |= visible;
2060                        updateCapabilities(nai, nai.networkCapabilities);
2061                    }
2062                    if (!visible) {
2063                        setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
2064                    } else {
2065                        if (nai == null) {
2066                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2067                            break;
2068                        }
2069                        setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2070                                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2071                                (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2072                    }
2073                    break;
2074                }
2075            }
2076            return true;
2077        }
2078
2079        @Override
2080        public void handleMessage(Message msg) {
2081            if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2082                maybeHandleNetworkAgentMessage(msg);
2083            }
2084        }
2085    }
2086
2087    private void linger(NetworkAgentInfo nai) {
2088        nai.lingering = true;
2089        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
2090        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2091        notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2092    }
2093
2094    // Cancel any lingering so the linger timeout doesn't teardown a network.
2095    // This should be called when a network begins satisfying a NetworkRequest.
2096    // Note: depending on what state the NetworkMonitor is in (e.g.,
2097    // if it's awaiting captive portal login, or if validation failed), this
2098    // may trigger a re-evaluation of the network.
2099    private void unlinger(NetworkAgentInfo nai) {
2100        nai.networkLingered.clear();
2101        if (!nai.lingering) return;
2102        nai.lingering = false;
2103        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
2104        if (VDBG) log("Canceling linger of " + nai.name());
2105        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2106    }
2107
2108    private void handleAsyncChannelHalfConnect(Message msg) {
2109        AsyncChannel ac = (AsyncChannel) msg.obj;
2110        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2111            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2112                if (VDBG) log("NetworkFactory connected");
2113                // A network factory has connected.  Send it all current NetworkRequests.
2114                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2115                    if (!nri.isRequest()) continue;
2116                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2117                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2118                            (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
2119                }
2120            } else {
2121                loge("Error connecting NetworkFactory");
2122                mNetworkFactoryInfos.remove(msg.obj);
2123            }
2124        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2125            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2126                if (VDBG) log("NetworkAgent connected");
2127                // A network agent has requested a connection.  Establish the connection.
2128                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2129                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2130            } else {
2131                loge("Error connecting NetworkAgent");
2132                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2133                if (nai != null) {
2134                    final boolean wasDefault = isDefaultNetwork(nai);
2135                    synchronized (mNetworkForNetId) {
2136                        mNetworkForNetId.remove(nai.network.netId);
2137                        mNetIdInUse.delete(nai.network.netId);
2138                    }
2139                    // Just in case.
2140                    mLegacyTypeTracker.remove(nai, wasDefault);
2141                }
2142            }
2143        }
2144    }
2145
2146    private void handleAsyncChannelDisconnected(Message msg) {
2147        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2148        if (nai != null) {
2149            if (DBG) {
2150                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2151            }
2152            // A network agent has disconnected.
2153            // TODO - if we move the logic to the network agent (have them disconnect
2154            // because they lost all their requests or because their score isn't good)
2155            // then they would disconnect organically, report their new state and then
2156            // disconnect the channel.
2157            if (nai.networkInfo.isConnected()) {
2158                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2159                        null, null);
2160            }
2161            final boolean wasDefault = isDefaultNetwork(nai);
2162            if (wasDefault) {
2163                mDefaultInetConditionPublished = 0;
2164            }
2165            notifyIfacesChangedForNetworkStats();
2166            // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2167            // by other networks that are already connected. Perhaps that can be done by
2168            // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2169            // of rematchAllNetworksAndRequests
2170            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2171            mKeepaliveTracker.handleStopAllKeepalives(nai,
2172                    ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2173            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2174            mNetworkAgentInfos.remove(msg.replyTo);
2175            updateClat(null, nai.linkProperties, nai);
2176            synchronized (mNetworkForNetId) {
2177                // Remove the NetworkAgent, but don't mark the netId as
2178                // available until we've told netd to delete it below.
2179                mNetworkForNetId.remove(nai.network.netId);
2180            }
2181            // Remove all previously satisfied requests.
2182            for (int i = 0; i < nai.networkRequests.size(); i++) {
2183                NetworkRequest request = nai.networkRequests.valueAt(i);
2184                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2185                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2186                    mNetworkForRequestId.remove(request.requestId);
2187                    sendUpdatedScoreToFactories(request, 0);
2188                }
2189            }
2190            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2191                removeDataActivityTracking(nai);
2192                notifyLockdownVpn(nai);
2193                requestNetworkTransitionWakelock(nai.name());
2194            }
2195            mLegacyTypeTracker.remove(nai, wasDefault);
2196            rematchAllNetworksAndRequests(null, 0);
2197            if (wasDefault && getDefaultNetwork() == null) {
2198                // Log that we lost the default network and there is no replacement.
2199                logDefaultNetworkEvent(null, nai);
2200            }
2201            if (nai.created) {
2202                // Tell netd to clean up the configuration for this network
2203                // (routing rules, DNS, etc).
2204                // This may be slow as it requires a lot of netd shelling out to ip and
2205                // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2206                // after we've rematched networks with requests which should make a potential
2207                // fallback network the default or requested a new network from the
2208                // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2209                // long time.
2210                try {
2211                    mNetd.removeNetwork(nai.network.netId);
2212                } catch (Exception e) {
2213                    loge("Exception removing network: " + e);
2214                }
2215            }
2216            synchronized (mNetworkForNetId) {
2217                mNetIdInUse.delete(nai.network.netId);
2218            }
2219        } else {
2220            NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2221            if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
2222        }
2223    }
2224
2225    // If this method proves to be too slow then we can maintain a separate
2226    // pendingIntent => NetworkRequestInfo map.
2227    // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2228    private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2229        Intent intent = pendingIntent.getIntent();
2230        for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2231            PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2232            if (existingPendingIntent != null &&
2233                    existingPendingIntent.getIntent().filterEquals(intent)) {
2234                return entry.getValue();
2235            }
2236        }
2237        return null;
2238    }
2239
2240    private void handleRegisterNetworkRequestWithIntent(Message msg) {
2241        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2242
2243        NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2244        if (existingRequest != null) { // remove the existing request.
2245            if (DBG) log("Replacing " + existingRequest.request + " with "
2246                    + nri.request + " because their intents matched.");
2247            handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2248        }
2249        handleRegisterNetworkRequest(nri);
2250    }
2251
2252    private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
2253        mNetworkRequests.put(nri.request, nri);
2254        mNetworkRequestInfoLogs.log("REGISTER " + nri);
2255        if (!nri.isRequest()) {
2256            for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2257                if (nri.request.networkCapabilities.hasSignalStrength() &&
2258                        network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2259                    updateSignalStrengthThresholds(network, "REGISTER", nri.request);
2260                }
2261            }
2262        }
2263        rematchAllNetworksAndRequests(null, 0);
2264        if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
2265            sendUpdatedScoreToFactories(nri.request, 0);
2266        }
2267    }
2268
2269    private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2270            int callingUid) {
2271        NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2272        if (nri != null) {
2273            handleReleaseNetworkRequest(nri.request, callingUid);
2274        }
2275    }
2276
2277    // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2278    // This is whether it is satisfying any NetworkRequests or were it to become validated,
2279    // would it have a chance of satisfying any NetworkRequests.
2280    private boolean unneeded(NetworkAgentInfo nai) {
2281        if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
2282        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2283            // If this Network is already the highest scoring Network for a request, or if
2284            // there is hope for it to become one if it validated, then it is needed.
2285            if (nri.isRequest() && nai.satisfies(nri.request) &&
2286                    (nai.networkRequests.get(nri.request.requestId) != null ||
2287                    // Note that this catches two important cases:
2288                    // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2289                    //    is currently satisfying the request.  This is desirable when
2290                    //    cellular ends up validating but WiFi does not.
2291                    // 2. Unvalidated WiFi will not be reaped when validated cellular
2292                    //    is currently satisfying the request.  This is desirable when
2293                    //    WiFi ends up validating and out scoring cellular.
2294                    mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2295                            nai.getCurrentScoreAsValidated())) {
2296                return false;
2297            }
2298        }
2299        return true;
2300    }
2301
2302    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2303        NetworkRequestInfo nri = mNetworkRequests.get(request);
2304        if (nri != null) {
2305            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2306                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2307                return;
2308            }
2309            if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
2310            nri.unlinkDeathRecipient();
2311            mNetworkRequests.remove(request);
2312            synchronized (mUidToNetworkRequestCount) {
2313                int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2314                if (requests < 1) {
2315                    Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2316                            nri.mUid);
2317                } else if (requests == 1) {
2318                    mUidToNetworkRequestCount.removeAt(
2319                            mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2320                } else {
2321                    mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2322                }
2323            }
2324            mNetworkRequestInfoLogs.log("RELEASE " + nri);
2325            if (nri.isRequest()) {
2326                // Find all networks that are satisfying this request and remove the request
2327                // from their request lists.
2328                // TODO - it's my understanding that for a request there is only a single
2329                // network satisfying it, so this loop is wasteful
2330                boolean wasKept = false;
2331                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2332                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2333                        nai.networkRequests.remove(nri.request.requestId);
2334                        if (VDBG) {
2335                            log(" Removing from current network " + nai.name() +
2336                                    ", leaving " + nai.networkRequests.size() +
2337                                    " requests.");
2338                        }
2339                        if (unneeded(nai)) {
2340                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2341                            teardownUnneededNetwork(nai);
2342                        } else {
2343                            // suspect there should only be one pass through here
2344                            // but if any were kept do the check below
2345                            wasKept |= true;
2346                        }
2347                    }
2348                }
2349
2350                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2351                if (nai != null) {
2352                    mNetworkForRequestId.remove(nri.request.requestId);
2353                }
2354                // Maintain the illusion.  When this request arrived, we might have pretended
2355                // that a network connected to serve it, even though the network was already
2356                // connected.  Now that this request has gone away, we might have to pretend
2357                // that the network disconnected.  LegacyTypeTracker will generate that
2358                // phantom disconnect for this type.
2359                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2360                    boolean doRemove = true;
2361                    if (wasKept) {
2362                        // check if any of the remaining requests for this network are for the
2363                        // same legacy type - if so, don't remove the nai
2364                        for (int i = 0; i < nai.networkRequests.size(); i++) {
2365                            NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2366                            if (otherRequest.legacyType == nri.request.legacyType &&
2367                                    isRequest(otherRequest)) {
2368                                if (DBG) log(" still have other legacy request - leaving");
2369                                doRemove = false;
2370                            }
2371                        }
2372                    }
2373
2374                    if (doRemove) {
2375                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2376                    }
2377                }
2378
2379                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2380                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2381                            nri.request);
2382                }
2383            } else {
2384                // listens don't have a singular affectedNetwork.  Check all networks to see
2385                // if this listen request applies and remove it.
2386                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2387                    nai.networkRequests.remove(nri.request.requestId);
2388                    if (nri.request.networkCapabilities.hasSignalStrength() &&
2389                            nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2390                        updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2391                    }
2392                }
2393            }
2394            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2395        }
2396    }
2397
2398    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2399        enforceConnectivityInternalPermission();
2400        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2401                accept ? 1 : 0, always ? 1: 0, network));
2402    }
2403
2404    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2405        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2406                " accept=" + accept + " always=" + always);
2407
2408        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2409        if (nai == null) {
2410            // Nothing to do.
2411            return;
2412        }
2413
2414        if (nai.everValidated) {
2415            // The network validated while the dialog box was up. Take no action.
2416            return;
2417        }
2418
2419        if (!nai.networkMisc.explicitlySelected) {
2420            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2421        }
2422
2423        if (accept != nai.networkMisc.acceptUnvalidated) {
2424            int oldScore = nai.getCurrentScore();
2425            nai.networkMisc.acceptUnvalidated = accept;
2426            rematchAllNetworksAndRequests(nai, oldScore);
2427            sendUpdatedScoreToFactories(nai);
2428        }
2429
2430        if (always) {
2431            nai.asyncChannel.sendMessage(
2432                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2433        }
2434
2435        if (!accept) {
2436            // Tell the NetworkAgent to not automatically reconnect to the network.
2437            nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2438            // Teardown the nework.
2439            teardownUnneededNetwork(nai);
2440        }
2441
2442    }
2443
2444    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2445        if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
2446        mHandler.sendMessageDelayed(
2447                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2448                PROMPT_UNVALIDATED_DELAY_MS);
2449    }
2450
2451    private void handlePromptUnvalidated(Network network) {
2452        if (VDBG) log("handlePromptUnvalidated " + network);
2453        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2454
2455        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2456        // we haven't already been told to switch to it regardless of whether it validated or not.
2457        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2458        if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
2459                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2460            return;
2461        }
2462
2463        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2464        intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
2465        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2466        intent.setClassName("com.android.settings",
2467                "com.android.settings.wifi.WifiNoInternetDialog");
2468
2469        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2470                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2471        setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2472                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
2473    }
2474
2475    private class InternalHandler extends Handler {
2476        public InternalHandler(Looper looper) {
2477            super(looper);
2478        }
2479
2480        @Override
2481        public void handleMessage(Message msg) {
2482            switch (msg.what) {
2483                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2484                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2485                    String causedBy = null;
2486                    synchronized (ConnectivityService.this) {
2487                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2488                                mNetTransitionWakeLock.isHeld()) {
2489                            mNetTransitionWakeLock.release();
2490                            causedBy = mNetTransitionWakeLockCausedBy;
2491                        } else {
2492                            break;
2493                        }
2494                    }
2495                    if (VDBG) {
2496                        if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2497                            log("Failed to find a new network - expiring NetTransition Wakelock");
2498                        } else {
2499                            log("NetTransition Wakelock (" +
2500                                    (causedBy == null ? "unknown" : causedBy) +
2501                                    " cleared because we found a replacement network");
2502                        }
2503                    }
2504                    break;
2505                }
2506                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2507                    handleDeprecatedGlobalHttpProxy();
2508                    break;
2509                }
2510                case EVENT_PROXY_HAS_CHANGED: {
2511                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2512                    break;
2513                }
2514                case EVENT_REGISTER_NETWORK_FACTORY: {
2515                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2516                    break;
2517                }
2518                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2519                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2520                    break;
2521                }
2522                case EVENT_REGISTER_NETWORK_AGENT: {
2523                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2524                    break;
2525                }
2526                case EVENT_REGISTER_NETWORK_REQUEST:
2527                case EVENT_REGISTER_NETWORK_LISTENER: {
2528                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2529                    break;
2530                }
2531                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2532                case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
2533                    handleRegisterNetworkRequestWithIntent(msg);
2534                    break;
2535                }
2536                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2537                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2538                    break;
2539                }
2540                case EVENT_RELEASE_NETWORK_REQUEST: {
2541                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2542                    break;
2543                }
2544                case EVENT_SET_ACCEPT_UNVALIDATED: {
2545                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2546                    break;
2547                }
2548                case EVENT_PROMPT_UNVALIDATED: {
2549                    handlePromptUnvalidated((Network) msg.obj);
2550                    break;
2551                }
2552                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2553                    handleMobileDataAlwaysOn();
2554                    break;
2555                }
2556                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2557                case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2558                    mKeepaliveTracker.handleStartKeepalive(msg);
2559                    break;
2560                }
2561                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2562                case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2563                    NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2564                    int slot = msg.arg1;
2565                    int reason = msg.arg2;
2566                    mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2567                    break;
2568                }
2569                case EVENT_SYSTEM_READY: {
2570                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2571                        nai.networkMonitor.systemReady = true;
2572                    }
2573                    break;
2574                }
2575            }
2576        }
2577    }
2578
2579    // javadoc from interface
2580    public int tether(String iface) {
2581        ConnectivityManager.enforceTetherChangePermission(mContext);
2582        if (isTetheringSupported()) {
2583            final int status = mTethering.tether(iface);
2584            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2585                try {
2586                    mPolicyManager.onTetheringChanged(iface, true);
2587                } catch (RemoteException e) {
2588                }
2589            }
2590            return status;
2591        } else {
2592            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593        }
2594    }
2595
2596    // javadoc from interface
2597    public int untether(String iface) {
2598        ConnectivityManager.enforceTetherChangePermission(mContext);
2599
2600        if (isTetheringSupported()) {
2601            final int status = mTethering.untether(iface);
2602            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2603                try {
2604                    mPolicyManager.onTetheringChanged(iface, false);
2605                } catch (RemoteException e) {
2606                }
2607            }
2608            return status;
2609        } else {
2610            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2611        }
2612    }
2613
2614    // javadoc from interface
2615    public int getLastTetherError(String iface) {
2616        enforceTetherAccessPermission();
2617
2618        if (isTetheringSupported()) {
2619            return mTethering.getLastTetherError(iface);
2620        } else {
2621            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2622        }
2623    }
2624
2625    // TODO - proper iface API for selection by property, inspection, etc
2626    public String[] getTetherableUsbRegexs() {
2627        enforceTetherAccessPermission();
2628        if (isTetheringSupported()) {
2629            return mTethering.getTetherableUsbRegexs();
2630        } else {
2631            return new String[0];
2632        }
2633    }
2634
2635    public String[] getTetherableWifiRegexs() {
2636        enforceTetherAccessPermission();
2637        if (isTetheringSupported()) {
2638            return mTethering.getTetherableWifiRegexs();
2639        } else {
2640            return new String[0];
2641        }
2642    }
2643
2644    public String[] getTetherableBluetoothRegexs() {
2645        enforceTetherAccessPermission();
2646        if (isTetheringSupported()) {
2647            return mTethering.getTetherableBluetoothRegexs();
2648        } else {
2649            return new String[0];
2650        }
2651    }
2652
2653    public int setUsbTethering(boolean enable) {
2654        ConnectivityManager.enforceTetherChangePermission(mContext);
2655        if (isTetheringSupported()) {
2656            return mTethering.setUsbTethering(enable);
2657        } else {
2658            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2659        }
2660    }
2661
2662    // TODO - move iface listing, queries, etc to new module
2663    // javadoc from interface
2664    public String[] getTetherableIfaces() {
2665        enforceTetherAccessPermission();
2666        return mTethering.getTetherableIfaces();
2667    }
2668
2669    public String[] getTetheredIfaces() {
2670        enforceTetherAccessPermission();
2671        return mTethering.getTetheredIfaces();
2672    }
2673
2674    public String[] getTetheringErroredIfaces() {
2675        enforceTetherAccessPermission();
2676        return mTethering.getErroredIfaces();
2677    }
2678
2679    public String[] getTetheredDhcpRanges() {
2680        enforceConnectivityInternalPermission();
2681        return mTethering.getTetheredDhcpRanges();
2682    }
2683
2684    // if ro.tether.denied = true we default to no tethering
2685    // gservices could set the secure setting to 1 though to enable it on a build where it
2686    // had previously been turned off.
2687    @Override
2688    public boolean isTetheringSupported() {
2689        enforceTetherAccessPermission();
2690        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2691        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2692                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2693                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2694        return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2695                ((mTethering.getTetherableUsbRegexs().length != 0 ||
2696                mTethering.getTetherableWifiRegexs().length != 0 ||
2697                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2698                mTethering.getUpstreamIfaceTypes().length != 0);
2699    }
2700
2701    @Override
2702    public void startTethering(int type, ResultReceiver receiver,
2703            boolean showProvisioningUi) {
2704        ConnectivityManager.enforceTetherChangePermission(mContext);
2705        if (!isTetheringSupported()) {
2706            receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2707            return;
2708        }
2709        mTethering.startTethering(type, receiver, showProvisioningUi);
2710    }
2711
2712    @Override
2713    public void stopTethering(int type) {
2714        ConnectivityManager.enforceTetherChangePermission(mContext);
2715        mTethering.stopTethering(type);
2716    }
2717
2718    // Called when we lose the default network and have no replacement yet.
2719    // This will automatically be cleared after X seconds or a new default network
2720    // becomes CONNECTED, whichever happens first.  The timer is started by the
2721    // first caller and not restarted by subsequent callers.
2722    private void requestNetworkTransitionWakelock(String forWhom) {
2723        int serialNum = 0;
2724        synchronized (this) {
2725            if (mNetTransitionWakeLock.isHeld()) return;
2726            serialNum = ++mNetTransitionWakeLockSerialNumber;
2727            mNetTransitionWakeLock.acquire();
2728            mNetTransitionWakeLockCausedBy = forWhom;
2729        }
2730        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2731                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2732                mNetTransitionWakeLockTimeout);
2733        return;
2734    }
2735
2736    // 100 percent is full good, 0 is full bad.
2737    public void reportInetCondition(int networkType, int percentage) {
2738        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2739        if (nai == null) return;
2740        reportNetworkConnectivity(nai.network, percentage > 50);
2741    }
2742
2743    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2744        enforceAccessPermission();
2745        enforceInternetPermission();
2746
2747        NetworkAgentInfo nai;
2748        if (network == null) {
2749            nai = getDefaultNetwork();
2750        } else {
2751            nai = getNetworkAgentInfoForNetwork(network);
2752        }
2753        if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2754            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2755            return;
2756        }
2757        // Revalidate if the app report does not match our current validated state.
2758        if (hasConnectivity == nai.lastValidated) return;
2759        final int uid = Binder.getCallingUid();
2760        if (DBG) {
2761            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2762                    ") by " + uid);
2763        }
2764        synchronized (nai) {
2765            // Validating a network that has not yet connected could result in a call to
2766            // rematchNetworkAndRequests() which is not meant to work on such networks.
2767            if (!nai.everConnected) return;
2768
2769            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
2770
2771            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2772        }
2773    }
2774
2775    private ProxyInfo getDefaultProxy() {
2776        // this information is already available as a world read/writable jvm property
2777        // so this API change wouldn't have a benifit.  It also breaks the passing
2778        // of proxy info to all the JVMs.
2779        // enforceAccessPermission();
2780        synchronized (mProxyLock) {
2781            ProxyInfo ret = mGlobalProxy;
2782            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2783            return ret;
2784        }
2785    }
2786
2787    public ProxyInfo getProxyForNetwork(Network network) {
2788        if (network == null) return getDefaultProxy();
2789        final ProxyInfo globalProxy = getGlobalProxy();
2790        if (globalProxy != null) return globalProxy;
2791        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2792        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2793        // caller may not have.
2794        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2795        if (nai == null) return null;
2796        synchronized (nai) {
2797            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2798            if (proxyInfo == null) return null;
2799            return new ProxyInfo(proxyInfo);
2800        }
2801    }
2802
2803    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2804    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2805    // proxy is null then there is no proxy in place).
2806    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2807        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2808                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2809            proxy = null;
2810        }
2811        return proxy;
2812    }
2813
2814    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2815    // better for determining if a new proxy broadcast is necessary:
2816    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2817    //    avoid unnecessary broadcasts.
2818    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2819    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2820    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2821    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2822    //    all set.
2823    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2824        a = canonicalizeProxyInfo(a);
2825        b = canonicalizeProxyInfo(b);
2826        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2827        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2828        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2829    }
2830
2831    public void setGlobalProxy(ProxyInfo proxyProperties) {
2832        enforceConnectivityInternalPermission();
2833
2834        synchronized (mProxyLock) {
2835            if (proxyProperties == mGlobalProxy) return;
2836            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2837            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2838
2839            String host = "";
2840            int port = 0;
2841            String exclList = "";
2842            String pacFileUrl = "";
2843            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2844                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2845                if (!proxyProperties.isValid()) {
2846                    if (DBG)
2847                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2848                    return;
2849                }
2850                mGlobalProxy = new ProxyInfo(proxyProperties);
2851                host = mGlobalProxy.getHost();
2852                port = mGlobalProxy.getPort();
2853                exclList = mGlobalProxy.getExclusionListAsString();
2854                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2855                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2856                }
2857            } else {
2858                mGlobalProxy = null;
2859            }
2860            ContentResolver res = mContext.getContentResolver();
2861            final long token = Binder.clearCallingIdentity();
2862            try {
2863                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2864                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2865                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2866                        exclList);
2867                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2868            } finally {
2869                Binder.restoreCallingIdentity(token);
2870            }
2871
2872            if (mGlobalProxy == null) {
2873                proxyProperties = mDefaultProxy;
2874            }
2875            sendProxyBroadcast(proxyProperties);
2876        }
2877    }
2878
2879    private void loadGlobalProxy() {
2880        ContentResolver res = mContext.getContentResolver();
2881        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2882        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2883        String exclList = Settings.Global.getString(res,
2884                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2885        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2886        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2887            ProxyInfo proxyProperties;
2888            if (!TextUtils.isEmpty(pacFileUrl)) {
2889                proxyProperties = new ProxyInfo(pacFileUrl);
2890            } else {
2891                proxyProperties = new ProxyInfo(host, port, exclList);
2892            }
2893            if (!proxyProperties.isValid()) {
2894                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2895                return;
2896            }
2897
2898            synchronized (mProxyLock) {
2899                mGlobalProxy = proxyProperties;
2900            }
2901        }
2902    }
2903
2904    public ProxyInfo getGlobalProxy() {
2905        // this information is already available as a world read/writable jvm property
2906        // so this API change wouldn't have a benifit.  It also breaks the passing
2907        // of proxy info to all the JVMs.
2908        // enforceAccessPermission();
2909        synchronized (mProxyLock) {
2910            return mGlobalProxy;
2911        }
2912    }
2913
2914    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2915        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2916                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2917            proxy = null;
2918        }
2919        synchronized (mProxyLock) {
2920            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2921            if (mDefaultProxy == proxy) return; // catches repeated nulls
2922            if (proxy != null &&  !proxy.isValid()) {
2923                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2924                return;
2925            }
2926
2927            // This call could be coming from the PacManager, containing the port of the local
2928            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2929            // global (to get the correct local port), and send a broadcast.
2930            // TODO: Switch PacManager to have its own message to send back rather than
2931            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2932            if ((mGlobalProxy != null) && (proxy != null)
2933                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2934                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2935                mGlobalProxy = proxy;
2936                sendProxyBroadcast(mGlobalProxy);
2937                return;
2938            }
2939            mDefaultProxy = proxy;
2940
2941            if (mGlobalProxy != null) return;
2942            if (!mDefaultProxyDisabled) {
2943                sendProxyBroadcast(proxy);
2944            }
2945        }
2946    }
2947
2948    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2949    // This method gets called when any network changes proxy, but the broadcast only ever contains
2950    // the default proxy (even if it hasn't changed).
2951    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2952    // world where an app might be bound to a non-default network.
2953    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2954        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2955        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2956
2957        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2958            sendProxyBroadcast(getDefaultProxy());
2959        }
2960    }
2961
2962    private void handleDeprecatedGlobalHttpProxy() {
2963        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2964                Settings.Global.HTTP_PROXY);
2965        if (!TextUtils.isEmpty(proxy)) {
2966            String data[] = proxy.split(":");
2967            if (data.length == 0) {
2968                return;
2969            }
2970
2971            String proxyHost =  data[0];
2972            int proxyPort = 8080;
2973            if (data.length > 1) {
2974                try {
2975                    proxyPort = Integer.parseInt(data[1]);
2976                } catch (NumberFormatException e) {
2977                    return;
2978                }
2979            }
2980            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2981            setGlobalProxy(p);
2982        }
2983    }
2984
2985    private void sendProxyBroadcast(ProxyInfo proxy) {
2986        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2987        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2988        if (DBG) log("sending Proxy Broadcast for " + proxy);
2989        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2990        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2991            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2992        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2993        final long ident = Binder.clearCallingIdentity();
2994        try {
2995            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2996        } finally {
2997            Binder.restoreCallingIdentity(ident);
2998        }
2999    }
3000
3001    private static class SettingsObserver extends ContentObserver {
3002        final private HashMap<Uri, Integer> mUriEventMap;
3003        final private Context mContext;
3004        final private Handler mHandler;
3005
3006        SettingsObserver(Context context, Handler handler) {
3007            super(null);
3008            mUriEventMap = new HashMap<Uri, Integer>();
3009            mContext = context;
3010            mHandler = handler;
3011        }
3012
3013        void observe(Uri uri, int what) {
3014            mUriEventMap.put(uri, what);
3015            final ContentResolver resolver = mContext.getContentResolver();
3016            resolver.registerContentObserver(uri, false, this);
3017        }
3018
3019        @Override
3020        public void onChange(boolean selfChange) {
3021            Slog.wtf(TAG, "Should never be reached.");
3022        }
3023
3024        @Override
3025        public void onChange(boolean selfChange, Uri uri) {
3026            final Integer what = mUriEventMap.get(uri);
3027            if (what != null) {
3028                mHandler.obtainMessage(what.intValue()).sendToTarget();
3029            } else {
3030                loge("No matching event to send for URI=" + uri);
3031            }
3032        }
3033    }
3034
3035    private static void log(String s) {
3036        Slog.d(TAG, s);
3037    }
3038
3039    private static void loge(String s) {
3040        Slog.e(TAG, s);
3041    }
3042
3043    private static <T> T checkNotNull(T value, String message) {
3044        if (value == null) {
3045            throw new NullPointerException(message);
3046        }
3047        return value;
3048    }
3049
3050    /**
3051     * Prepare for a VPN application.
3052     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3053     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3054     *
3055     * @param oldPackage Package name of the application which currently controls VPN, which will
3056     *                   be replaced. If there is no such application, this should should either be
3057     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3058     * @param newPackage Package name of the application which should gain control of VPN, or
3059     *                   {@code null} to disable.
3060     * @param userId User for whom to prepare the new VPN.
3061     *
3062     * @hide
3063     */
3064    @Override
3065    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3066            int userId) {
3067        enforceCrossUserPermission(userId);
3068        throwIfLockdownEnabled();
3069
3070        synchronized(mVpns) {
3071            Vpn vpn = mVpns.get(userId);
3072            if (vpn != null) {
3073                return vpn.prepare(oldPackage, newPackage);
3074            } else {
3075                return false;
3076            }
3077        }
3078    }
3079
3080    /**
3081     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3082     * This method is used by system-privileged apps.
3083     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3084     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3085     *
3086     * @param packageName The package for which authorization state should change.
3087     * @param userId User for whom {@code packageName} is installed.
3088     * @param authorized {@code true} if this app should be able to start a VPN connection without
3089     *                   explicit user approval, {@code false} if not.
3090     *
3091     * @hide
3092     */
3093    @Override
3094    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3095        enforceCrossUserPermission(userId);
3096
3097        synchronized(mVpns) {
3098            Vpn vpn = mVpns.get(userId);
3099            if (vpn != null) {
3100                vpn.setPackageAuthorization(packageName, authorized);
3101            }
3102        }
3103    }
3104
3105    /**
3106     * Configure a TUN interface and return its file descriptor. Parameters
3107     * are encoded and opaque to this class. This method is used by VpnBuilder
3108     * and not available in ConnectivityManager. Permissions are checked in
3109     * Vpn class.
3110     * @hide
3111     */
3112    @Override
3113    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3114        throwIfLockdownEnabled();
3115        int user = UserHandle.getUserId(Binder.getCallingUid());
3116        synchronized(mVpns) {
3117            return mVpns.get(user).establish(config);
3118        }
3119    }
3120
3121    /**
3122     * Start legacy VPN, controlling native daemons as needed. Creates a
3123     * secondary thread to perform connection work, returning quickly.
3124     */
3125    @Override
3126    public void startLegacyVpn(VpnProfile profile) {
3127        throwIfLockdownEnabled();
3128        final LinkProperties egress = getActiveLinkProperties();
3129        if (egress == null) {
3130            throw new IllegalStateException("Missing active network connection");
3131        }
3132        int user = UserHandle.getUserId(Binder.getCallingUid());
3133        synchronized(mVpns) {
3134            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3135        }
3136    }
3137
3138    /**
3139     * Return the information of the ongoing legacy VPN. This method is used
3140     * by VpnSettings and not available in ConnectivityManager. Permissions
3141     * are checked in Vpn class.
3142     */
3143    @Override
3144    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3145        enforceCrossUserPermission(userId);
3146        if (mLockdownEnabled) {
3147            return null;
3148        }
3149
3150        synchronized(mVpns) {
3151            return mVpns.get(userId).getLegacyVpnInfo();
3152        }
3153    }
3154
3155    /**
3156     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3157     * and not available in ConnectivityManager.
3158     */
3159    @Override
3160    public VpnInfo[] getAllVpnInfo() {
3161        enforceConnectivityInternalPermission();
3162        if (mLockdownEnabled) {
3163            return new VpnInfo[0];
3164        }
3165
3166        synchronized(mVpns) {
3167            List<VpnInfo> infoList = new ArrayList<>();
3168            for (int i = 0; i < mVpns.size(); i++) {
3169                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3170                if (info != null) {
3171                    infoList.add(info);
3172                }
3173            }
3174            return infoList.toArray(new VpnInfo[infoList.size()]);
3175        }
3176    }
3177
3178    /**
3179     * @return VPN information for accounting, or null if we can't retrieve all required
3180     *         information, e.g primary underlying iface.
3181     */
3182    @Nullable
3183    private VpnInfo createVpnInfo(Vpn vpn) {
3184        VpnInfo info = vpn.getVpnInfo();
3185        if (info == null) {
3186            return null;
3187        }
3188        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3189        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3190        // the underlyingNetworks list.
3191        if (underlyingNetworks == null) {
3192            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3193            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3194                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3195            }
3196        } else if (underlyingNetworks.length > 0) {
3197            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3198            if (linkProperties != null) {
3199                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3200            }
3201        }
3202        return info.primaryUnderlyingIface == null ? null : info;
3203    }
3204
3205    /**
3206     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3207     * VpnDialogs and not available in ConnectivityManager.
3208     * Permissions are checked in Vpn class.
3209     * @hide
3210     */
3211    @Override
3212    public VpnConfig getVpnConfig(int userId) {
3213        enforceCrossUserPermission(userId);
3214        synchronized(mVpns) {
3215            Vpn vpn = mVpns.get(userId);
3216            if (vpn != null) {
3217                return vpn.getVpnConfig();
3218            } else {
3219                return null;
3220            }
3221        }
3222    }
3223
3224    @Override
3225    public boolean updateLockdownVpn() {
3226        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3227            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3228            return false;
3229        }
3230
3231        // Tear down existing lockdown if profile was removed
3232        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3233        if (mLockdownEnabled) {
3234            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3235            final VpnProfile profile = VpnProfile.decode(
3236                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3237            if (profile == null) {
3238                Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3239                setLockdownTracker(null);
3240                return true;
3241            }
3242            int user = UserHandle.getUserId(Binder.getCallingUid());
3243            synchronized(mVpns) {
3244                Vpn vpn = mVpns.get(user);
3245                if (vpn == null) {
3246                    Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3247                    return false;
3248                }
3249                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
3250            }
3251        } else {
3252            setLockdownTracker(null);
3253        }
3254
3255        return true;
3256    }
3257
3258    /**
3259     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3260     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3261     */
3262    private void setLockdownTracker(LockdownVpnTracker tracker) {
3263        // Shutdown any existing tracker
3264        final LockdownVpnTracker existing = mLockdownTracker;
3265        mLockdownTracker = null;
3266        if (existing != null) {
3267            existing.shutdown();
3268        }
3269
3270        try {
3271            if (tracker != null) {
3272                mNetd.setFirewallEnabled(true);
3273                mNetd.setFirewallInterfaceRule("lo", true);
3274                mLockdownTracker = tracker;
3275                mLockdownTracker.init();
3276            } else {
3277                mNetd.setFirewallEnabled(false);
3278            }
3279        } catch (RemoteException e) {
3280            // ignored; NMS lives inside system_server
3281        }
3282    }
3283
3284    private void throwIfLockdownEnabled() {
3285        if (mLockdownEnabled) {
3286            throw new IllegalStateException("Unavailable in lockdown mode");
3287        }
3288    }
3289
3290    /**
3291     * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3292     *
3293     * @return {@code false} in case of errors; {@code true} otherwise.
3294     */
3295    private boolean updateAlwaysOnVpn(int user) {
3296        final String lockdownPackage = getAlwaysOnVpnPackage(user);
3297        if (lockdownPackage == null) {
3298            return true;
3299        }
3300
3301        // Create an intent to start the VPN service declared in the app's manifest.
3302        Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3303        serviceIntent.setPackage(lockdownPackage);
3304
3305        try {
3306            return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3307        } catch (RuntimeException e) {
3308            return false;
3309        }
3310    }
3311
3312    @Override
3313    public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3314        enforceConnectivityInternalPermission();
3315        enforceCrossUserPermission(userId);
3316
3317        // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3318        if (LockdownVpnTracker.isEnabled()) {
3319            return false;
3320        }
3321
3322        // If the current VPN package is the same as the new one, this is a no-op
3323        final String oldPackage = getAlwaysOnVpnPackage(userId);
3324        if (TextUtils.equals(oldPackage, packageName)) {
3325            return true;
3326        }
3327
3328        synchronized (mVpns) {
3329            Vpn vpn = mVpns.get(userId);
3330            if (vpn == null) {
3331                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3332                return false;
3333            }
3334            if (!vpn.setAlwaysOnPackage(packageName)) {
3335                return false;
3336            }
3337            if (!updateAlwaysOnVpn(userId)) {
3338                vpn.setAlwaysOnPackage(null);
3339                return false;
3340            }
3341        }
3342        return true;
3343    }
3344
3345    @Override
3346    public String getAlwaysOnVpnPackage(int userId) {
3347        enforceConnectivityInternalPermission();
3348        enforceCrossUserPermission(userId);
3349
3350        synchronized (mVpns) {
3351            Vpn vpn = mVpns.get(userId);
3352            if (vpn == null) {
3353                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3354                return null;
3355            }
3356            return vpn.getAlwaysOnPackage();
3357        }
3358    }
3359
3360    @Override
3361    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3362        // TODO: Remove?  Any reason to trigger a provisioning check?
3363        return -1;
3364    }
3365
3366    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3367    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3368
3369    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3370        Intent intent = new Intent(action);
3371        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3372        // Concatenate the range of types onto the range of NetIDs.
3373        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3374        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3375                networkType, null, pendingIntent, false);
3376    }
3377
3378    /**
3379     * Show or hide network provisioning notifications.
3380     *
3381     * We use notifications for two purposes: to notify that a network requires sign in
3382     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3383     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3384     * particular network we can display the notification type that was most recently requested.
3385     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3386     * might first display NO_INTERNET, and then when the captive portal check completes, display
3387     * SIGN_IN.
3388     *
3389     * @param id an identifier that uniquely identifies this notification.  This must match
3390     *         between show and hide calls.  We use the NetID value but for legacy callers
3391     *         we concatenate the range of types with the range of NetIDs.
3392     */
3393    private void setProvNotificationVisibleIntent(boolean visible, int id,
3394            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3395            boolean highPriority) {
3396        if (VDBG || (DBG && visible)) {
3397            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3398                    + " networkType=" + getNetworkTypeName(networkType)
3399                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3400        }
3401
3402        Resources r = Resources.getSystem();
3403        NotificationManager notificationManager = (NotificationManager) mContext
3404            .getSystemService(Context.NOTIFICATION_SERVICE);
3405
3406        if (visible) {
3407            CharSequence title;
3408            CharSequence details;
3409            int icon;
3410            if (notifyType == NotificationType.NO_INTERNET &&
3411                    networkType == ConnectivityManager.TYPE_WIFI) {
3412                title = r.getString(R.string.wifi_no_internet, 0);
3413                details = r.getString(R.string.wifi_no_internet_detailed);
3414                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3415            } else if (notifyType == NotificationType.SIGN_IN) {
3416                switch (networkType) {
3417                    case ConnectivityManager.TYPE_WIFI:
3418                        title = r.getString(R.string.wifi_available_sign_in, 0);
3419                        details = r.getString(R.string.network_available_sign_in_detailed,
3420                                extraInfo);
3421                        icon = R.drawable.stat_notify_wifi_in_range;
3422                        break;
3423                    case ConnectivityManager.TYPE_MOBILE:
3424                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3425                        title = r.getString(R.string.network_available_sign_in, 0);
3426                        // TODO: Change this to pull from NetworkInfo once a printable
3427                        // name has been added to it
3428                        details = mTelephonyManager.getNetworkOperatorName();
3429                        icon = R.drawable.stat_notify_rssi_in_range;
3430                        break;
3431                    default:
3432                        title = r.getString(R.string.network_available_sign_in, 0);
3433                        details = r.getString(R.string.network_available_sign_in_detailed,
3434                                extraInfo);
3435                        icon = R.drawable.stat_notify_rssi_in_range;
3436                        break;
3437                }
3438            } else {
3439                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3440                        + getNetworkTypeName(networkType));
3441                return;
3442            }
3443
3444            Notification notification = new Notification.Builder(mContext)
3445                    .setWhen(0)
3446                    .setSmallIcon(icon)
3447                    .setAutoCancel(true)
3448                    .setTicker(title)
3449                    .setColor(mContext.getColor(
3450                            com.android.internal.R.color.system_notification_accent_color))
3451                    .setContentTitle(title)
3452                    .setContentText(details)
3453                    .setContentIntent(intent)
3454                    .setLocalOnly(true)
3455                    .setPriority(highPriority ?
3456                            Notification.PRIORITY_HIGH :
3457                            Notification.PRIORITY_DEFAULT)
3458                    .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
3459                    .setOnlyAlertOnce(true)
3460                    .build();
3461
3462            try {
3463                notificationManager.notify(NOTIFICATION_ID, id, notification);
3464            } catch (NullPointerException npe) {
3465                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3466                npe.printStackTrace();
3467            }
3468        } else {
3469            try {
3470                notificationManager.cancel(NOTIFICATION_ID, id);
3471            } catch (NullPointerException npe) {
3472                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3473                npe.printStackTrace();
3474            }
3475        }
3476    }
3477
3478    /** Location to an updatable file listing carrier provisioning urls.
3479     *  An example:
3480     *
3481     * <?xml version="1.0" encoding="utf-8"?>
3482     *  <provisioningUrls>
3483     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3484     *  </provisioningUrls>
3485     */
3486    private static final String PROVISIONING_URL_PATH =
3487            "/data/misc/radio/provisioning_urls.xml";
3488    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3489
3490    /** XML tag for root element. */
3491    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3492    /** XML tag for individual url */
3493    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3494    /** XML attribute for mcc */
3495    private static final String ATTR_MCC = "mcc";
3496    /** XML attribute for mnc */
3497    private static final String ATTR_MNC = "mnc";
3498
3499    private String getProvisioningUrlBaseFromFile() {
3500        FileReader fileReader = null;
3501        XmlPullParser parser = null;
3502        Configuration config = mContext.getResources().getConfiguration();
3503
3504        try {
3505            fileReader = new FileReader(mProvisioningUrlFile);
3506            parser = Xml.newPullParser();
3507            parser.setInput(fileReader);
3508            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3509
3510            while (true) {
3511                XmlUtils.nextElement(parser);
3512
3513                String element = parser.getName();
3514                if (element == null) break;
3515
3516                if (element.equals(TAG_PROVISIONING_URL)) {
3517                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3518                    try {
3519                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3520                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3521                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3522                                parser.next();
3523                                if (parser.getEventType() == XmlPullParser.TEXT) {
3524                                    return parser.getText();
3525                                }
3526                            }
3527                        }
3528                    } catch (NumberFormatException e) {
3529                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3530                    }
3531                }
3532            }
3533            return null;
3534        } catch (FileNotFoundException e) {
3535            loge("Carrier Provisioning Urls file not found");
3536        } catch (XmlPullParserException e) {
3537            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3538        } catch (IOException e) {
3539            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3540        } finally {
3541            if (fileReader != null) {
3542                try {
3543                    fileReader.close();
3544                } catch (IOException e) {}
3545            }
3546        }
3547        return null;
3548    }
3549
3550    @Override
3551    public String getMobileProvisioningUrl() {
3552        enforceConnectivityInternalPermission();
3553        String url = getProvisioningUrlBaseFromFile();
3554        if (TextUtils.isEmpty(url)) {
3555            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3556            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3557        } else {
3558            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3559        }
3560        // populate the iccid, imei and phone number in the provisioning url.
3561        if (!TextUtils.isEmpty(url)) {
3562            String phoneNumber = mTelephonyManager.getLine1Number();
3563            if (TextUtils.isEmpty(phoneNumber)) {
3564                phoneNumber = "0000000000";
3565            }
3566            url = String.format(url,
3567                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3568                    mTelephonyManager.getDeviceId() /* IMEI */,
3569                    phoneNumber /* Phone numer */);
3570        }
3571
3572        return url;
3573    }
3574
3575    @Override
3576    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3577            String action) {
3578        enforceConnectivityInternalPermission();
3579        final long ident = Binder.clearCallingIdentity();
3580        try {
3581            setProvNotificationVisible(visible, networkType, action);
3582        } finally {
3583            Binder.restoreCallingIdentity(ident);
3584        }
3585    }
3586
3587    @Override
3588    public void setAirplaneMode(boolean enable) {
3589        enforceConnectivityInternalPermission();
3590        final long ident = Binder.clearCallingIdentity();
3591        try {
3592            final ContentResolver cr = mContext.getContentResolver();
3593            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3594            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3595            intent.putExtra("state", enable);
3596            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3597        } finally {
3598            Binder.restoreCallingIdentity(ident);
3599        }
3600    }
3601
3602    private void onUserStart(int userId) {
3603        synchronized(mVpns) {
3604            Vpn userVpn = mVpns.get(userId);
3605            if (userVpn != null) {
3606                loge("Starting user already has a VPN");
3607                return;
3608            }
3609            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3610            mVpns.put(userId, userVpn);
3611        }
3612        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3613            updateLockdownVpn();
3614        } else {
3615            updateAlwaysOnVpn(userId);
3616        }
3617    }
3618
3619    private void onUserStop(int userId) {
3620        synchronized(mVpns) {
3621            Vpn userVpn = mVpns.get(userId);
3622            if (userVpn == null) {
3623                loge("Stopped user has no VPN");
3624                return;
3625            }
3626            mVpns.delete(userId);
3627        }
3628    }
3629
3630    private void onUserAdded(int userId) {
3631        synchronized(mVpns) {
3632            final int vpnsSize = mVpns.size();
3633            for (int i = 0; i < vpnsSize; i++) {
3634                Vpn vpn = mVpns.valueAt(i);
3635                vpn.onUserAdded(userId);
3636            }
3637        }
3638    }
3639
3640    private void onUserRemoved(int userId) {
3641        synchronized(mVpns) {
3642            final int vpnsSize = mVpns.size();
3643            for (int i = 0; i < vpnsSize; i++) {
3644                Vpn vpn = mVpns.valueAt(i);
3645                vpn.onUserRemoved(userId);
3646            }
3647        }
3648    }
3649
3650    private void onUserUnlocked(int userId) {
3651        // User present may be sent because of an unlock, which might mean an unlocked keystore.
3652        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3653            updateLockdownVpn();
3654        } else {
3655            updateAlwaysOnVpn(userId);
3656        }
3657    }
3658
3659    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3660        @Override
3661        public void onReceive(Context context, Intent intent) {
3662            final String action = intent.getAction();
3663            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3664            if (userId == UserHandle.USER_NULL) return;
3665
3666            if (Intent.ACTION_USER_STARTED.equals(action)) {
3667                onUserStart(userId);
3668            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3669                onUserStop(userId);
3670            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3671                onUserAdded(userId);
3672            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3673                onUserRemoved(userId);
3674            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3675                onUserUnlocked(userId);
3676            }
3677        }
3678    };
3679
3680    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3681            new HashMap<Messenger, NetworkFactoryInfo>();
3682    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3683            new HashMap<NetworkRequest, NetworkRequestInfo>();
3684
3685    private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3686    // Map from UID to number of NetworkRequests that UID has filed.
3687    @GuardedBy("mUidToNetworkRequestCount")
3688    private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3689
3690    private static class NetworkFactoryInfo {
3691        public final String name;
3692        public final Messenger messenger;
3693        public final AsyncChannel asyncChannel;
3694
3695        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3696            this.name = name;
3697            this.messenger = messenger;
3698            this.asyncChannel = asyncChannel;
3699        }
3700    }
3701
3702    /**
3703     * A NetworkRequest as registered by an application can be one of three
3704     * types:
3705     *
3706     *     - "listen", for which the framework will issue callbacks about any
3707     *       and all networks that match the specified NetworkCapabilities,
3708     *
3709     *     - "request", capable of causing a specific network to be created
3710     *       first (e.g. a telephony DUN request), the framework will issue
3711     *       callbacks about the single, highest scoring current network
3712     *       (if any) that matches the specified NetworkCapabilities, or
3713     *
3714     *     - "track the default network", a hybrid of the two designed such
3715     *       that the framework will issue callbacks for the single, highest
3716     *       scoring current network (if any) that matches the capabilities of
3717     *       the default Internet request (mDefaultRequest), but which cannot
3718     *       cause the framework to either create or retain the existence of
3719     *       any specific network.
3720     *
3721     */
3722    private static enum NetworkRequestType {
3723        LISTEN,
3724        TRACK_DEFAULT,
3725        REQUEST
3726    };
3727
3728    /**
3729     * Tracks info about the requester.
3730     * Also used to notice when the calling process dies so we can self-expire
3731     */
3732    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3733        final NetworkRequest request;
3734        final PendingIntent mPendingIntent;
3735        boolean mPendingIntentSent;
3736        private final IBinder mBinder;
3737        final int mPid;
3738        final int mUid;
3739        final Messenger messenger;
3740        private final NetworkRequestType mType;
3741
3742        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
3743            request = r;
3744            mPendingIntent = pi;
3745            messenger = null;
3746            mBinder = null;
3747            mPid = getCallingPid();
3748            mUid = getCallingUid();
3749            mType = type;
3750            enforceRequestCountLimit();
3751        }
3752
3753        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
3754            super();
3755            messenger = m;
3756            request = r;
3757            mBinder = binder;
3758            mPid = getCallingPid();
3759            mUid = getCallingUid();
3760            mType = type;
3761            mPendingIntent = null;
3762            enforceRequestCountLimit();
3763
3764            try {
3765                mBinder.linkToDeath(this, 0);
3766            } catch (RemoteException e) {
3767                binderDied();
3768            }
3769        }
3770
3771        private void enforceRequestCountLimit() {
3772            synchronized (mUidToNetworkRequestCount) {
3773                int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3774                if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3775                    throw new IllegalArgumentException("Too many NetworkRequests filed");
3776                }
3777                mUidToNetworkRequestCount.put(mUid, networkRequests);
3778            }
3779        }
3780
3781        private String typeString() {
3782            switch (mType) {
3783                case LISTEN: return "Listen";
3784                case REQUEST: return "Request";
3785                case TRACK_DEFAULT: return "Track default";
3786                default:
3787                    return "unknown type";
3788            }
3789        }
3790
3791        void unlinkDeathRecipient() {
3792            if (mBinder != null) {
3793                mBinder.unlinkToDeath(this, 0);
3794            }
3795        }
3796
3797        public void binderDied() {
3798            log("ConnectivityService NetworkRequestInfo binderDied(" +
3799                    request + ", " + mBinder + ")");
3800            releaseNetworkRequest(request);
3801        }
3802
3803        /**
3804         * Returns true iff. the contained NetworkRequest is one that:
3805         *
3806         *     - should be associated with at most one satisfying network
3807         *       at a time;
3808         *
3809         *     - should cause a network to be kept up if it is the only network
3810         *       which can satisfy the NetworkReqeust.
3811         *
3812         * For full detail of how isRequest() is used for pairing Networks with
3813         * NetworkRequests read rematchNetworkAndRequests().
3814         *
3815         * TODO: Rename to something more properly descriptive.
3816         */
3817        public boolean isRequest() {
3818            return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3819                   (mType == NetworkRequestType.REQUEST);
3820        }
3821
3822        public String toString() {
3823            return typeString() +
3824                    " from uid/pid:" + mUid + "/" + mPid +
3825                    " for " + request +
3826                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3827        }
3828    }
3829
3830    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3831        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3832        if (badCapability != null) {
3833            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3834        }
3835    }
3836
3837    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3838        final SortedSet<Integer> thresholds = new TreeSet();
3839        synchronized (nai) {
3840            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3841                if (nri.request.networkCapabilities.hasSignalStrength() &&
3842                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3843                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3844                }
3845            }
3846        }
3847        return new ArrayList<Integer>(thresholds);
3848    }
3849
3850    private void updateSignalStrengthThresholds(
3851            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3852        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3853        Bundle thresholds = new Bundle();
3854        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3855
3856        if (VDBG || (DBG && !"CONNECT".equals(reason))) {
3857            String detail;
3858            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3859                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3860            } else {
3861                detail = reason;
3862            }
3863            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3864                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3865        }
3866
3867        nai.asyncChannel.sendMessage(
3868                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3869                0, 0, thresholds);
3870    }
3871
3872    @Override
3873    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3874            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3875        final NetworkRequestType type = (networkCapabilities == null)
3876                ? NetworkRequestType.TRACK_DEFAULT
3877                : NetworkRequestType.REQUEST;
3878        // If the requested networkCapabilities is null, take them instead from
3879        // the default network request. This allows callers to keep track of
3880        // the system default network.
3881        if (type == NetworkRequestType.TRACK_DEFAULT) {
3882            networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3883            enforceAccessPermission();
3884        } else {
3885            networkCapabilities = new NetworkCapabilities(networkCapabilities);
3886            enforceNetworkRequestPermissions(networkCapabilities);
3887        }
3888        enforceMeteredApnPolicy(networkCapabilities);
3889        ensureRequestableCapabilities(networkCapabilities);
3890
3891        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3892            throw new IllegalArgumentException("Bad timeout specified");
3893        }
3894
3895        if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3896                .equals(networkCapabilities.getNetworkSpecifier())) {
3897            throw new IllegalArgumentException("Invalid network specifier - must not be '"
3898                    + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3899        }
3900
3901        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3902                nextNetworkRequestId());
3903        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
3904        if (DBG) log("requestNetwork for " + nri);
3905
3906        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3907        if (timeoutMs > 0) {
3908            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3909                    nri), timeoutMs);
3910        }
3911        return networkRequest;
3912    }
3913
3914    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3915        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3916            enforceConnectivityInternalPermission();
3917        } else {
3918            enforceChangePermission();
3919        }
3920    }
3921
3922    @Override
3923    public boolean requestBandwidthUpdate(Network network) {
3924        enforceAccessPermission();
3925        NetworkAgentInfo nai = null;
3926        if (network == null) {
3927            return false;
3928        }
3929        synchronized (mNetworkForNetId) {
3930            nai = mNetworkForNetId.get(network.netId);
3931        }
3932        if (nai != null) {
3933            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3934            return true;
3935        }
3936        return false;
3937    }
3938
3939
3940    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3941        // if UID is restricted, don't allow them to bring up metered APNs
3942        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3943            final int uidRules;
3944            final int uid = Binder.getCallingUid();
3945            synchronized(mRulesLock) {
3946                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3947            }
3948            if (uidRules != RULE_ALLOW_ALL) {
3949                // we could silently fail or we can filter the available nets to only give
3950                // them those they have access to.  Chose the more useful
3951                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3952            }
3953        }
3954    }
3955
3956    @Override
3957    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3958            PendingIntent operation) {
3959        checkNotNull(operation, "PendingIntent cannot be null.");
3960        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3961        enforceNetworkRequestPermissions(networkCapabilities);
3962        enforceMeteredApnPolicy(networkCapabilities);
3963        ensureRequestableCapabilities(networkCapabilities);
3964
3965        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3966                nextNetworkRequestId());
3967        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3968                NetworkRequestType.REQUEST);
3969        if (DBG) log("pendingRequest for " + nri);
3970        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3971                nri));
3972        return networkRequest;
3973    }
3974
3975    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3976        mHandler.sendMessageDelayed(
3977                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3978                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3979    }
3980
3981    @Override
3982    public void releasePendingNetworkRequest(PendingIntent operation) {
3983        checkNotNull(operation, "PendingIntent cannot be null.");
3984        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3985                getCallingUid(), 0, operation));
3986    }
3987
3988    // In order to implement the compatibility measure for pre-M apps that call
3989    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3990    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3991    // This ensures it has permission to do so.
3992    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3993        if (nc == null) {
3994            return false;
3995        }
3996        int[] transportTypes = nc.getTransportTypes();
3997        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3998            return false;
3999        }
4000        try {
4001            mContext.enforceCallingOrSelfPermission(
4002                    android.Manifest.permission.ACCESS_WIFI_STATE,
4003                    "ConnectivityService");
4004        } catch (SecurityException e) {
4005            return false;
4006        }
4007        return true;
4008    }
4009
4010    @Override
4011    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4012            Messenger messenger, IBinder binder) {
4013        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4014            enforceAccessPermission();
4015        }
4016
4017        NetworkRequest networkRequest = new NetworkRequest(
4018                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4019        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4020                NetworkRequestType.LISTEN);
4021        if (VDBG) log("listenForNetwork for " + nri);
4022
4023        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4024        return networkRequest;
4025    }
4026
4027    @Override
4028    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4029            PendingIntent operation) {
4030        checkNotNull(operation, "PendingIntent cannot be null.");
4031        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4032            enforceAccessPermission();
4033        }
4034
4035        NetworkRequest networkRequest = new NetworkRequest(
4036                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4037        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
4038                NetworkRequestType.LISTEN);
4039        if (VDBG) log("pendingListenForNetwork for " + nri);
4040
4041        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4042    }
4043
4044    @Override
4045    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4046        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4047                0, networkRequest));
4048    }
4049
4050    @Override
4051    public void registerNetworkFactory(Messenger messenger, String name) {
4052        enforceConnectivityInternalPermission();
4053        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4054        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4055    }
4056
4057    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4058        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
4059        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4060        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4061    }
4062
4063    @Override
4064    public void unregisterNetworkFactory(Messenger messenger) {
4065        enforceConnectivityInternalPermission();
4066        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4067    }
4068
4069    private void handleUnregisterNetworkFactory(Messenger messenger) {
4070        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4071        if (nfi == null) {
4072            loge("Failed to find Messenger in unregisterNetworkFactory");
4073            return;
4074        }
4075        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
4076    }
4077
4078    /**
4079     * NetworkAgentInfo supporting a request by requestId.
4080     * These have already been vetted (their Capabilities satisfy the request)
4081     * and the are the highest scored network available.
4082     * the are keyed off the Requests requestId.
4083     */
4084    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
4085    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4086            new SparseArray<NetworkAgentInfo>();
4087
4088    // NOTE: Accessed on multiple threads, must be synchronized on itself.
4089    @GuardedBy("mNetworkForNetId")
4090    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4091            new SparseArray<NetworkAgentInfo>();
4092    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4093    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4094    // there may not be a strict 1:1 correlation between the two.
4095    @GuardedBy("mNetworkForNetId")
4096    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
4097
4098    // NetworkAgentInfo keyed off its connecting messenger
4099    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4100    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
4101    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4102            new HashMap<Messenger, NetworkAgentInfo>();
4103
4104    @GuardedBy("mBlockedAppUids")
4105    private final HashSet<Integer> mBlockedAppUids = new HashSet();
4106
4107    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
4108    private final NetworkRequest mDefaultRequest;
4109
4110    // Request used to optionally keep mobile data active even when higher
4111    // priority networks like Wi-Fi are active.
4112    private final NetworkRequest mDefaultMobileDataRequest;
4113
4114    private NetworkAgentInfo getDefaultNetwork() {
4115        return mNetworkForRequestId.get(mDefaultRequest.requestId);
4116    }
4117
4118    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4119        return nai == getDefaultNetwork();
4120    }
4121
4122    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4123            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4124            int currentScore, NetworkMisc networkMisc) {
4125        enforceConnectivityInternalPermission();
4126
4127        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4128        // satisfies mDefaultRequest.
4129        final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
4130                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4131                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
4132                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
4133        synchronized (this) {
4134            nai.networkMonitor.systemReady = mSystemReady;
4135        }
4136        addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
4137        if (DBG) log("registerNetworkAgent " + nai);
4138        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4139        return nai.network.netId;
4140    }
4141
4142    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4143        if (VDBG) log("Got NetworkAgent Messenger");
4144        mNetworkAgentInfos.put(na.messenger, na);
4145        synchronized (mNetworkForNetId) {
4146            mNetworkForNetId.put(na.network.netId, na);
4147        }
4148        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4149        NetworkInfo networkInfo = na.networkInfo;
4150        na.networkInfo = null;
4151        updateNetworkInfo(na, networkInfo);
4152    }
4153
4154    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4155        LinkProperties newLp = networkAgent.linkProperties;
4156        int netId = networkAgent.network.netId;
4157
4158        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4159        // we do anything else, make sure its LinkProperties are accurate.
4160        if (networkAgent.clatd != null) {
4161            networkAgent.clatd.fixupLinkProperties(oldLp);
4162        }
4163
4164        updateInterfaces(newLp, oldLp, netId);
4165        updateMtu(newLp, oldLp);
4166        // TODO - figure out what to do for clat
4167//        for (LinkProperties lp : newLp.getStackedLinks()) {
4168//            updateMtu(lp, null);
4169//        }
4170        updateTcpBufferSizes(networkAgent);
4171
4172        updateRoutes(newLp, oldLp, netId);
4173        updateDnses(newLp, oldLp, netId);
4174
4175        updateClat(newLp, oldLp, networkAgent);
4176        if (isDefaultNetwork(networkAgent)) {
4177            handleApplyDefaultProxy(newLp.getHttpProxy());
4178        } else {
4179            updateProxy(newLp, oldLp, networkAgent);
4180        }
4181        // TODO - move this check to cover the whole function
4182        if (!Objects.equals(newLp, oldLp)) {
4183            notifyIfacesChangedForNetworkStats();
4184            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4185        }
4186
4187        mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
4188    }
4189
4190    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4191        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4192        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
4193
4194        if (!wasRunningClat && shouldRunClat) {
4195            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4196            nai.clatd.start();
4197        } else if (wasRunningClat && !shouldRunClat) {
4198            nai.clatd.stop();
4199        }
4200    }
4201
4202    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4203        CompareResult<String> interfaceDiff = new CompareResult<String>();
4204        if (oldLp != null) {
4205            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4206        } else if (newLp != null) {
4207            interfaceDiff.added = newLp.getAllInterfaceNames();
4208        }
4209        for (String iface : interfaceDiff.added) {
4210            try {
4211                if (DBG) log("Adding iface " + iface + " to network " + netId);
4212                mNetd.addInterfaceToNetwork(iface, netId);
4213            } catch (Exception e) {
4214                loge("Exception adding interface: " + e);
4215            }
4216        }
4217        for (String iface : interfaceDiff.removed) {
4218            try {
4219                if (DBG) log("Removing iface " + iface + " from network " + netId);
4220                mNetd.removeInterfaceFromNetwork(iface, netId);
4221            } catch (Exception e) {
4222                loge("Exception removing interface: " + e);
4223            }
4224        }
4225    }
4226
4227    /**
4228     * Have netd update routes from oldLp to newLp.
4229     * @return true if routes changed between oldLp and newLp
4230     */
4231    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4232        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4233        if (oldLp != null) {
4234            routeDiff = oldLp.compareAllRoutes(newLp);
4235        } else if (newLp != null) {
4236            routeDiff.added = newLp.getAllRoutes();
4237        }
4238
4239        // add routes before removing old in case it helps with continuous connectivity
4240
4241        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4242        for (RouteInfo route : routeDiff.added) {
4243            if (route.hasGateway()) continue;
4244            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4245            try {
4246                mNetd.addRoute(netId, route);
4247            } catch (Exception e) {
4248                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4249                    loge("Exception in addRoute for non-gateway: " + e);
4250                }
4251            }
4252        }
4253        for (RouteInfo route : routeDiff.added) {
4254            if (route.hasGateway() == false) continue;
4255            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4256            try {
4257                mNetd.addRoute(netId, route);
4258            } catch (Exception e) {
4259                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4260                    loge("Exception in addRoute for gateway: " + e);
4261                }
4262            }
4263        }
4264
4265        for (RouteInfo route : routeDiff.removed) {
4266            if (VDBG) log("Removing Route [" + route + "] from network " + netId);
4267            try {
4268                mNetd.removeRoute(netId, route);
4269            } catch (Exception e) {
4270                loge("Exception in removeRoute: " + e);
4271            }
4272        }
4273        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4274    }
4275
4276    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4277        if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4278            return;  // no updating necessary
4279        }
4280
4281        Collection<InetAddress> dnses = newLp.getDnsServers();
4282        if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
4283        try {
4284            mNetd.setDnsServersForNetwork(
4285                    netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4286        } catch (Exception e) {
4287            loge("Exception in setDnsServersForNetwork: " + e);
4288        }
4289        final NetworkAgentInfo defaultNai = getDefaultNetwork();
4290        if (defaultNai != null && defaultNai.network.netId == netId) {
4291            setDefaultDnsSystemProperties(dnses);
4292        }
4293        flushVmDnsCache();
4294    }
4295
4296    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4297        int last = 0;
4298        for (InetAddress dns : dnses) {
4299            ++last;
4300            String key = "net.dns" + last;
4301            String value = dns.getHostAddress();
4302            SystemProperties.set(key, value);
4303        }
4304        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4305            String key = "net.dns" + i;
4306            SystemProperties.set(key, "");
4307        }
4308        mNumDnsEntries = last;
4309    }
4310
4311    /**
4312     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4313     * augmented with any stateful capabilities implied from {@code networkAgent}
4314     * (e.g., validated status and captive portal status).
4315     *
4316     * @param nai the network having its capabilities updated.
4317     * @param networkCapabilities the new network capabilities.
4318     */
4319    private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
4320        // Don't modify caller's NetworkCapabilities.
4321        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4322        if (nai.lastValidated) {
4323            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4324        } else {
4325            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4326        }
4327        if (nai.lastCaptivePortalDetected) {
4328            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4329        } else {
4330            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4331        }
4332        if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4333            final int oldScore = nai.getCurrentScore();
4334            if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4335                    networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4336                try {
4337                    mNetd.setNetworkPermission(nai.network.netId,
4338                            networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4339                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4340                } catch (RemoteException e) {
4341                    loge("Exception in setNetworkPermission: " + e);
4342                }
4343            }
4344            synchronized (nai) {
4345                nai.networkCapabilities = networkCapabilities;
4346            }
4347            rematchAllNetworksAndRequests(nai, oldScore);
4348            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4349        }
4350    }
4351
4352    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4353        for (int i = 0; i < nai.networkRequests.size(); i++) {
4354            NetworkRequest nr = nai.networkRequests.valueAt(i);
4355            // Don't send listening requests to factories. b/17393458
4356            if (!isRequest(nr)) continue;
4357            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4358        }
4359    }
4360
4361    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4362        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4363        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4364            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4365                    networkRequest);
4366        }
4367    }
4368
4369    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4370            int notificationType) {
4371        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4372            Intent intent = new Intent();
4373            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4374            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4375            nri.mPendingIntentSent = true;
4376            sendIntent(nri.mPendingIntent, intent);
4377        }
4378        // else not handled
4379    }
4380
4381    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4382        mPendingIntentWakeLock.acquire();
4383        try {
4384            if (DBG) log("Sending " + pendingIntent);
4385            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4386        } catch (PendingIntent.CanceledException e) {
4387            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4388            mPendingIntentWakeLock.release();
4389            releasePendingNetworkRequest(pendingIntent);
4390        }
4391        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4392    }
4393
4394    @Override
4395    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4396            String resultData, Bundle resultExtras) {
4397        if (DBG) log("Finished sending " + pendingIntent);
4398        mPendingIntentWakeLock.release();
4399        // Release with a delay so the receiving client has an opportunity to put in its
4400        // own request.
4401        releasePendingNetworkRequestWithDelay(pendingIntent);
4402    }
4403
4404    private void callCallbackForRequest(NetworkRequestInfo nri,
4405            NetworkAgentInfo networkAgent, int notificationType) {
4406        if (nri.messenger == null) return;  // Default request has no msgr
4407        Bundle bundle = new Bundle();
4408        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4409                new NetworkRequest(nri.request));
4410        Message msg = Message.obtain();
4411        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4412                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4413            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4414        }
4415        switch (notificationType) {
4416            case ConnectivityManager.CALLBACK_LOSING: {
4417                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4418                break;
4419            }
4420            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4421                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4422                        new NetworkCapabilities(networkAgent.networkCapabilities));
4423                break;
4424            }
4425            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4426                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4427                        new LinkProperties(networkAgent.linkProperties));
4428                break;
4429            }
4430        }
4431        msg.what = notificationType;
4432        msg.setData(bundle);
4433        try {
4434            if (VDBG) {
4435                log("sending notification " + notifyTypeToName(notificationType) +
4436                        " for " + nri.request);
4437            }
4438            nri.messenger.send(msg);
4439        } catch (RemoteException e) {
4440            // may occur naturally in the race of binder death.
4441            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4442        }
4443    }
4444
4445    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4446        for (int i = 0; i < nai.networkRequests.size(); i++) {
4447            NetworkRequest nr = nai.networkRequests.valueAt(i);
4448            // Ignore listening requests.
4449            if (!isRequest(nr)) continue;
4450            loge("Dead network still had at least " + nr);
4451            break;
4452        }
4453        nai.asyncChannel.disconnect();
4454    }
4455
4456    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4457        if (oldNetwork == null) {
4458            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4459            return;
4460        }
4461        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4462        teardownUnneededNetwork(oldNetwork);
4463    }
4464
4465    private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
4466        if (DBG) log("Switching to new default network: " + newNetwork);
4467        setupDataActivityTracking(newNetwork);
4468        try {
4469            mNetd.setDefaultNetId(newNetwork.network.netId);
4470        } catch (Exception e) {
4471            loge("Exception setting default network :" + e);
4472        }
4473        notifyLockdownVpn(newNetwork);
4474        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4475        updateTcpBufferSizes(newNetwork);
4476        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4477        logDefaultNetworkEvent(newNetwork, prevNetwork);
4478    }
4479
4480    // Handles a network appearing or improving its score.
4481    //
4482    // - Evaluates all current NetworkRequests that can be
4483    //   satisfied by newNetwork, and reassigns to newNetwork
4484    //   any such requests for which newNetwork is the best.
4485    //
4486    // - Lingers any validated Networks that as a result are no longer
4487    //   needed. A network is needed if it is the best network for
4488    //   one or more NetworkRequests, or if it is a VPN.
4489    //
4490    // - Tears down newNetwork if it just became validated
4491    //   but turns out to be unneeded.
4492    //
4493    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4494    //   networks that have no chance (i.e. even if validated)
4495    //   of becoming the highest scoring network.
4496    //
4497    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4498    // it does not remove NetworkRequests that other Networks could better satisfy.
4499    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4500    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4501    // as it performs better by a factor of the number of Networks.
4502    //
4503    // @param newNetwork is the network to be matched against NetworkRequests.
4504    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4505    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4506    //               validated) of becoming the highest scoring network.
4507    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
4508            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4509        if (!newNetwork.everConnected) return;
4510        boolean keep = newNetwork.isVPN();
4511        boolean isNewDefault = false;
4512        NetworkAgentInfo oldDefaultNetwork = null;
4513        if (VDBG) log("rematching " + newNetwork.name());
4514        // Find and migrate to this Network any NetworkRequests for
4515        // which this network is now the best.
4516        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4517        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4518        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4519        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4520            final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4521            final boolean satisfies = newNetwork.satisfies(nri.request);
4522            if (newNetwork == currentNetwork && satisfies) {
4523                if (VDBG) {
4524                    log("Network " + newNetwork.name() + " was already satisfying" +
4525                            " request " + nri.request.requestId + ". No change.");
4526                }
4527                keep = true;
4528                continue;
4529            }
4530
4531            // check if it satisfies the NetworkCapabilities
4532            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4533            if (satisfies) {
4534                if (!nri.isRequest()) {
4535                    // This is not a request, it's a callback listener.
4536                    // Add it to newNetwork regardless of score.
4537                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4538                    continue;
4539                }
4540
4541                // next check if it's better than any current network we're using for
4542                // this request
4543                if (VDBG) {
4544                    log("currentScore = " +
4545                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4546                            ", newScore = " + newNetwork.getCurrentScore());
4547                }
4548                if (currentNetwork == null ||
4549                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4550                    if (VDBG) log("rematch for " + newNetwork.name());
4551                    if (currentNetwork != null) {
4552                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
4553                        currentNetwork.networkRequests.remove(nri.request.requestId);
4554                        currentNetwork.networkLingered.add(nri.request);
4555                        affectedNetworks.add(currentNetwork);
4556                    } else {
4557                        if (VDBG) log("   accepting network in place of null");
4558                    }
4559                    unlinger(newNetwork);
4560                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4561                    if (!newNetwork.addRequest(nri.request)) {
4562                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4563                    }
4564                    addedRequests.add(nri);
4565                    keep = true;
4566                    // Tell NetworkFactories about the new score, so they can stop
4567                    // trying to connect if they know they cannot match it.
4568                    // TODO - this could get expensive if we have alot of requests for this
4569                    // network.  Think about if there is a way to reduce this.  Push
4570                    // netid->request mapping to each factory?
4571                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4572                    if (mDefaultRequest.requestId == nri.request.requestId) {
4573                        isNewDefault = true;
4574                        oldDefaultNetwork = currentNetwork;
4575                    }
4576                }
4577            } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4578                // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4579                // mark it as no longer satisfying "nri".  Because networks are processed by
4580                // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4581                // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4582                // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4583                // This means this code doesn't have to handle the case where "currentNetwork" no
4584                // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4585                if (DBG) {
4586                    log("Network " + newNetwork.name() + " stopped satisfying" +
4587                            " request " + nri.request.requestId);
4588                }
4589                newNetwork.networkRequests.remove(nri.request.requestId);
4590                if (currentNetwork == newNetwork) {
4591                    mNetworkForRequestId.remove(nri.request.requestId);
4592                    sendUpdatedScoreToFactories(nri.request, 0);
4593                } else {
4594                    if (nri.isRequest()) {
4595                        Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4596                                newNetwork.name() +
4597                                " without updating mNetworkForRequestId or factories!");
4598                    }
4599                }
4600                // TODO: technically, sending CALLBACK_LOST here is
4601                // incorrect if nri is a request (not a listen) and there
4602                // is a replacement network currently connected that can
4603                // satisfy it. However, the only capability that can both
4604                // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4605                // so this code is only incorrect for a network that loses
4606                // the TRUSTED capability, which is a rare case.
4607                callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
4608            }
4609        }
4610        // Linger any networks that are no longer needed.
4611        for (NetworkAgentInfo nai : affectedNetworks) {
4612            if (nai.lingering) {
4613                // Already lingered.  Nothing to do.  This can only happen if "nai" is in
4614                // "affectedNetworks" twice.  The reasoning being that to get added to
4615                // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4616                // (i.e. not lingered) so it could have only been lingered by this loop.
4617                // unneeded(nai) will be false and we'll call unlinger() below which would
4618                // be bad, so handle it here.
4619            } else if (unneeded(nai)) {
4620                linger(nai);
4621            } else {
4622                // Clear nai.networkLingered we might have added above.
4623                unlinger(nai);
4624            }
4625        }
4626        if (isNewDefault) {
4627            // Notify system services that this network is up.
4628            makeDefault(newNetwork, oldDefaultNetwork);
4629            synchronized (ConnectivityService.this) {
4630                // have a new default network, release the transition wakelock in
4631                // a second if it's held.  The second pause is to allow apps
4632                // to reconnect over the new network
4633                if (mNetTransitionWakeLock.isHeld()) {
4634                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
4635                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4636                            mNetTransitionWakeLockSerialNumber, 0),
4637                            1000);
4638                }
4639            }
4640        }
4641
4642        // do this after the default net is switched, but
4643        // before LegacyTypeTracker sends legacy broadcasts
4644        for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4645
4646        if (isNewDefault) {
4647            // Maintain the illusion: since the legacy API only
4648            // understands one network at a time, we must pretend
4649            // that the current default network disconnected before
4650            // the new one connected.
4651            if (oldDefaultNetwork != null) {
4652                mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4653                                          oldDefaultNetwork, true);
4654            }
4655            mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4656            mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4657            notifyLockdownVpn(newNetwork);
4658        }
4659
4660        if (keep) {
4661            // Notify battery stats service about this network, both the normal
4662            // interface and any stacked links.
4663            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4664            try {
4665                final IBatteryStats bs = BatteryStatsService.getService();
4666                final int type = newNetwork.networkInfo.getType();
4667
4668                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4669                bs.noteNetworkInterfaceType(baseIface, type);
4670                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4671                    final String stackedIface = stacked.getInterfaceName();
4672                    bs.noteNetworkInterfaceType(stackedIface, type);
4673                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4674                }
4675            } catch (RemoteException ignored) {
4676            }
4677
4678            // This has to happen after the notifyNetworkCallbacks as that tickles each
4679            // ConnectivityManager instance so that legacy requests correctly bind dns
4680            // requests to this network.  The legacy users are listening for this bcast
4681            // and will generally do a dns request so they can ensureRouteToHost and if
4682            // they do that before the callbacks happen they'll use the default network.
4683            //
4684            // TODO: Is there still a race here? We send the broadcast
4685            // after sending the callback, but if the app can receive the
4686            // broadcast before the callback, it might still break.
4687            //
4688            // This *does* introduce a race where if the user uses the new api
4689            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4690            // they may get old info.  Reverse this after the old startUsing api is removed.
4691            // This is on top of the multiple intent sequencing referenced in the todo above.
4692            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4693                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4694                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4695                    // legacy type tracker filters out repeat adds
4696                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4697                }
4698            }
4699
4700            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4701            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4702            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4703            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4704            if (newNetwork.isVPN()) {
4705                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4706            }
4707        }
4708        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4709            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4710                if (unneeded(nai)) {
4711                    if (DBG) log("Reaping " + nai.name());
4712                    teardownUnneededNetwork(nai);
4713                }
4714            }
4715        }
4716    }
4717
4718    /**
4719     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4720     * being disconnected.
4721     * @param changed If only one Network's score or capabilities have been modified since the last
4722     *         time this function was called, pass this Network in this argument, otherwise pass
4723     *         null.
4724     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4725     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4726     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4727     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4728     *         network's score.
4729     */
4730    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4731        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4732        // to avoid the slowness.  It is not simply enough to process just "changed", for
4733        // example in the case where "changed"'s score decreases and another network should begin
4734        // satifying a NetworkRequest that "changed" currently satisfies.
4735
4736        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4737        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4738        // rematchNetworkAndRequests() handles.
4739        if (changed != null && oldScore < changed.getCurrentScore()) {
4740            rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
4741        } else {
4742            final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4743                    new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4744            // Rematch higher scoring networks first to prevent requests first matching a lower
4745            // scoring network and then a higher scoring network, which could produce multiple
4746            // callbacks and inadvertently unlinger networks.
4747            Arrays.sort(nais);
4748            for (NetworkAgentInfo nai : nais) {
4749                rematchNetworkAndRequests(nai,
4750                        // Only reap the last time through the loop.  Reaping before all rematching
4751                        // is complete could incorrectly teardown a network that hasn't yet been
4752                        // rematched.
4753                        (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
4754                                : ReapUnvalidatedNetworks.REAP);
4755            }
4756        }
4757    }
4758
4759    private void updateInetCondition(NetworkAgentInfo nai) {
4760        // Don't bother updating until we've graduated to validated at least once.
4761        if (!nai.everValidated) return;
4762        // For now only update icons for default connection.
4763        // TODO: Update WiFi and cellular icons separately. b/17237507
4764        if (!isDefaultNetwork(nai)) return;
4765
4766        int newInetCondition = nai.lastValidated ? 100 : 0;
4767        // Don't repeat publish.
4768        if (newInetCondition == mDefaultInetConditionPublished) return;
4769
4770        mDefaultInetConditionPublished = newInetCondition;
4771        sendInetConditionBroadcast(nai.networkInfo);
4772    }
4773
4774    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4775        if (mLockdownTracker != null) {
4776            if (nai != null && nai.isVPN()) {
4777                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4778            } else {
4779                mLockdownTracker.onNetworkInfoChanged();
4780            }
4781        }
4782    }
4783
4784    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4785        NetworkInfo.State state = newInfo.getState();
4786        NetworkInfo oldInfo = null;
4787        final int oldScore = networkAgent.getCurrentScore();
4788        synchronized (networkAgent) {
4789            oldInfo = networkAgent.networkInfo;
4790            networkAgent.networkInfo = newInfo;
4791        }
4792        notifyLockdownVpn(networkAgent);
4793
4794        if (oldInfo != null && oldInfo.getState() == state) {
4795            if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4796                if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4797                notifyIfacesChangedForNetworkStats();
4798            } else if (VDBG) log("ignoring duplicate network state non-change");
4799            // In either case, no further work should be needed.
4800            return;
4801        }
4802        if (DBG) {
4803            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4804                    (oldInfo == null ? "null" : oldInfo.getState()) +
4805                    " to " + state);
4806        }
4807
4808        if (!networkAgent.created
4809                && (state == NetworkInfo.State.CONNECTED
4810                || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
4811            try {
4812                // This should never fail.  Specifying an already in use NetID will cause failure.
4813                if (networkAgent.isVPN()) {
4814                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4815                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4816                            (networkAgent.networkMisc == null ||
4817                                !networkAgent.networkMisc.allowBypass));
4818                } else {
4819                    mNetd.createPhysicalNetwork(networkAgent.network.netId,
4820                            networkAgent.networkCapabilities.hasCapability(
4821                                    NET_CAPABILITY_NOT_RESTRICTED) ?
4822                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4823                }
4824            } catch (Exception e) {
4825                loge("Error creating network " + networkAgent.network.netId + ": "
4826                        + e.getMessage());
4827                return;
4828            }
4829            networkAgent.created = true;
4830        }
4831
4832        if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4833            networkAgent.everConnected = true;
4834
4835            updateLinkProperties(networkAgent, null);
4836            notifyIfacesChangedForNetworkStats();
4837
4838            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4839            scheduleUnvalidatedPrompt(networkAgent);
4840
4841            if (networkAgent.isVPN()) {
4842                // Temporarily disable the default proxy (not global).
4843                synchronized (mProxyLock) {
4844                    if (!mDefaultProxyDisabled) {
4845                        mDefaultProxyDisabled = true;
4846                        if (mGlobalProxy == null && mDefaultProxy != null) {
4847                            sendProxyBroadcast(null);
4848                        }
4849                    }
4850                }
4851                // TODO: support proxy per network.
4852            }
4853
4854            // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4855            // be communicated to a particular NetworkAgent depends only on the network's immutable,
4856            // capabilities, so it only needs to be done once on initial connect, not every time the
4857            // network's capabilities change. Note that we do this before rematching the network,
4858            // so we could decide to tear it down immediately afterwards. That's fine though - on
4859            // disconnection NetworkAgents should stop any signal strength monitoring they have been
4860            // doing.
4861            updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
4862
4863            // Consider network even though it is not yet validated.
4864            rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
4865
4866            // This has to happen after matching the requests, because callbacks are just requests.
4867            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4868        } else if (state == NetworkInfo.State.DISCONNECTED) {
4869            networkAgent.asyncChannel.disconnect();
4870            if (networkAgent.isVPN()) {
4871                synchronized (mProxyLock) {
4872                    if (mDefaultProxyDisabled) {
4873                        mDefaultProxyDisabled = false;
4874                        if (mGlobalProxy == null && mDefaultProxy != null) {
4875                            sendProxyBroadcast(mDefaultProxy);
4876                        }
4877                    }
4878                }
4879            }
4880        } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4881                state == NetworkInfo.State.SUSPENDED) {
4882            // going into or coming out of SUSPEND: rescore and notify
4883            if (networkAgent.getCurrentScore() != oldScore) {
4884                rematchAllNetworksAndRequests(networkAgent, oldScore);
4885            }
4886            notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4887                    ConnectivityManager.CALLBACK_SUSPENDED :
4888                    ConnectivityManager.CALLBACK_RESUMED));
4889            mLegacyTypeTracker.update(networkAgent);
4890        }
4891    }
4892
4893    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4894        if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4895        if (score < 0) {
4896            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4897                    ").  Bumping score to min of 0");
4898            score = 0;
4899        }
4900
4901        final int oldScore = nai.getCurrentScore();
4902        nai.setCurrentScore(score);
4903
4904        rematchAllNetworksAndRequests(nai, oldScore);
4905
4906        sendUpdatedScoreToFactories(nai);
4907    }
4908
4909    // notify only this one new request of the current state
4910    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4911        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4912        // TODO - read state from monitor to decide what to send.
4913//        if (nai.networkMonitor.isLingering()) {
4914//            notifyType = NetworkCallbacks.LOSING;
4915//        } else if (nai.networkMonitor.isEvaluating()) {
4916//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4917//        }
4918        if (nri.mPendingIntent == null) {
4919            callCallbackForRequest(nri, nai, notifyType);
4920        } else {
4921            sendPendingIntentForRequest(nri, nai, notifyType);
4922        }
4923    }
4924
4925    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
4926        // The NetworkInfo we actually send out has no bearing on the real
4927        // state of affairs. For example, if the default connection is mobile,
4928        // and a request for HIPRI has just gone away, we need to pretend that
4929        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4930        // the state to DISCONNECTED, even though the network is of type MOBILE
4931        // and is still connected.
4932        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4933        info.setType(type);
4934        if (state != DetailedState.DISCONNECTED) {
4935            info.setDetailedState(state, null, info.getExtraInfo());
4936            sendConnectedBroadcast(info);
4937        } else {
4938            info.setDetailedState(state, info.getReason(), info.getExtraInfo());
4939            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4940            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4941            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4942            if (info.isFailover()) {
4943                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4944                nai.networkInfo.setFailover(false);
4945            }
4946            if (info.getReason() != null) {
4947                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4948            }
4949            if (info.getExtraInfo() != null) {
4950                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4951            }
4952            NetworkAgentInfo newDefaultAgent = null;
4953            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4954                newDefaultAgent = getDefaultNetwork();
4955                if (newDefaultAgent != null) {
4956                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4957                            newDefaultAgent.networkInfo);
4958                } else {
4959                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4960                }
4961            }
4962            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4963                    mDefaultInetConditionPublished);
4964            sendStickyBroadcast(intent);
4965            if (newDefaultAgent != null) {
4966                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4967            }
4968        }
4969    }
4970
4971    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4972        if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4973        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4974            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4975            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4976            if (VDBG) log(" sending notification for " + nr);
4977            if (nri.mPendingIntent == null) {
4978                callCallbackForRequest(nri, networkAgent, notifyType);
4979            } else {
4980                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4981            }
4982        }
4983    }
4984
4985    private String notifyTypeToName(int notifyType) {
4986        switch (notifyType) {
4987            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4988            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4989            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4990            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4991            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4992            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4993            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4994            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4995        }
4996        return "UNKNOWN";
4997    }
4998
4999    /**
5000     * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5001     * properties tracked by NetworkStatsService on an active iface has changed.
5002     */
5003    private void notifyIfacesChangedForNetworkStats() {
5004        try {
5005            mStatsService.forceUpdateIfaces();
5006        } catch (Exception ignored) {
5007        }
5008    }
5009
5010    @Override
5011    public boolean addVpnAddress(String address, int prefixLength) {
5012        throwIfLockdownEnabled();
5013        int user = UserHandle.getUserId(Binder.getCallingUid());
5014        synchronized (mVpns) {
5015            return mVpns.get(user).addAddress(address, prefixLength);
5016        }
5017    }
5018
5019    @Override
5020    public boolean removeVpnAddress(String address, int prefixLength) {
5021        throwIfLockdownEnabled();
5022        int user = UserHandle.getUserId(Binder.getCallingUid());
5023        synchronized (mVpns) {
5024            return mVpns.get(user).removeAddress(address, prefixLength);
5025        }
5026    }
5027
5028    @Override
5029    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5030        throwIfLockdownEnabled();
5031        int user = UserHandle.getUserId(Binder.getCallingUid());
5032        boolean success;
5033        synchronized (mVpns) {
5034            success = mVpns.get(user).setUnderlyingNetworks(networks);
5035        }
5036        if (success) {
5037            notifyIfacesChangedForNetworkStats();
5038        }
5039        return success;
5040    }
5041
5042    @Override
5043    public String getCaptivePortalServerUrl() {
5044        return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5045    }
5046
5047    @Override
5048    public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5049            IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5050        enforceKeepalivePermission();
5051        mKeepaliveTracker.startNattKeepalive(
5052                getNetworkAgentInfoForNetwork(network),
5053                intervalSeconds, messenger, binder,
5054                srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5055    }
5056
5057    @Override
5058    public void stopKeepalive(Network network, int slot) {
5059        mHandler.sendMessage(mHandler.obtainMessage(
5060                NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5061    }
5062
5063    @Override
5064    public void factoryReset() {
5065        enforceConnectivityInternalPermission();
5066
5067        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5068            return;
5069        }
5070
5071        final int userId = UserHandle.getCallingUserId();
5072
5073        // Turn airplane mode off
5074        setAirplaneMode(false);
5075
5076        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5077            // Untether
5078            for (String tether : getTetheredIfaces()) {
5079                untether(tether);
5080            }
5081        }
5082
5083        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5084            // Turn VPN off
5085            VpnConfig vpnConfig = getVpnConfig(userId);
5086            if (vpnConfig != null) {
5087                if (vpnConfig.legacy) {
5088                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5089                } else {
5090                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5091                    // in the future without user intervention.
5092                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
5093
5094                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5095                }
5096            }
5097        }
5098    }
5099
5100    @VisibleForTesting
5101    public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5102            NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5103        return new NetworkMonitor(context, handler, nai, defaultRequest);
5104    }
5105
5106    private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5107        int newNetid = NETID_UNSET;
5108        int prevNetid = NETID_UNSET;
5109        int[] transports = new int[0];
5110        boolean hadIPv4 = false;
5111        boolean hadIPv6 = false;
5112
5113        if (newNai != null) {
5114            newNetid = newNai.network.netId;
5115            transports = newNai.networkCapabilities.getTransportTypes();
5116        }
5117        if (prevNai != null) {
5118            prevNetid = prevNai.network.netId;
5119            final LinkProperties lp = prevNai.linkProperties;
5120            hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5121            hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5122        }
5123
5124        DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
5125    }
5126}
5127