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