ConnectivityService.java revision e0e413e2b17a0164e15c77f4ab51b3166f9111d2
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     * used internally to send a sticky broadcast delayed.
259     */
260    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
261
262    /**
263     * PAC manager has received new port.
264     */
265    private static final int EVENT_PROXY_HAS_CHANGED = 16;
266
267    /**
268     * used internally when registering NetworkFactories
269     * obj = NetworkFactoryInfo
270     */
271    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
272
273    /**
274     * used internally when registering NetworkAgents
275     * obj = Messenger
276     */
277    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
278
279    /**
280     * used to add a network request
281     * includes a NetworkRequestInfo
282     */
283    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
284
285    /**
286     * indicates a timeout period is over - check if we had a network yet or not
287     * and if not, call the timeout calback (but leave the request live until they
288     * cancel it.
289     * includes a NetworkRequestInfo
290     */
291    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
292
293    /**
294     * used to add a network listener - no request
295     * includes a NetworkRequestInfo
296     */
297    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
298
299    /**
300     * used to remove a network request, either a listener or a real request
301     * arg1 = UID of caller
302     * obj  = NetworkRequest
303     */
304    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
305
306    /**
307     * used internally when registering NetworkFactories
308     * obj = Messenger
309     */
310    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
311
312    /**
313     * used internally to expire a wakelock when transitioning
314     * from one net to another.  Expire happens when we fail to find
315     * a new network (typically after 1 minute) -
316     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
317     * a replacement network.
318     */
319    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
320
321    /**
322     * Used internally to indicate the system is ready.
323     */
324    private static final int EVENT_SYSTEM_READY = 25;
325
326    /**
327     * used to add a network request with a pending intent
328     * obj = NetworkRequestInfo
329     */
330    private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
331
332    /**
333     * used to remove a pending intent and its associated network request.
334     * arg1 = UID of caller
335     * obj  = PendingIntent
336     */
337    private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
338
339    /**
340     * used to specify whether a network should be used even if unvalidated.
341     * arg1 = whether to accept the network if it's unvalidated (1 or 0)
342     * arg2 = whether to remember this choice in the future (1 or 0)
343     * obj  = network
344     */
345    private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
346
347    /**
348     * used to ask the user to confirm a connection to an unvalidated network.
349     * obj  = network
350     */
351    private static final int EVENT_PROMPT_UNVALIDATED = 29;
352
353    /**
354     * used internally to (re)configure mobile data always-on settings.
355     */
356    private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
357
358    /**
359     * used to add a network listener with a pending intent
360     * obj = NetworkRequestInfo
361     */
362    private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
363
364    /** Handler thread used for both of the handlers below. */
365    @VisibleForTesting
366    protected final HandlerThread mHandlerThread;
367    /** Handler used for internal events. */
368    final private InternalHandler mHandler;
369    /** Handler used for incoming {@link NetworkStateTracker} events. */
370    final private NetworkStateTrackerHandler mTrackerHandler;
371
372    private boolean mSystemReady;
373    private Intent mInitialBroadcast;
374
375    private PowerManager.WakeLock mNetTransitionWakeLock;
376    private String mNetTransitionWakeLockCausedBy = "";
377    private int mNetTransitionWakeLockSerialNumber;
378    private int mNetTransitionWakeLockTimeout;
379    private final PowerManager.WakeLock mPendingIntentWakeLock;
380
381    private InetAddress mDefaultDns;
382
383    // used in DBG mode to track inet condition reports
384    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
385    private ArrayList mInetLog;
386
387    // track the current default http proxy - tell the world if we get a new one (real change)
388    private volatile ProxyInfo mDefaultProxy = null;
389    private Object mProxyLock = new Object();
390    private boolean mDefaultProxyDisabled = false;
391
392    // track the global proxy.
393    private ProxyInfo mGlobalProxy = null;
394
395    private PacManager mPacManager = null;
396
397    final private SettingsObserver mSettingsObserver;
398
399    private UserManager mUserManager;
400
401    NetworkConfig[] mNetConfigs;
402    int mNetworksDefined;
403
404    // the set of network types that can only be enabled by system/sig apps
405    List mProtectedNetworks;
406
407    private DataConnectionStats mDataConnectionStats;
408
409    TelephonyManager mTelephonyManager;
410
411    private KeepaliveTracker mKeepaliveTracker;
412
413    // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
414    private final static int MIN_NET_ID = 100; // some reserved marks
415    private final static int MAX_NET_ID = 65535;
416    private int mNextNetId = MIN_NET_ID;
417
418    // sequence number of NetworkRequests
419    private int mNextNetworkRequestId = 1;
420
421    // NetworkRequest activity String log entries.
422    private static final int MAX_NETWORK_REQUEST_LOGS = 20;
423    private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
424
425    // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
426    private static final int MAX_VALIDATION_LOGS = 10;
427    private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
428            new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
429
430    private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
431        synchronized(mValidationLogs) {
432            while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
433                mValidationLogs.removeLast();
434            }
435            mValidationLogs.addFirst(new Pair(network, log));
436        }
437    }
438
439    /**
440     * Implements support for the legacy "one network per network type" model.
441     *
442     * We used to have a static array of NetworkStateTrackers, one for each
443     * network type, but that doesn't work any more now that we can have,
444     * for example, more that one wifi network. This class stores all the
445     * NetworkAgentInfo objects that support a given type, but the legacy
446     * API will only see the first one.
447     *
448     * It serves two main purposes:
449     *
450     * 1. Provide information about "the network for a given type" (since this
451     *    API only supports one).
452     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
453     *    the first network for a given type changes, or if the default network
454     *    changes.
455     */
456    private class LegacyTypeTracker {
457
458        private static final boolean DBG = true;
459        private static final boolean VDBG = false;
460        private static final String TAG = "CSLegacyTypeTracker";
461
462        /**
463         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
464         * Each list holds references to all NetworkAgentInfos that are used to
465         * satisfy requests for that network type.
466         *
467         * This array is built out at startup such that an unsupported network
468         * doesn't get an ArrayList instance, making this a tristate:
469         * unsupported, supported but not active and active.
470         *
471         * The actual lists are populated when we scan the network types that
472         * are supported on this device.
473         */
474        private ArrayList<NetworkAgentInfo> mTypeLists[];
475
476        public LegacyTypeTracker() {
477            mTypeLists = (ArrayList<NetworkAgentInfo>[])
478                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
479        }
480
481        public void addSupportedType(int type) {
482            if (mTypeLists[type] != null) {
483                throw new IllegalStateException(
484                        "legacy list for type " + type + "already initialized");
485            }
486            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
487        }
488
489        public boolean isTypeSupported(int type) {
490            return isNetworkTypeValid(type) && mTypeLists[type] != null;
491        }
492
493        public NetworkAgentInfo getNetworkForType(int type) {
494            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
495                return mTypeLists[type].get(0);
496            } else {
497                return null;
498            }
499        }
500
501        private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
502                boolean isDefaultNetwork) {
503            if (DBG) {
504                log("Sending " + state +
505                        " broadcast for type " + type + " " + nai.name() +
506                        " isDefaultNetwork=" + isDefaultNetwork);
507            }
508        }
509
510        /** Adds the given network to the specified legacy type list. */
511        public void add(int type, NetworkAgentInfo nai) {
512            if (!isTypeSupported(type)) {
513                return;  // Invalid network type.
514            }
515            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
516
517            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
518            if (list.contains(nai)) {
519                return;
520            }
521
522            list.add(nai);
523
524            // Send a broadcast if this is the first network of its type or if it's the default.
525            final boolean isDefaultNetwork = isDefaultNetwork(nai);
526            if (list.size() == 1 || isDefaultNetwork) {
527                maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
528                sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
529            }
530        }
531
532        /** Removes the given network from the specified legacy type list. */
533        public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
534            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
535            if (list == null || list.isEmpty()) {
536                return;
537            }
538
539            final boolean wasFirstNetwork = list.get(0).equals(nai);
540
541            if (!list.remove(nai)) {
542                return;
543            }
544
545            final DetailedState state = DetailedState.DISCONNECTED;
546
547            if (wasFirstNetwork || wasDefault) {
548                maybeLogBroadcast(nai, state, type, wasDefault);
549                sendLegacyNetworkBroadcast(nai, state, type);
550            }
551
552            if (!list.isEmpty() && wasFirstNetwork) {
553                if (DBG) log("Other network available for type " + type +
554                              ", sending connected broadcast");
555                final NetworkAgentInfo replacement = list.get(0);
556                maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
557                sendLegacyNetworkBroadcast(replacement, state, type);
558            }
559        }
560
561        /** Removes the given network from all legacy type lists. */
562        public void remove(NetworkAgentInfo nai, boolean wasDefault) {
563            if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
564            for (int type = 0; type < mTypeLists.length; type++) {
565                remove(type, nai, wasDefault);
566            }
567        }
568
569        // send out another legacy broadcast - currently only used for suspend/unsuspend
570        // toggle
571        public void update(NetworkAgentInfo nai) {
572            final boolean isDefault = isDefaultNetwork(nai);
573            final DetailedState state = nai.networkInfo.getDetailedState();
574            for (int type = 0; type < mTypeLists.length; type++) {
575                final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
576                final boolean contains = (list != null && list.contains(nai));
577                final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
578                if (isFirst || (contains && isDefault)) {
579                    maybeLogBroadcast(nai, state, type, isDefault);
580                    sendLegacyNetworkBroadcast(nai, state, type);
581                }
582            }
583        }
584
585        private String naiToString(NetworkAgentInfo nai) {
586            String name = (nai != null) ? nai.name() : "null";
587            String state = (nai.networkInfo != null) ?
588                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
589                    "???/???";
590            return name + " " + state;
591        }
592
593        public void dump(IndentingPrintWriter pw) {
594            pw.println("mLegacyTypeTracker:");
595            pw.increaseIndent();
596            pw.print("Supported types:");
597            for (int type = 0; type < mTypeLists.length; type++) {
598                if (mTypeLists[type] != null) pw.print(" " + type);
599            }
600            pw.println();
601            pw.println("Current state:");
602            pw.increaseIndent();
603            for (int type = 0; type < mTypeLists.length; type++) {
604                if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
605                for (NetworkAgentInfo nai : mTypeLists[type]) {
606                    pw.println(type + " " + naiToString(nai));
607                }
608            }
609            pw.decreaseIndent();
610            pw.decreaseIndent();
611            pw.println();
612        }
613
614        // This class needs its own log method because it has a different TAG.
615        private void log(String s) {
616            Slog.d(TAG, s);
617        }
618
619    }
620    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
621
622    @VisibleForTesting
623    protected HandlerThread createHandlerThread() {
624        return new HandlerThread("ConnectivityServiceThread");
625    }
626
627    public ConnectivityService(Context context, INetworkManagementService netManager,
628            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
629        if (DBG) log("ConnectivityService starting up");
630
631        mDefaultRequest = createInternetRequestForTransport(-1);
632        NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
633                new Binder(), NetworkRequestInfo.REQUEST);
634        mNetworkRequests.put(mDefaultRequest, defaultNRI);
635        mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
636
637        mDefaultMobileDataRequest = createInternetRequestForTransport(
638                NetworkCapabilities.TRANSPORT_CELLULAR);
639
640        mHandlerThread = createHandlerThread();
641        mHandlerThread.start();
642        mHandler = new InternalHandler(mHandlerThread.getLooper());
643        mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
644
645        // setup our unique device name
646        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
647            String id = Settings.Secure.getString(context.getContentResolver(),
648                    Settings.Secure.ANDROID_ID);
649            if (id != null && id.length() > 0) {
650                String name = new String("android-").concat(id);
651                SystemProperties.set("net.hostname", name);
652            }
653        }
654
655        // read our default dns server ip
656        String dns = Settings.Global.getString(context.getContentResolver(),
657                Settings.Global.DEFAULT_DNS_SERVER);
658        if (dns == null || dns.length() == 0) {
659            dns = context.getResources().getString(
660                    com.android.internal.R.string.config_default_dns_server);
661        }
662        try {
663            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
664        } catch (IllegalArgumentException e) {
665            loge("Error setting defaultDns using " + dns);
666        }
667
668        mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
669                Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
670
671        mContext = checkNotNull(context, "missing Context");
672        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
673        mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
674        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
675        mKeyStore = KeyStore.getInstance();
676        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
677
678        try {
679            mPolicyManager.registerListener(mPolicyListener);
680        } catch (RemoteException e) {
681            // ouch, no rules updates means some processes may never get network
682            loge("unable to register INetworkPolicyListener" + e.toString());
683        }
684
685        final PowerManager powerManager = (PowerManager) context.getSystemService(
686                Context.POWER_SERVICE);
687        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
688        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
689                com.android.internal.R.integer.config_networkTransitionTimeout);
690        mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
691
692        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
693
694        // TODO: What is the "correct" way to do determine if this is a wifi only device?
695        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
696        log("wifiOnly=" + wifiOnly);
697        String[] naStrings = context.getResources().getStringArray(
698                com.android.internal.R.array.networkAttributes);
699        for (String naString : naStrings) {
700            try {
701                NetworkConfig n = new NetworkConfig(naString);
702                if (VDBG) log("naString=" + naString + " config=" + n);
703                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
704                    loge("Error in networkAttributes - ignoring attempt to define type " +
705                            n.type);
706                    continue;
707                }
708                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
709                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
710                            n.type);
711                    continue;
712                }
713                if (mNetConfigs[n.type] != null) {
714                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
715                            n.type);
716                    continue;
717                }
718                mLegacyTypeTracker.addSupportedType(n.type);
719
720                mNetConfigs[n.type] = n;
721                mNetworksDefined++;
722            } catch(Exception e) {
723                // ignore it - leave the entry null
724            }
725        }
726
727        // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
728        if (mNetConfigs[TYPE_VPN] == null) {
729            // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
730            // don't need to add TYPE_VPN to mNetConfigs.
731            mLegacyTypeTracker.addSupportedType(TYPE_VPN);
732            mNetworksDefined++;  // used only in the log() statement below.
733        }
734
735        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
736
737        mProtectedNetworks = new ArrayList<Integer>();
738        int[] protectedNetworks = context.getResources().getIntArray(
739                com.android.internal.R.array.config_protectedNetworks);
740        for (int p : protectedNetworks) {
741            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
742                mProtectedNetworks.add(p);
743            } else {
744                if (DBG) loge("Ignoring protectedNetwork " + p);
745            }
746        }
747
748        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
749                && SystemProperties.get("ro.build.type").equals("eng");
750
751        mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
752
753        mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
754
755        //set up the listener for user state for creating user VPNs
756        IntentFilter intentFilter = new IntentFilter();
757        intentFilter.addAction(Intent.ACTION_USER_STARTING);
758        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
759        intentFilter.addAction(Intent.ACTION_USER_ADDED);
760        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
761        mContext.registerReceiverAsUser(
762                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
763
764        try {
765            mNetd.registerObserver(mTethering);
766            mNetd.registerObserver(mDataActivityObserver);
767        } catch (RemoteException e) {
768            loge("Error registering observer :" + e);
769        }
770
771        if (DBG) {
772            mInetLog = new ArrayList();
773        }
774
775        mSettingsObserver = new SettingsObserver(mContext, mHandler);
776        registerSettingsCallbacks();
777
778        mDataConnectionStats = new DataConnectionStats(mContext);
779        mDataConnectionStats.startMonitoring();
780
781        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
782
783        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
784
785        mKeepaliveTracker = new KeepaliveTracker(mHandler);
786    }
787
788    private NetworkRequest createInternetRequestForTransport(int transportType) {
789        NetworkCapabilities netCap = new NetworkCapabilities();
790        netCap.addCapability(NET_CAPABILITY_INTERNET);
791        netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
792        if (transportType > -1) {
793            netCap.addTransportType(transportType);
794        }
795        return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
796    }
797
798    private void handleMobileDataAlwaysOn() {
799        final boolean enable = (Settings.Global.getInt(
800                mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
801        final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
802        if (enable == isEnabled) {
803            return;  // Nothing to do.
804        }
805
806        if (enable) {
807            handleRegisterNetworkRequest(new NetworkRequestInfo(
808                    null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
809        } else {
810            handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
811        }
812    }
813
814    private void registerSettingsCallbacks() {
815        // Watch for global HTTP proxy changes.
816        mSettingsObserver.observe(
817                Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
818                EVENT_APPLY_GLOBAL_HTTP_PROXY);
819
820        // Watch for whether or not to keep mobile data always on.
821        mSettingsObserver.observe(
822                Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
823                EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
824    }
825
826    private synchronized int nextNetworkRequestId() {
827        return mNextNetworkRequestId++;
828    }
829
830    @VisibleForTesting
831    protected int reserveNetId() {
832        synchronized (mNetworkForNetId) {
833            for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
834                int netId = mNextNetId;
835                if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
836                // Make sure NetID unused.  http://b/16815182
837                if (!mNetIdInUse.get(netId)) {
838                    mNetIdInUse.put(netId, true);
839                    return netId;
840                }
841            }
842        }
843        throw new IllegalStateException("No free netIds");
844    }
845
846    private NetworkState getFilteredNetworkState(int networkType, int uid) {
847        NetworkInfo info = null;
848        LinkProperties lp = null;
849        NetworkCapabilities nc = null;
850        Network network = null;
851        String subscriberId = null;
852
853        if (mLegacyTypeTracker.isTypeSupported(networkType)) {
854            NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
855            if (nai != null) {
856                synchronized (nai) {
857                    info = new NetworkInfo(nai.networkInfo);
858                    lp = new LinkProperties(nai.linkProperties);
859                    nc = new NetworkCapabilities(nai.networkCapabilities);
860                    // Network objects are outwardly immutable so there is no point to duplicating.
861                    // Duplicating also precludes sharing socket factories and connection pools.
862                    network = nai.network;
863                    subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
864                }
865                info.setType(networkType);
866            } else {
867                info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
868                info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
869                info.setIsAvailable(true);
870                lp = new LinkProperties();
871                nc = new NetworkCapabilities();
872                network = null;
873            }
874            info = getFilteredNetworkInfo(info, lp, uid);
875        }
876
877        return new NetworkState(info, lp, nc, network, subscriberId, null);
878    }
879
880    private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
881        if (network == null) {
882            return null;
883        }
884        synchronized (mNetworkForNetId) {
885            return mNetworkForNetId.get(network.netId);
886        }
887    };
888
889    private Network[] getVpnUnderlyingNetworks(int uid) {
890        if (!mLockdownEnabled) {
891            int user = UserHandle.getUserId(uid);
892            synchronized (mVpns) {
893                Vpn vpn = mVpns.get(user);
894                if (vpn != null && vpn.appliesToUid(uid)) {
895                    return vpn.getUnderlyingNetworks();
896                }
897            }
898        }
899        return null;
900    }
901
902    private NetworkState getUnfilteredActiveNetworkState(int uid) {
903        NetworkInfo info = null;
904        LinkProperties lp = null;
905        NetworkCapabilities nc = null;
906        Network network = null;
907        String subscriberId = null;
908
909        NetworkAgentInfo nai = getDefaultNetwork();
910
911        final Network[] networks = getVpnUnderlyingNetworks(uid);
912        if (networks != null) {
913            // getUnderlyingNetworks() returns:
914            // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
915            // empty array => the VPN explicitly said "no default network".
916            // non-empty array => the VPN specified one or more default networks; we use the
917            //                    first one.
918            if (networks.length > 0) {
919                nai = getNetworkAgentInfoForNetwork(networks[0]);
920            } else {
921                nai = null;
922            }
923        }
924
925        if (nai != null) {
926            synchronized (nai) {
927                info = new NetworkInfo(nai.networkInfo);
928                lp = new LinkProperties(nai.linkProperties);
929                nc = new NetworkCapabilities(nai.networkCapabilities);
930                // Network objects are outwardly immutable so there is no point to duplicating.
931                // Duplicating also precludes sharing socket factories and connection pools.
932                network = nai.network;
933                subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
934            }
935        }
936
937        return new NetworkState(info, lp, nc, network, subscriberId, null);
938    }
939
940    /**
941     * Check if UID should be blocked from using the network with the given LinkProperties.
942     */
943    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
944        final boolean networkCostly;
945        final int uidRules;
946
947        final String iface = (lp == null ? "" : lp.getInterfaceName());
948        synchronized (mRulesLock) {
949            networkCostly = mMeteredIfaces.contains(iface);
950            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
951        }
952
953        if (uidRules == RULE_REJECT_ALL) {
954            return true;
955        } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
956            return true;
957        } else {
958            return false;
959        }
960    }
961
962    /**
963     * Return a filtered {@link NetworkInfo}, potentially marked
964     * {@link DetailedState#BLOCKED} based on
965     * {@link #isNetworkWithLinkPropertiesBlocked}.
966     */
967    private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
968        if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
969            // network is blocked; clone and override state
970            info = new NetworkInfo(info);
971            info.setDetailedState(DetailedState.BLOCKED, null, null);
972            if (VDBG) {
973                log("returning Blocked NetworkInfo for ifname=" +
974                        lp.getInterfaceName() + ", uid=" + uid);
975            }
976        }
977        if (info != null && mLockdownTracker != null) {
978            info = mLockdownTracker.augmentNetworkInfo(info);
979            if (VDBG) log("returning Locked NetworkInfo");
980        }
981        return info;
982    }
983
984    /**
985     * Return NetworkInfo for the active (i.e., connected) network interface.
986     * It is assumed that at most one network is active at a time. If more
987     * than one is active, it is indeterminate which will be returned.
988     * @return the info for the active network, or {@code null} if none is
989     * active
990     */
991    @Override
992    public NetworkInfo getActiveNetworkInfo() {
993        enforceAccessPermission();
994        final int uid = Binder.getCallingUid();
995        NetworkState state = getUnfilteredActiveNetworkState(uid);
996        return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
997    }
998
999    @Override
1000    public Network getActiveNetwork() {
1001        enforceAccessPermission();
1002        final int uid = Binder.getCallingUid();
1003        final int user = UserHandle.getUserId(uid);
1004        int vpnNetId = NETID_UNSET;
1005        synchronized (mVpns) {
1006            final Vpn vpn = mVpns.get(user);
1007            if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1008        }
1009        NetworkAgentInfo nai;
1010        if (vpnNetId != NETID_UNSET) {
1011            synchronized (mNetworkForNetId) {
1012                nai = mNetworkForNetId.get(vpnNetId);
1013            }
1014            if (nai != null) return nai.network;
1015        }
1016        nai = getDefaultNetwork();
1017        if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1018        return nai != null ? nai.network : null;
1019    }
1020
1021    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1022        enforceAccessPermission();
1023        final int uid = Binder.getCallingUid();
1024        NetworkState state = getUnfilteredActiveNetworkState(uid);
1025        return state.networkInfo;
1026    }
1027
1028    @Override
1029    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1030        enforceConnectivityInternalPermission();
1031        NetworkState state = getUnfilteredActiveNetworkState(uid);
1032        return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1033    }
1034
1035    @Override
1036    public NetworkInfo getNetworkInfo(int networkType) {
1037        enforceAccessPermission();
1038        final int uid = Binder.getCallingUid();
1039        if (getVpnUnderlyingNetworks(uid) != null) {
1040            // A VPN is active, so we may need to return one of its underlying networks. This
1041            // information is not available in LegacyTypeTracker, so we have to get it from
1042            // getUnfilteredActiveNetworkState.
1043            NetworkState state = getUnfilteredActiveNetworkState(uid);
1044            if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1045                return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1046            }
1047        }
1048        NetworkState state = getFilteredNetworkState(networkType, uid);
1049        return state.networkInfo;
1050    }
1051
1052    @Override
1053    public NetworkInfo getNetworkInfoForNetwork(Network network) {
1054        enforceAccessPermission();
1055        final int uid = Binder.getCallingUid();
1056        NetworkInfo info = null;
1057        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1058        if (nai != null) {
1059            synchronized (nai) {
1060                info = new NetworkInfo(nai.networkInfo);
1061                info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
1062            }
1063        }
1064        return info;
1065    }
1066
1067    @Override
1068    public NetworkInfo[] getAllNetworkInfo() {
1069        enforceAccessPermission();
1070        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1071        for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1072                networkType++) {
1073            NetworkInfo info = getNetworkInfo(networkType);
1074            if (info != null) {
1075                result.add(info);
1076            }
1077        }
1078        return result.toArray(new NetworkInfo[result.size()]);
1079    }
1080
1081    @Override
1082    public Network getNetworkForType(int networkType) {
1083        enforceAccessPermission();
1084        final int uid = Binder.getCallingUid();
1085        NetworkState state = getFilteredNetworkState(networkType, uid);
1086        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1087            return state.network;
1088        }
1089        return null;
1090    }
1091
1092    @Override
1093    public Network[] getAllNetworks() {
1094        enforceAccessPermission();
1095        synchronized (mNetworkForNetId) {
1096            final Network[] result = new Network[mNetworkForNetId.size()];
1097            for (int i = 0; i < mNetworkForNetId.size(); i++) {
1098                result[i] = mNetworkForNetId.valueAt(i).network;
1099            }
1100            return result;
1101        }
1102    }
1103
1104    @Override
1105    public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1106        // The basic principle is: if an app's traffic could possibly go over a
1107        // network, without the app doing anything multinetwork-specific,
1108        // (hence, by "default"), then include that network's capabilities in
1109        // the array.
1110        //
1111        // In the normal case, app traffic only goes over the system's default
1112        // network connection, so that's the only network returned.
1113        //
1114        // With a VPN in force, some app traffic may go into the VPN, and thus
1115        // over whatever underlying networks the VPN specifies, while other app
1116        // traffic may go over the system default network (e.g.: a split-tunnel
1117        // VPN, or an app disallowed by the VPN), so the set of networks
1118        // returned includes the VPN's underlying networks and the system
1119        // default.
1120        enforceAccessPermission();
1121
1122        HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1123
1124        NetworkAgentInfo nai = getDefaultNetwork();
1125        NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1126        if (nc != null) {
1127            result.put(nai.network, nc);
1128        }
1129
1130        if (!mLockdownEnabled) {
1131            synchronized (mVpns) {
1132                Vpn vpn = mVpns.get(userId);
1133                if (vpn != null) {
1134                    Network[] networks = vpn.getUnderlyingNetworks();
1135                    if (networks != null) {
1136                        for (Network network : networks) {
1137                            nai = getNetworkAgentInfoForNetwork(network);
1138                            nc = getNetworkCapabilitiesInternal(nai);
1139                            if (nc != null) {
1140                                result.put(network, nc);
1141                            }
1142                        }
1143                    }
1144                }
1145            }
1146        }
1147
1148        NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1149        out = result.values().toArray(out);
1150        return out;
1151    }
1152
1153    @Override
1154    public boolean isNetworkSupported(int networkType) {
1155        enforceAccessPermission();
1156        return mLegacyTypeTracker.isTypeSupported(networkType);
1157    }
1158
1159    /**
1160     * Return LinkProperties for the active (i.e., connected) default
1161     * network interface.  It is assumed that at most one default network
1162     * is active at a time. If more than one is active, it is indeterminate
1163     * which will be returned.
1164     * @return the ip properties for the active network, or {@code null} if
1165     * none is active
1166     */
1167    @Override
1168    public LinkProperties getActiveLinkProperties() {
1169        enforceAccessPermission();
1170        final int uid = Binder.getCallingUid();
1171        NetworkState state = getUnfilteredActiveNetworkState(uid);
1172        return state.linkProperties;
1173    }
1174
1175    @Override
1176    public LinkProperties getLinkPropertiesForType(int networkType) {
1177        enforceAccessPermission();
1178        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1179        if (nai != null) {
1180            synchronized (nai) {
1181                return new LinkProperties(nai.linkProperties);
1182            }
1183        }
1184        return null;
1185    }
1186
1187    // TODO - this should be ALL networks
1188    @Override
1189    public LinkProperties getLinkProperties(Network network) {
1190        enforceAccessPermission();
1191        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1192        if (nai != null) {
1193            synchronized (nai) {
1194                return new LinkProperties(nai.linkProperties);
1195            }
1196        }
1197        return null;
1198    }
1199
1200    private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1201        if (nai != null) {
1202            synchronized (nai) {
1203                if (nai.networkCapabilities != null) {
1204                    return new NetworkCapabilities(nai.networkCapabilities);
1205                }
1206            }
1207        }
1208        return null;
1209    }
1210
1211    @Override
1212    public NetworkCapabilities getNetworkCapabilities(Network network) {
1213        enforceAccessPermission();
1214        return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1215    }
1216
1217    @Override
1218    public NetworkState[] getAllNetworkState() {
1219        // Require internal since we're handing out IMSI details
1220        enforceConnectivityInternalPermission();
1221
1222        final ArrayList<NetworkState> result = Lists.newArrayList();
1223        for (Network network : getAllNetworks()) {
1224            final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1225            if (nai != null) {
1226                synchronized (nai) {
1227                    final String subscriberId = (nai.networkMisc != null)
1228                            ? nai.networkMisc.subscriberId : null;
1229                    result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1230                            nai.networkCapabilities, network, subscriberId, null));
1231                }
1232            }
1233        }
1234        return result.toArray(new NetworkState[result.size()]);
1235    }
1236
1237    @Override
1238    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1239        enforceAccessPermission();
1240        final int uid = Binder.getCallingUid();
1241        final long token = Binder.clearCallingIdentity();
1242        try {
1243            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1244            if (state.networkInfo != null) {
1245                try {
1246                    return mPolicyManager.getNetworkQuotaInfo(state);
1247                } catch (RemoteException e) {
1248                }
1249            }
1250            return null;
1251        } finally {
1252            Binder.restoreCallingIdentity(token);
1253        }
1254    }
1255
1256    @Override
1257    public boolean isActiveNetworkMetered() {
1258        enforceAccessPermission();
1259        final int uid = Binder.getCallingUid();
1260        final long token = Binder.clearCallingIdentity();
1261        try {
1262            return isActiveNetworkMeteredUnchecked(uid);
1263        } finally {
1264            Binder.restoreCallingIdentity(token);
1265        }
1266    }
1267
1268    private boolean isActiveNetworkMeteredUnchecked(int uid) {
1269        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1270        if (state.networkInfo != null) {
1271            try {
1272                return mPolicyManager.isNetworkMetered(state);
1273            } catch (RemoteException e) {
1274            }
1275        }
1276        return false;
1277    }
1278
1279    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1280        @Override
1281        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1282            int deviceType = Integer.parseInt(label);
1283            sendDataActivityBroadcast(deviceType, active, tsNanos);
1284        }
1285    };
1286
1287    /**
1288     * Ensure that a network route exists to deliver traffic to the specified
1289     * host via the specified network interface.
1290     * @param networkType the type of the network over which traffic to the
1291     * specified host is to be routed
1292     * @param hostAddress the IP address of the host to which the route is
1293     * desired
1294     * @return {@code true} on success, {@code false} on failure
1295     */
1296    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1297        enforceChangePermission();
1298        if (mProtectedNetworks.contains(networkType)) {
1299            enforceConnectivityInternalPermission();
1300        }
1301
1302        InetAddress addr;
1303        try {
1304            addr = InetAddress.getByAddress(hostAddress);
1305        } catch (UnknownHostException e) {
1306            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1307            return false;
1308        }
1309
1310        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1311            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1312            return false;
1313        }
1314
1315        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1316        if (nai == null) {
1317            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1318                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1319            } else {
1320                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1321            }
1322            return false;
1323        }
1324
1325        DetailedState netState;
1326        synchronized (nai) {
1327            netState = nai.networkInfo.getDetailedState();
1328        }
1329
1330        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1331            if (VDBG) {
1332                log("requestRouteToHostAddress on down network "
1333                        + "(" + networkType + ") - dropped"
1334                        + " netState=" + netState);
1335            }
1336            return false;
1337        }
1338
1339        final int uid = Binder.getCallingUid();
1340        final long token = Binder.clearCallingIdentity();
1341        try {
1342            LinkProperties lp;
1343            int netId;
1344            synchronized (nai) {
1345                lp = nai.linkProperties;
1346                netId = nai.network.netId;
1347            }
1348            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1349            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1350            return ok;
1351        } finally {
1352            Binder.restoreCallingIdentity(token);
1353        }
1354    }
1355
1356    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1357        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1358        if (bestRoute == null) {
1359            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1360        } else {
1361            String iface = bestRoute.getInterface();
1362            if (bestRoute.getGateway().equals(addr)) {
1363                // if there is no better route, add the implied hostroute for our gateway
1364                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1365            } else {
1366                // if we will connect to this through another route, add a direct route
1367                // to it's gateway
1368                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1369            }
1370        }
1371        if (DBG) log("Adding legacy route " + bestRoute +
1372                " for UID/PID " + uid + "/" + Binder.getCallingPid());
1373        try {
1374            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1375        } catch (Exception e) {
1376            // never crash - catch them all
1377            if (DBG) loge("Exception trying to add a route: " + e);
1378            return false;
1379        }
1380        return true;
1381    }
1382
1383    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1384        @Override
1385        public void onUidRulesChanged(int uid, int uidRules) {
1386            // caller is NPMS, since we only register with them
1387            if (LOGD_RULES) {
1388                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1389            }
1390
1391            synchronized (mRulesLock) {
1392                // skip update when we've already applied rules
1393                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1394                if (oldRules == uidRules) return;
1395
1396                mUidRules.put(uid, uidRules);
1397            }
1398
1399            // TODO: notify UID when it has requested targeted updates
1400        }
1401
1402        @Override
1403        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1404            // caller is NPMS, since we only register with them
1405            if (LOGD_RULES) {
1406                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1407            }
1408
1409            synchronized (mRulesLock) {
1410                mMeteredIfaces.clear();
1411                for (String iface : meteredIfaces) {
1412                    mMeteredIfaces.add(iface);
1413                }
1414            }
1415        }
1416
1417        @Override
1418        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1419            // caller is NPMS, since we only register with them
1420            if (LOGD_RULES) {
1421                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1422            }
1423        }
1424    };
1425
1426    /**
1427     * Require that the caller is either in the same user or has appropriate permission to interact
1428     * across users.
1429     *
1430     * @param userId Target user for whatever operation the current IPC is supposed to perform.
1431     */
1432    private void enforceCrossUserPermission(int userId) {
1433        if (userId == UserHandle.getCallingUserId()) {
1434            // Not a cross-user call.
1435            return;
1436        }
1437        mContext.enforceCallingOrSelfPermission(
1438                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1439                "ConnectivityService");
1440    }
1441
1442    private void enforceInternetPermission() {
1443        mContext.enforceCallingOrSelfPermission(
1444                android.Manifest.permission.INTERNET,
1445                "ConnectivityService");
1446    }
1447
1448    private void enforceAccessPermission() {
1449        mContext.enforceCallingOrSelfPermission(
1450                android.Manifest.permission.ACCESS_NETWORK_STATE,
1451                "ConnectivityService");
1452    }
1453
1454    private void enforceChangePermission() {
1455        ConnectivityManager.enforceChangePermission(mContext);
1456    }
1457
1458    private void enforceTetherAccessPermission() {
1459        mContext.enforceCallingOrSelfPermission(
1460                android.Manifest.permission.ACCESS_NETWORK_STATE,
1461                "ConnectivityService");
1462    }
1463
1464    private void enforceConnectivityInternalPermission() {
1465        mContext.enforceCallingOrSelfPermission(
1466                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1467                "ConnectivityService");
1468    }
1469
1470    private void enforceKeepalivePermission() {
1471        mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1472    }
1473
1474    public void sendConnectedBroadcast(NetworkInfo info) {
1475        enforceConnectivityInternalPermission();
1476        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1477    }
1478
1479    private void sendInetConditionBroadcast(NetworkInfo info) {
1480        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1481    }
1482
1483    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1484        if (mLockdownTracker != null) {
1485            info = mLockdownTracker.augmentNetworkInfo(info);
1486        }
1487
1488        Intent intent = new Intent(bcastType);
1489        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1490        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1491        if (info.isFailover()) {
1492            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1493            info.setFailover(false);
1494        }
1495        if (info.getReason() != null) {
1496            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1497        }
1498        if (info.getExtraInfo() != null) {
1499            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1500                    info.getExtraInfo());
1501        }
1502        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1503        return intent;
1504    }
1505
1506    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1507        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1508    }
1509
1510    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1511        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1512        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1513        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1514        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1515        final long ident = Binder.clearCallingIdentity();
1516        try {
1517            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1518                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1519        } finally {
1520            Binder.restoreCallingIdentity(ident);
1521        }
1522    }
1523
1524    private void sendStickyBroadcast(Intent intent) {
1525        synchronized(this) {
1526            if (!mSystemReady) {
1527                mInitialBroadcast = new Intent(intent);
1528            }
1529            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1530            if (DBG) {
1531                log("sendStickyBroadcast: action=" + intent.getAction());
1532            }
1533
1534            Bundle options = null;
1535            final long ident = Binder.clearCallingIdentity();
1536            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1537                final NetworkInfo ni = intent.getParcelableExtra(
1538                        ConnectivityManager.EXTRA_NETWORK_INFO);
1539                if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1540                    intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1541                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1542                } else {
1543                    BroadcastOptions opts = BroadcastOptions.makeBasic();
1544                    opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1545                    options = opts.toBundle();
1546                }
1547                final IBatteryStats bs = BatteryStatsService.getService();
1548                try {
1549                    bs.noteConnectivityChanged(intent.getIntExtra(
1550                            ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1551                            ni != null ? ni.getState().toString() : "?");
1552                } catch (RemoteException e) {
1553                }
1554            }
1555            try {
1556                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
1557            } finally {
1558                Binder.restoreCallingIdentity(ident);
1559            }
1560        }
1561    }
1562
1563    void systemReady() {
1564        loadGlobalProxy();
1565
1566        synchronized(this) {
1567            mSystemReady = true;
1568            if (mInitialBroadcast != null) {
1569                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1570                mInitialBroadcast = null;
1571            }
1572        }
1573        // load the global proxy at startup
1574        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1575
1576        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1577        // for user to unlock device.
1578        if (!updateLockdownVpn()) {
1579            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1580            mContext.registerReceiver(mUserPresentReceiver, filter);
1581        }
1582
1583        // Configure whether mobile data is always on.
1584        mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1585
1586        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1587
1588        mPermissionMonitor.startMonitoring();
1589    }
1590
1591    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1592        @Override
1593        public void onReceive(Context context, Intent intent) {
1594            // Try creating lockdown tracker, since user present usually means
1595            // unlocked keystore.
1596            if (updateLockdownVpn()) {
1597                mContext.unregisterReceiver(this);
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_SEND_STICKY_BROADCAST_INTENT: {
2519                    Intent intent = (Intent)msg.obj;
2520                    sendStickyBroadcast(intent);
2521                    break;
2522                }
2523                case EVENT_PROXY_HAS_CHANGED: {
2524                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2525                    break;
2526                }
2527                case EVENT_REGISTER_NETWORK_FACTORY: {
2528                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2529                    break;
2530                }
2531                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2532                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2533                    break;
2534                }
2535                case EVENT_REGISTER_NETWORK_AGENT: {
2536                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2537                    break;
2538                }
2539                case EVENT_REGISTER_NETWORK_REQUEST:
2540                case EVENT_REGISTER_NETWORK_LISTENER: {
2541                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2542                    break;
2543                }
2544                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2545                case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
2546                    handleRegisterNetworkRequestWithIntent(msg);
2547                    break;
2548                }
2549                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2550                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2551                    break;
2552                }
2553                case EVENT_RELEASE_NETWORK_REQUEST: {
2554                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2555                    break;
2556                }
2557                case EVENT_SET_ACCEPT_UNVALIDATED: {
2558                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2559                    break;
2560                }
2561                case EVENT_PROMPT_UNVALIDATED: {
2562                    handlePromptUnvalidated((Network) msg.obj);
2563                    break;
2564                }
2565                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2566                    handleMobileDataAlwaysOn();
2567                    break;
2568                }
2569                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2570                case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2571                    mKeepaliveTracker.handleStartKeepalive(msg);
2572                    break;
2573                }
2574                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2575                case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2576                    NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2577                    int slot = msg.arg1;
2578                    int reason = msg.arg2;
2579                    mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2580                    break;
2581                }
2582                case EVENT_SYSTEM_READY: {
2583                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2584                        nai.networkMonitor.systemReady = true;
2585                    }
2586                    break;
2587                }
2588            }
2589        }
2590    }
2591
2592    // javadoc from interface
2593    public int tether(String iface) {
2594        ConnectivityManager.enforceTetherChangePermission(mContext);
2595        if (isTetheringSupported()) {
2596            return mTethering.tether(iface);
2597        } else {
2598            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2599        }
2600    }
2601
2602    // javadoc from interface
2603    public int untether(String iface) {
2604        ConnectivityManager.enforceTetherChangePermission(mContext);
2605
2606        if (isTetheringSupported()) {
2607            return mTethering.untether(iface);
2608        } else {
2609            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2610        }
2611    }
2612
2613    // javadoc from interface
2614    public int getLastTetherError(String iface) {
2615        enforceTetherAccessPermission();
2616
2617        if (isTetheringSupported()) {
2618            return mTethering.getLastTetherError(iface);
2619        } else {
2620            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2621        }
2622    }
2623
2624    // TODO - proper iface API for selection by property, inspection, etc
2625    public String[] getTetherableUsbRegexs() {
2626        enforceTetherAccessPermission();
2627        if (isTetheringSupported()) {
2628            return mTethering.getTetherableUsbRegexs();
2629        } else {
2630            return new String[0];
2631        }
2632    }
2633
2634    public String[] getTetherableWifiRegexs() {
2635        enforceTetherAccessPermission();
2636        if (isTetheringSupported()) {
2637            return mTethering.getTetherableWifiRegexs();
2638        } else {
2639            return new String[0];
2640        }
2641    }
2642
2643    public String[] getTetherableBluetoothRegexs() {
2644        enforceTetherAccessPermission();
2645        if (isTetheringSupported()) {
2646            return mTethering.getTetherableBluetoothRegexs();
2647        } else {
2648            return new String[0];
2649        }
2650    }
2651
2652    public int setUsbTethering(boolean enable) {
2653        ConnectivityManager.enforceTetherChangePermission(mContext);
2654        if (isTetheringSupported()) {
2655            return mTethering.setUsbTethering(enable);
2656        } else {
2657            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2658        }
2659    }
2660
2661    // TODO - move iface listing, queries, etc to new module
2662    // javadoc from interface
2663    public String[] getTetherableIfaces() {
2664        enforceTetherAccessPermission();
2665        return mTethering.getTetherableIfaces();
2666    }
2667
2668    public String[] getTetheredIfaces() {
2669        enforceTetherAccessPermission();
2670        return mTethering.getTetheredIfaces();
2671    }
2672
2673    public String[] getTetheringErroredIfaces() {
2674        enforceTetherAccessPermission();
2675        return mTethering.getErroredIfaces();
2676    }
2677
2678    public String[] getTetheredDhcpRanges() {
2679        enforceConnectivityInternalPermission();
2680        return mTethering.getTetheredDhcpRanges();
2681    }
2682
2683    // if ro.tether.denied = true we default to no tethering
2684    // gservices could set the secure setting to 1 though to enable it on a build where it
2685    // had previously been turned off.
2686    public boolean isTetheringSupported() {
2687        enforceTetherAccessPermission();
2688        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2689        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2690                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2691                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2692        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2693                mTethering.getTetherableWifiRegexs().length != 0 ||
2694                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2695                mTethering.getUpstreamIfaceTypes().length != 0);
2696    }
2697
2698    // Called when we lose the default network and have no replacement yet.
2699    // This will automatically be cleared after X seconds or a new default network
2700    // becomes CONNECTED, whichever happens first.  The timer is started by the
2701    // first caller and not restarted by subsequent callers.
2702    private void requestNetworkTransitionWakelock(String forWhom) {
2703        int serialNum = 0;
2704        synchronized (this) {
2705            if (mNetTransitionWakeLock.isHeld()) return;
2706            serialNum = ++mNetTransitionWakeLockSerialNumber;
2707            mNetTransitionWakeLock.acquire();
2708            mNetTransitionWakeLockCausedBy = forWhom;
2709        }
2710        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2711                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2712                mNetTransitionWakeLockTimeout);
2713        return;
2714    }
2715
2716    // 100 percent is full good, 0 is full bad.
2717    public void reportInetCondition(int networkType, int percentage) {
2718        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2719        if (nai == null) return;
2720        reportNetworkConnectivity(nai.network, percentage > 50);
2721    }
2722
2723    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2724        enforceAccessPermission();
2725        enforceInternetPermission();
2726
2727        NetworkAgentInfo nai;
2728        if (network == null) {
2729            nai = getDefaultNetwork();
2730        } else {
2731            nai = getNetworkAgentInfoForNetwork(network);
2732        }
2733        if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2734            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2735            return;
2736        }
2737        // Revalidate if the app report does not match our current validated state.
2738        if (hasConnectivity == nai.lastValidated) return;
2739        final int uid = Binder.getCallingUid();
2740        if (DBG) {
2741            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2742                    ") by " + uid);
2743        }
2744        synchronized (nai) {
2745            // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2746            // which isn't meant to work on uncreated networks.
2747            if (!nai.created) return;
2748
2749            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
2750
2751            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2752        }
2753    }
2754
2755    private ProxyInfo getDefaultProxy() {
2756        // this information is already available as a world read/writable jvm property
2757        // so this API change wouldn't have a benifit.  It also breaks the passing
2758        // of proxy info to all the JVMs.
2759        // enforceAccessPermission();
2760        synchronized (mProxyLock) {
2761            ProxyInfo ret = mGlobalProxy;
2762            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2763            return ret;
2764        }
2765    }
2766
2767    public ProxyInfo getProxyForNetwork(Network network) {
2768        if (network == null) return getDefaultProxy();
2769        final ProxyInfo globalProxy = getGlobalProxy();
2770        if (globalProxy != null) return globalProxy;
2771        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2772        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2773        // caller may not have.
2774        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2775        if (nai == null) return null;
2776        synchronized (nai) {
2777            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2778            if (proxyInfo == null) return null;
2779            return new ProxyInfo(proxyInfo);
2780        }
2781    }
2782
2783    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2784    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2785    // proxy is null then there is no proxy in place).
2786    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2787        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2788                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2789            proxy = null;
2790        }
2791        return proxy;
2792    }
2793
2794    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2795    // better for determining if a new proxy broadcast is necessary:
2796    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2797    //    avoid unnecessary broadcasts.
2798    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2799    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2800    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2801    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2802    //    all set.
2803    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2804        a = canonicalizeProxyInfo(a);
2805        b = canonicalizeProxyInfo(b);
2806        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2807        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2808        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2809    }
2810
2811    public void setGlobalProxy(ProxyInfo proxyProperties) {
2812        enforceConnectivityInternalPermission();
2813
2814        synchronized (mProxyLock) {
2815            if (proxyProperties == mGlobalProxy) return;
2816            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2817            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2818
2819            String host = "";
2820            int port = 0;
2821            String exclList = "";
2822            String pacFileUrl = "";
2823            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2824                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2825                if (!proxyProperties.isValid()) {
2826                    if (DBG)
2827                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2828                    return;
2829                }
2830                mGlobalProxy = new ProxyInfo(proxyProperties);
2831                host = mGlobalProxy.getHost();
2832                port = mGlobalProxy.getPort();
2833                exclList = mGlobalProxy.getExclusionListAsString();
2834                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2835                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2836                }
2837            } else {
2838                mGlobalProxy = null;
2839            }
2840            ContentResolver res = mContext.getContentResolver();
2841            final long token = Binder.clearCallingIdentity();
2842            try {
2843                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2844                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2845                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2846                        exclList);
2847                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2848            } finally {
2849                Binder.restoreCallingIdentity(token);
2850            }
2851
2852            if (mGlobalProxy == null) {
2853                proxyProperties = mDefaultProxy;
2854            }
2855            sendProxyBroadcast(proxyProperties);
2856        }
2857    }
2858
2859    private void loadGlobalProxy() {
2860        ContentResolver res = mContext.getContentResolver();
2861        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2862        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2863        String exclList = Settings.Global.getString(res,
2864                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2865        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2866        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2867            ProxyInfo proxyProperties;
2868            if (!TextUtils.isEmpty(pacFileUrl)) {
2869                proxyProperties = new ProxyInfo(pacFileUrl);
2870            } else {
2871                proxyProperties = new ProxyInfo(host, port, exclList);
2872            }
2873            if (!proxyProperties.isValid()) {
2874                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2875                return;
2876            }
2877
2878            synchronized (mProxyLock) {
2879                mGlobalProxy = proxyProperties;
2880            }
2881        }
2882    }
2883
2884    public ProxyInfo getGlobalProxy() {
2885        // this information is already available as a world read/writable jvm property
2886        // so this API change wouldn't have a benifit.  It also breaks the passing
2887        // of proxy info to all the JVMs.
2888        // enforceAccessPermission();
2889        synchronized (mProxyLock) {
2890            return mGlobalProxy;
2891        }
2892    }
2893
2894    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2895        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2896                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2897            proxy = null;
2898        }
2899        synchronized (mProxyLock) {
2900            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2901            if (mDefaultProxy == proxy) return; // catches repeated nulls
2902            if (proxy != null &&  !proxy.isValid()) {
2903                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2904                return;
2905            }
2906
2907            // This call could be coming from the PacManager, containing the port of the local
2908            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2909            // global (to get the correct local port), and send a broadcast.
2910            // TODO: Switch PacManager to have its own message to send back rather than
2911            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2912            if ((mGlobalProxy != null) && (proxy != null)
2913                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2914                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2915                mGlobalProxy = proxy;
2916                sendProxyBroadcast(mGlobalProxy);
2917                return;
2918            }
2919            mDefaultProxy = proxy;
2920
2921            if (mGlobalProxy != null) return;
2922            if (!mDefaultProxyDisabled) {
2923                sendProxyBroadcast(proxy);
2924            }
2925        }
2926    }
2927
2928    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2929    // This method gets called when any network changes proxy, but the broadcast only ever contains
2930    // the default proxy (even if it hasn't changed).
2931    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2932    // world where an app might be bound to a non-default network.
2933    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2934        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2935        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2936
2937        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2938            sendProxyBroadcast(getDefaultProxy());
2939        }
2940    }
2941
2942    private void handleDeprecatedGlobalHttpProxy() {
2943        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2944                Settings.Global.HTTP_PROXY);
2945        if (!TextUtils.isEmpty(proxy)) {
2946            String data[] = proxy.split(":");
2947            if (data.length == 0) {
2948                return;
2949            }
2950
2951            String proxyHost =  data[0];
2952            int proxyPort = 8080;
2953            if (data.length > 1) {
2954                try {
2955                    proxyPort = Integer.parseInt(data[1]);
2956                } catch (NumberFormatException e) {
2957                    return;
2958                }
2959            }
2960            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2961            setGlobalProxy(p);
2962        }
2963    }
2964
2965    private void sendProxyBroadcast(ProxyInfo proxy) {
2966        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2967        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2968        if (DBG) log("sending Proxy Broadcast for " + proxy);
2969        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2970        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2971            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2972        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2973        final long ident = Binder.clearCallingIdentity();
2974        try {
2975            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2976        } finally {
2977            Binder.restoreCallingIdentity(ident);
2978        }
2979    }
2980
2981    private static class SettingsObserver extends ContentObserver {
2982        final private HashMap<Uri, Integer> mUriEventMap;
2983        final private Context mContext;
2984        final private Handler mHandler;
2985
2986        SettingsObserver(Context context, Handler handler) {
2987            super(null);
2988            mUriEventMap = new HashMap<Uri, Integer>();
2989            mContext = context;
2990            mHandler = handler;
2991        }
2992
2993        void observe(Uri uri, int what) {
2994            mUriEventMap.put(uri, what);
2995            final ContentResolver resolver = mContext.getContentResolver();
2996            resolver.registerContentObserver(uri, false, this);
2997        }
2998
2999        @Override
3000        public void onChange(boolean selfChange) {
3001            Slog.wtf(TAG, "Should never be reached.");
3002        }
3003
3004        @Override
3005        public void onChange(boolean selfChange, Uri uri) {
3006            final Integer what = mUriEventMap.get(uri);
3007            if (what != null) {
3008                mHandler.obtainMessage(what.intValue()).sendToTarget();
3009            } else {
3010                loge("No matching event to send for URI=" + uri);
3011            }
3012        }
3013    }
3014
3015    private static void log(String s) {
3016        Slog.d(TAG, s);
3017    }
3018
3019    private static void loge(String s) {
3020        Slog.e(TAG, s);
3021    }
3022
3023    private static <T> T checkNotNull(T value, String message) {
3024        if (value == null) {
3025            throw new NullPointerException(message);
3026        }
3027        return value;
3028    }
3029
3030    /**
3031     * Prepare for a VPN application.
3032     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3033     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3034     *
3035     * @param oldPackage Package name of the application which currently controls VPN, which will
3036     *                   be replaced. If there is no such application, this should should either be
3037     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3038     * @param newPackage Package name of the application which should gain control of VPN, or
3039     *                   {@code null} to disable.
3040     * @param userId User for whom to prepare the new VPN.
3041     *
3042     * @hide
3043     */
3044    @Override
3045    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3046            int userId) {
3047        enforceCrossUserPermission(userId);
3048        throwIfLockdownEnabled();
3049
3050        synchronized(mVpns) {
3051            Vpn vpn = mVpns.get(userId);
3052            if (vpn != null) {
3053                return vpn.prepare(oldPackage, newPackage);
3054            } else {
3055                return false;
3056            }
3057        }
3058    }
3059
3060    /**
3061     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3062     * This method is used by system-privileged apps.
3063     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3064     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3065     *
3066     * @param packageName The package for which authorization state should change.
3067     * @param userId User for whom {@code packageName} is installed.
3068     * @param authorized {@code true} if this app should be able to start a VPN connection without
3069     *                   explicit user approval, {@code false} if not.
3070     *
3071     * @hide
3072     */
3073    @Override
3074    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3075        enforceCrossUserPermission(userId);
3076
3077        synchronized(mVpns) {
3078            Vpn vpn = mVpns.get(userId);
3079            if (vpn != null) {
3080                vpn.setPackageAuthorization(packageName, authorized);
3081            }
3082        }
3083    }
3084
3085    /**
3086     * Configure a TUN interface and return its file descriptor. Parameters
3087     * are encoded and opaque to this class. This method is used by VpnBuilder
3088     * and not available in ConnectivityManager. Permissions are checked in
3089     * Vpn class.
3090     * @hide
3091     */
3092    @Override
3093    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3094        throwIfLockdownEnabled();
3095        int user = UserHandle.getUserId(Binder.getCallingUid());
3096        synchronized(mVpns) {
3097            return mVpns.get(user).establish(config);
3098        }
3099    }
3100
3101    /**
3102     * Start legacy VPN, controlling native daemons as needed. Creates a
3103     * secondary thread to perform connection work, returning quickly.
3104     */
3105    @Override
3106    public void startLegacyVpn(VpnProfile profile) {
3107        throwIfLockdownEnabled();
3108        final LinkProperties egress = getActiveLinkProperties();
3109        if (egress == null) {
3110            throw new IllegalStateException("Missing active network connection");
3111        }
3112        int user = UserHandle.getUserId(Binder.getCallingUid());
3113        synchronized(mVpns) {
3114            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3115        }
3116    }
3117
3118    /**
3119     * Return the information of the ongoing legacy VPN. This method is used
3120     * by VpnSettings and not available in ConnectivityManager. Permissions
3121     * are checked in Vpn class.
3122     */
3123    @Override
3124    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3125        enforceCrossUserPermission(userId);
3126        if (mLockdownEnabled) {
3127            return null;
3128        }
3129
3130        synchronized(mVpns) {
3131            return mVpns.get(userId).getLegacyVpnInfo();
3132        }
3133    }
3134
3135    /**
3136     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3137     * and not available in ConnectivityManager.
3138     */
3139    @Override
3140    public VpnInfo[] getAllVpnInfo() {
3141        enforceConnectivityInternalPermission();
3142        if (mLockdownEnabled) {
3143            return new VpnInfo[0];
3144        }
3145
3146        synchronized(mVpns) {
3147            List<VpnInfo> infoList = new ArrayList<>();
3148            for (int i = 0; i < mVpns.size(); i++) {
3149                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3150                if (info != null) {
3151                    infoList.add(info);
3152                }
3153            }
3154            return infoList.toArray(new VpnInfo[infoList.size()]);
3155        }
3156    }
3157
3158    /**
3159     * @return VPN information for accounting, or null if we can't retrieve all required
3160     *         information, e.g primary underlying iface.
3161     */
3162    @Nullable
3163    private VpnInfo createVpnInfo(Vpn vpn) {
3164        VpnInfo info = vpn.getVpnInfo();
3165        if (info == null) {
3166            return null;
3167        }
3168        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3169        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3170        // the underlyingNetworks list.
3171        if (underlyingNetworks == null) {
3172            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3173            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3174                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3175            }
3176        } else if (underlyingNetworks.length > 0) {
3177            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3178            if (linkProperties != null) {
3179                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3180            }
3181        }
3182        return info.primaryUnderlyingIface == null ? null : info;
3183    }
3184
3185    /**
3186     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3187     * VpnDialogs and not available in ConnectivityManager.
3188     * Permissions are checked in Vpn class.
3189     * @hide
3190     */
3191    @Override
3192    public VpnConfig getVpnConfig(int userId) {
3193        enforceCrossUserPermission(userId);
3194        synchronized(mVpns) {
3195            Vpn vpn = mVpns.get(userId);
3196            if (vpn != null) {
3197                return vpn.getVpnConfig();
3198            } else {
3199                return null;
3200            }
3201        }
3202    }
3203
3204    @Override
3205    public boolean updateLockdownVpn() {
3206        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3207            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3208            return false;
3209        }
3210
3211        // Tear down existing lockdown if profile was removed
3212        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3213        if (mLockdownEnabled) {
3214            if (!mKeyStore.isUnlocked()) {
3215                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3216                return false;
3217            }
3218
3219            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3220            final VpnProfile profile = VpnProfile.decode(
3221                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3222            if (profile == null) {
3223                Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3224                setLockdownTracker(null);
3225                return true;
3226            }
3227            int user = UserHandle.getUserId(Binder.getCallingUid());
3228            synchronized(mVpns) {
3229                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3230                            profile));
3231            }
3232        } else {
3233            setLockdownTracker(null);
3234        }
3235
3236        return true;
3237    }
3238
3239    /**
3240     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3241     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3242     */
3243    private void setLockdownTracker(LockdownVpnTracker tracker) {
3244        // Shutdown any existing tracker
3245        final LockdownVpnTracker existing = mLockdownTracker;
3246        mLockdownTracker = null;
3247        if (existing != null) {
3248            existing.shutdown();
3249        }
3250
3251        try {
3252            if (tracker != null) {
3253                mNetd.setFirewallEnabled(true);
3254                mNetd.setFirewallInterfaceRule("lo", true);
3255                mLockdownTracker = tracker;
3256                mLockdownTracker.init();
3257            } else {
3258                mNetd.setFirewallEnabled(false);
3259            }
3260        } catch (RemoteException e) {
3261            // ignored; NMS lives inside system_server
3262        }
3263    }
3264
3265    private void throwIfLockdownEnabled() {
3266        if (mLockdownEnabled) {
3267            throw new IllegalStateException("Unavailable in lockdown mode");
3268        }
3269    }
3270
3271    @Override
3272    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3273        // TODO: Remove?  Any reason to trigger a provisioning check?
3274        return -1;
3275    }
3276
3277    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3278    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3279
3280    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3281        if (DBG) {
3282            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3283                + " action=" + action);
3284        }
3285        Intent intent = new Intent(action);
3286        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3287        // Concatenate the range of types onto the range of NetIDs.
3288        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3289        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3290                networkType, null, pendingIntent, false);
3291    }
3292
3293    /**
3294     * Show or hide network provisioning notifications.
3295     *
3296     * We use notifications for two purposes: to notify that a network requires sign in
3297     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3298     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3299     * particular network we can display the notification type that was most recently requested.
3300     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3301     * might first display NO_INTERNET, and then when the captive portal check completes, display
3302     * SIGN_IN.
3303     *
3304     * @param id an identifier that uniquely identifies this notification.  This must match
3305     *         between show and hide calls.  We use the NetID value but for legacy callers
3306     *         we concatenate the range of types with the range of NetIDs.
3307     */
3308    private void setProvNotificationVisibleIntent(boolean visible, int id,
3309            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3310            boolean highPriority) {
3311        if (DBG) {
3312            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3313                    + " networkType=" + getNetworkTypeName(networkType)
3314                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3315        }
3316
3317        Resources r = Resources.getSystem();
3318        NotificationManager notificationManager = (NotificationManager) mContext
3319            .getSystemService(Context.NOTIFICATION_SERVICE);
3320
3321        if (visible) {
3322            CharSequence title;
3323            CharSequence details;
3324            int icon;
3325            if (notifyType == NotificationType.NO_INTERNET &&
3326                    networkType == ConnectivityManager.TYPE_WIFI) {
3327                title = r.getString(R.string.wifi_no_internet, 0);
3328                details = r.getString(R.string.wifi_no_internet_detailed);
3329                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3330            } else if (notifyType == NotificationType.SIGN_IN) {
3331                switch (networkType) {
3332                    case ConnectivityManager.TYPE_WIFI:
3333                        title = r.getString(R.string.wifi_available_sign_in, 0);
3334                        details = r.getString(R.string.network_available_sign_in_detailed,
3335                                extraInfo);
3336                        icon = R.drawable.stat_notify_wifi_in_range;
3337                        break;
3338                    case ConnectivityManager.TYPE_MOBILE:
3339                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3340                        title = r.getString(R.string.network_available_sign_in, 0);
3341                        // TODO: Change this to pull from NetworkInfo once a printable
3342                        // name has been added to it
3343                        details = mTelephonyManager.getNetworkOperatorName();
3344                        icon = R.drawable.stat_notify_rssi_in_range;
3345                        break;
3346                    default:
3347                        title = r.getString(R.string.network_available_sign_in, 0);
3348                        details = r.getString(R.string.network_available_sign_in_detailed,
3349                                extraInfo);
3350                        icon = R.drawable.stat_notify_rssi_in_range;
3351                        break;
3352                }
3353            } else {
3354                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3355                        + getNetworkTypeName(networkType));
3356                return;
3357            }
3358
3359            Notification notification = new Notification.Builder(mContext)
3360                    .setWhen(0)
3361                    .setSmallIcon(icon)
3362                    .setAutoCancel(true)
3363                    .setTicker(title)
3364                    .setColor(mContext.getColor(
3365                            com.android.internal.R.color.system_notification_accent_color))
3366                    .setContentTitle(title)
3367                    .setContentText(details)
3368                    .setContentIntent(intent)
3369                    .setLocalOnly(true)
3370                    .setPriority(highPriority ?
3371                            Notification.PRIORITY_HIGH :
3372                            Notification.PRIORITY_DEFAULT)
3373                    .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
3374                    .setOnlyAlertOnce(true)
3375                    .build();
3376
3377            try {
3378                notificationManager.notify(NOTIFICATION_ID, id, notification);
3379            } catch (NullPointerException npe) {
3380                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3381                npe.printStackTrace();
3382            }
3383        } else {
3384            try {
3385                notificationManager.cancel(NOTIFICATION_ID, id);
3386            } catch (NullPointerException npe) {
3387                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3388                npe.printStackTrace();
3389            }
3390        }
3391    }
3392
3393    /** Location to an updatable file listing carrier provisioning urls.
3394     *  An example:
3395     *
3396     * <?xml version="1.0" encoding="utf-8"?>
3397     *  <provisioningUrls>
3398     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3399     *  </provisioningUrls>
3400     */
3401    private static final String PROVISIONING_URL_PATH =
3402            "/data/misc/radio/provisioning_urls.xml";
3403    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3404
3405    /** XML tag for root element. */
3406    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3407    /** XML tag for individual url */
3408    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3409    /** XML attribute for mcc */
3410    private static final String ATTR_MCC = "mcc";
3411    /** XML attribute for mnc */
3412    private static final String ATTR_MNC = "mnc";
3413
3414    private String getProvisioningUrlBaseFromFile() {
3415        FileReader fileReader = null;
3416        XmlPullParser parser = null;
3417        Configuration config = mContext.getResources().getConfiguration();
3418
3419        try {
3420            fileReader = new FileReader(mProvisioningUrlFile);
3421            parser = Xml.newPullParser();
3422            parser.setInput(fileReader);
3423            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3424
3425            while (true) {
3426                XmlUtils.nextElement(parser);
3427
3428                String element = parser.getName();
3429                if (element == null) break;
3430
3431                if (element.equals(TAG_PROVISIONING_URL)) {
3432                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3433                    try {
3434                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3435                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3436                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3437                                parser.next();
3438                                if (parser.getEventType() == XmlPullParser.TEXT) {
3439                                    return parser.getText();
3440                                }
3441                            }
3442                        }
3443                    } catch (NumberFormatException e) {
3444                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3445                    }
3446                }
3447            }
3448            return null;
3449        } catch (FileNotFoundException e) {
3450            loge("Carrier Provisioning Urls file not found");
3451        } catch (XmlPullParserException e) {
3452            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3453        } catch (IOException e) {
3454            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3455        } finally {
3456            if (fileReader != null) {
3457                try {
3458                    fileReader.close();
3459                } catch (IOException e) {}
3460            }
3461        }
3462        return null;
3463    }
3464
3465    @Override
3466    public String getMobileProvisioningUrl() {
3467        enforceConnectivityInternalPermission();
3468        String url = getProvisioningUrlBaseFromFile();
3469        if (TextUtils.isEmpty(url)) {
3470            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3471            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3472        } else {
3473            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3474        }
3475        // populate the iccid, imei and phone number in the provisioning url.
3476        if (!TextUtils.isEmpty(url)) {
3477            String phoneNumber = mTelephonyManager.getLine1Number();
3478            if (TextUtils.isEmpty(phoneNumber)) {
3479                phoneNumber = "0000000000";
3480            }
3481            url = String.format(url,
3482                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3483                    mTelephonyManager.getDeviceId() /* IMEI */,
3484                    phoneNumber /* Phone numer */);
3485        }
3486
3487        return url;
3488    }
3489
3490    @Override
3491    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3492            String action) {
3493        enforceConnectivityInternalPermission();
3494        final long ident = Binder.clearCallingIdentity();
3495        try {
3496            setProvNotificationVisible(visible, networkType, action);
3497        } finally {
3498            Binder.restoreCallingIdentity(ident);
3499        }
3500    }
3501
3502    @Override
3503    public void setAirplaneMode(boolean enable) {
3504        enforceConnectivityInternalPermission();
3505        final long ident = Binder.clearCallingIdentity();
3506        try {
3507            final ContentResolver cr = mContext.getContentResolver();
3508            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3509            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3510            intent.putExtra("state", enable);
3511            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3512        } finally {
3513            Binder.restoreCallingIdentity(ident);
3514        }
3515    }
3516
3517    private void onUserStart(int userId) {
3518        synchronized(mVpns) {
3519            Vpn userVpn = mVpns.get(userId);
3520            if (userVpn != null) {
3521                loge("Starting user already has a VPN");
3522                return;
3523            }
3524            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3525            mVpns.put(userId, userVpn);
3526        }
3527    }
3528
3529    private void onUserStop(int userId) {
3530        synchronized(mVpns) {
3531            Vpn userVpn = mVpns.get(userId);
3532            if (userVpn == null) {
3533                loge("Stopping user has no VPN");
3534                return;
3535            }
3536            mVpns.delete(userId);
3537        }
3538    }
3539
3540    private void onUserAdded(int userId) {
3541        synchronized(mVpns) {
3542            final int vpnsSize = mVpns.size();
3543            for (int i = 0; i < vpnsSize; i++) {
3544                Vpn vpn = mVpns.valueAt(i);
3545                vpn.onUserAdded(userId);
3546            }
3547        }
3548    }
3549
3550    private void onUserRemoved(int userId) {
3551        synchronized(mVpns) {
3552            final int vpnsSize = mVpns.size();
3553            for (int i = 0; i < vpnsSize; i++) {
3554                Vpn vpn = mVpns.valueAt(i);
3555                vpn.onUserRemoved(userId);
3556            }
3557        }
3558    }
3559
3560    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3561        @Override
3562        public void onReceive(Context context, Intent intent) {
3563            final String action = intent.getAction();
3564            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3565            if (userId == UserHandle.USER_NULL) return;
3566
3567            if (Intent.ACTION_USER_STARTING.equals(action)) {
3568                onUserStart(userId);
3569            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3570                onUserStop(userId);
3571            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3572                onUserAdded(userId);
3573            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3574                onUserRemoved(userId);
3575            }
3576        }
3577    };
3578
3579    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3580            new HashMap<Messenger, NetworkFactoryInfo>();
3581    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3582            new HashMap<NetworkRequest, NetworkRequestInfo>();
3583
3584    private static class NetworkFactoryInfo {
3585        public final String name;
3586        public final Messenger messenger;
3587        public final AsyncChannel asyncChannel;
3588
3589        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3590            this.name = name;
3591            this.messenger = messenger;
3592            this.asyncChannel = asyncChannel;
3593        }
3594    }
3595
3596    /**
3597     * Tracks info about the requester.
3598     * Also used to notice when the calling process dies so we can self-expire
3599     */
3600    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3601        static final boolean REQUEST = true;
3602        static final boolean LISTEN = false;
3603
3604        final NetworkRequest request;
3605        final PendingIntent mPendingIntent;
3606        boolean mPendingIntentSent;
3607        private final IBinder mBinder;
3608        final int mPid;
3609        final int mUid;
3610        final Messenger messenger;
3611        final boolean isRequest;
3612
3613        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3614            request = r;
3615            mPendingIntent = pi;
3616            messenger = null;
3617            mBinder = null;
3618            mPid = getCallingPid();
3619            mUid = getCallingUid();
3620            this.isRequest = isRequest;
3621        }
3622
3623        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3624            super();
3625            messenger = m;
3626            request = r;
3627            mBinder = binder;
3628            mPid = getCallingPid();
3629            mUid = getCallingUid();
3630            this.isRequest = isRequest;
3631            mPendingIntent = null;
3632
3633            try {
3634                mBinder.linkToDeath(this, 0);
3635            } catch (RemoteException e) {
3636                binderDied();
3637            }
3638        }
3639
3640        void unlinkDeathRecipient() {
3641            if (mBinder != null) {
3642                mBinder.unlinkToDeath(this, 0);
3643            }
3644        }
3645
3646        public void binderDied() {
3647            log("ConnectivityService NetworkRequestInfo binderDied(" +
3648                    request + ", " + mBinder + ")");
3649            releaseNetworkRequest(request);
3650        }
3651
3652        public String toString() {
3653            return (isRequest ? "Request" : "Listen") +
3654                    " from uid/pid:" + mUid + "/" + mPid +
3655                    " for " + request +
3656                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3657        }
3658    }
3659
3660    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3661        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3662        if (badCapability != null) {
3663            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3664        }
3665    }
3666
3667    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3668        final SortedSet<Integer> thresholds = new TreeSet();
3669        synchronized (nai) {
3670            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3671                if (nri.request.networkCapabilities.hasSignalStrength() &&
3672                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3673                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3674                }
3675            }
3676        }
3677        return new ArrayList<Integer>(thresholds);
3678    }
3679
3680    private void updateSignalStrengthThresholds(
3681            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3682        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3683        Bundle thresholds = new Bundle();
3684        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3685
3686        // TODO: Switch to VDBG.
3687        if (DBG) {
3688            String detail;
3689            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3690                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3691            } else {
3692                detail = reason;
3693            }
3694            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3695                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3696        }
3697
3698        nai.asyncChannel.sendMessage(
3699                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3700                0, 0, thresholds);
3701    }
3702
3703    @Override
3704    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3705            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3706        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3707        enforceNetworkRequestPermissions(networkCapabilities);
3708        enforceMeteredApnPolicy(networkCapabilities);
3709        ensureRequestableCapabilities(networkCapabilities);
3710
3711        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3712            throw new IllegalArgumentException("Bad timeout specified");
3713        }
3714
3715        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3716                nextNetworkRequestId());
3717        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3718                NetworkRequestInfo.REQUEST);
3719        if (DBG) log("requestNetwork for " + nri);
3720
3721        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3722        if (timeoutMs > 0) {
3723            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3724                    nri), timeoutMs);
3725        }
3726        return networkRequest;
3727    }
3728
3729    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3730        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
3731            enforceConnectivityInternalPermission();
3732        } else {
3733            enforceChangePermission();
3734        }
3735    }
3736
3737    @Override
3738    public boolean requestBandwidthUpdate(Network network) {
3739        enforceAccessPermission();
3740        NetworkAgentInfo nai = null;
3741        if (network == null) {
3742            return false;
3743        }
3744        synchronized (mNetworkForNetId) {
3745            nai = mNetworkForNetId.get(network.netId);
3746        }
3747        if (nai != null) {
3748            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3749            return true;
3750        }
3751        return false;
3752    }
3753
3754
3755    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3756        // if UID is restricted, don't allow them to bring up metered APNs
3757        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
3758            final int uidRules;
3759            final int uid = Binder.getCallingUid();
3760            synchronized(mRulesLock) {
3761                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3762            }
3763            if (uidRules != RULE_ALLOW_ALL) {
3764                // we could silently fail or we can filter the available nets to only give
3765                // them those they have access to.  Chose the more useful
3766                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
3767            }
3768        }
3769    }
3770
3771    @Override
3772    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3773            PendingIntent operation) {
3774        checkNotNull(operation, "PendingIntent cannot be null.");
3775        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3776        enforceNetworkRequestPermissions(networkCapabilities);
3777        enforceMeteredApnPolicy(networkCapabilities);
3778        ensureRequestableCapabilities(networkCapabilities);
3779
3780        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3781                nextNetworkRequestId());
3782        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3783                NetworkRequestInfo.REQUEST);
3784        if (DBG) log("pendingRequest for " + nri);
3785        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3786                nri));
3787        return networkRequest;
3788    }
3789
3790    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3791        mHandler.sendMessageDelayed(
3792                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3793                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3794    }
3795
3796    @Override
3797    public void releasePendingNetworkRequest(PendingIntent operation) {
3798        checkNotNull(operation, "PendingIntent cannot be null.");
3799        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3800                getCallingUid(), 0, operation));
3801    }
3802
3803    // In order to implement the compatibility measure for pre-M apps that call
3804    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3805    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3806    // This ensures it has permission to do so.
3807    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3808        if (nc == null) {
3809            return false;
3810        }
3811        int[] transportTypes = nc.getTransportTypes();
3812        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3813            return false;
3814        }
3815        try {
3816            mContext.enforceCallingOrSelfPermission(
3817                    android.Manifest.permission.ACCESS_WIFI_STATE,
3818                    "ConnectivityService");
3819        } catch (SecurityException e) {
3820            return false;
3821        }
3822        return true;
3823    }
3824
3825    @Override
3826    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3827            Messenger messenger, IBinder binder) {
3828        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3829            enforceAccessPermission();
3830        }
3831
3832        NetworkRequest networkRequest = new NetworkRequest(
3833                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3834        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3835                NetworkRequestInfo.LISTEN);
3836        if (DBG) log("listenForNetwork for " + nri);
3837
3838        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3839        return networkRequest;
3840    }
3841
3842    @Override
3843    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3844            PendingIntent operation) {
3845        checkNotNull(operation, "PendingIntent cannot be null.");
3846        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3847            enforceAccessPermission();
3848        }
3849
3850        NetworkRequest networkRequest = new NetworkRequest(
3851                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3852        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3853                NetworkRequestInfo.LISTEN);
3854        if (DBG) log("pendingListenForNetwork for " + nri);
3855
3856        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3857    }
3858
3859    @Override
3860    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3861        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3862                0, networkRequest));
3863    }
3864
3865    @Override
3866    public void registerNetworkFactory(Messenger messenger, String name) {
3867        enforceConnectivityInternalPermission();
3868        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3869        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3870    }
3871
3872    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3873        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3874        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3875        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3876    }
3877
3878    @Override
3879    public void unregisterNetworkFactory(Messenger messenger) {
3880        enforceConnectivityInternalPermission();
3881        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3882    }
3883
3884    private void handleUnregisterNetworkFactory(Messenger messenger) {
3885        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3886        if (nfi == null) {
3887            loge("Failed to find Messenger in unregisterNetworkFactory");
3888            return;
3889        }
3890        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3891    }
3892
3893    /**
3894     * NetworkAgentInfo supporting a request by requestId.
3895     * These have already been vetted (their Capabilities satisfy the request)
3896     * and the are the highest scored network available.
3897     * the are keyed off the Requests requestId.
3898     */
3899    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3900    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3901            new SparseArray<NetworkAgentInfo>();
3902
3903    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3904    @GuardedBy("mNetworkForNetId")
3905    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3906            new SparseArray<NetworkAgentInfo>();
3907    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3908    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3909    // there may not be a strict 1:1 correlation between the two.
3910    @GuardedBy("mNetworkForNetId")
3911    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3912
3913    // NetworkAgentInfo keyed off its connecting messenger
3914    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3915    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3916    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3917            new HashMap<Messenger, NetworkAgentInfo>();
3918
3919    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3920    private final NetworkRequest mDefaultRequest;
3921
3922    // Request used to optionally keep mobile data active even when higher
3923    // priority networks like Wi-Fi are active.
3924    private final NetworkRequest mDefaultMobileDataRequest;
3925
3926    private NetworkAgentInfo getDefaultNetwork() {
3927        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3928    }
3929
3930    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3931        return nai == getDefaultNetwork();
3932    }
3933
3934    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3935            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3936            int currentScore, NetworkMisc networkMisc) {
3937        enforceConnectivityInternalPermission();
3938
3939        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3940        // satisfies mDefaultRequest.
3941        final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3942                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3943                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3944                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
3945        synchronized (this) {
3946            nai.networkMonitor.systemReady = mSystemReady;
3947        }
3948        addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
3949        if (DBG) log("registerNetworkAgent " + nai);
3950        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3951        return nai.network.netId;
3952    }
3953
3954    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3955        if (VDBG) log("Got NetworkAgent Messenger");
3956        mNetworkAgentInfos.put(na.messenger, na);
3957        synchronized (mNetworkForNetId) {
3958            mNetworkForNetId.put(na.network.netId, na);
3959        }
3960        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3961        NetworkInfo networkInfo = na.networkInfo;
3962        na.networkInfo = null;
3963        updateNetworkInfo(na, networkInfo);
3964    }
3965
3966    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3967        LinkProperties newLp = networkAgent.linkProperties;
3968        int netId = networkAgent.network.netId;
3969
3970        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3971        // we do anything else, make sure its LinkProperties are accurate.
3972        if (networkAgent.clatd != null) {
3973            networkAgent.clatd.fixupLinkProperties(oldLp);
3974        }
3975
3976        updateInterfaces(newLp, oldLp, netId);
3977        updateMtu(newLp, oldLp);
3978        // TODO - figure out what to do for clat
3979//        for (LinkProperties lp : newLp.getStackedLinks()) {
3980//            updateMtu(lp, null);
3981//        }
3982        updateTcpBufferSizes(networkAgent);
3983
3984        // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3985        // In L, we used it only when the network had Internet access but provided no DNS servers.
3986        // For now, just disable it, and if disabling it doesn't break things, remove it.
3987        // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3988        //        NET_CAPABILITY_INTERNET);
3989        final boolean useDefaultDns = false;
3990        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3991        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3992
3993        updateClat(newLp, oldLp, networkAgent);
3994        if (isDefaultNetwork(networkAgent)) {
3995            handleApplyDefaultProxy(newLp.getHttpProxy());
3996        } else {
3997            updateProxy(newLp, oldLp, networkAgent);
3998        }
3999        // TODO - move this check to cover the whole function
4000        if (!Objects.equals(newLp, oldLp)) {
4001            notifyIfacesChanged();
4002            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4003        }
4004
4005        mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
4006    }
4007
4008    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4009        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4010        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
4011
4012        if (!wasRunningClat && shouldRunClat) {
4013            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4014            nai.clatd.start();
4015        } else if (wasRunningClat && !shouldRunClat) {
4016            nai.clatd.stop();
4017        }
4018    }
4019
4020    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4021        CompareResult<String> interfaceDiff = new CompareResult<String>();
4022        if (oldLp != null) {
4023            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4024        } else if (newLp != null) {
4025            interfaceDiff.added = newLp.getAllInterfaceNames();
4026        }
4027        for (String iface : interfaceDiff.added) {
4028            try {
4029                if (DBG) log("Adding iface " + iface + " to network " + netId);
4030                mNetd.addInterfaceToNetwork(iface, netId);
4031            } catch (Exception e) {
4032                loge("Exception adding interface: " + e);
4033            }
4034        }
4035        for (String iface : interfaceDiff.removed) {
4036            try {
4037                if (DBG) log("Removing iface " + iface + " from network " + netId);
4038                mNetd.removeInterfaceFromNetwork(iface, netId);
4039            } catch (Exception e) {
4040                loge("Exception removing interface: " + e);
4041            }
4042        }
4043    }
4044
4045    /**
4046     * Have netd update routes from oldLp to newLp.
4047     * @return true if routes changed between oldLp and newLp
4048     */
4049    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4050        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4051        if (oldLp != null) {
4052            routeDiff = oldLp.compareAllRoutes(newLp);
4053        } else if (newLp != null) {
4054            routeDiff.added = newLp.getAllRoutes();
4055        }
4056
4057        // add routes before removing old in case it helps with continuous connectivity
4058
4059        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4060        for (RouteInfo route : routeDiff.added) {
4061            if (route.hasGateway()) continue;
4062            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4063            try {
4064                mNetd.addRoute(netId, route);
4065            } catch (Exception e) {
4066                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4067                    loge("Exception in addRoute for non-gateway: " + e);
4068                }
4069            }
4070        }
4071        for (RouteInfo route : routeDiff.added) {
4072            if (route.hasGateway() == false) continue;
4073            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4074            try {
4075                mNetd.addRoute(netId, route);
4076            } catch (Exception e) {
4077                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4078                    loge("Exception in addRoute for gateway: " + e);
4079                }
4080            }
4081        }
4082
4083        for (RouteInfo route : routeDiff.removed) {
4084            if (DBG) log("Removing Route [" + route + "] from network " + netId);
4085            try {
4086                mNetd.removeRoute(netId, route);
4087            } catch (Exception e) {
4088                loge("Exception in removeRoute: " + e);
4089            }
4090        }
4091        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4092    }
4093
4094    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4095                             boolean flush, boolean useDefaultDns) {
4096        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4097            Collection<InetAddress> dnses = newLp.getDnsServers();
4098            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
4099                dnses = new ArrayList();
4100                dnses.add(mDefaultDns);
4101                if (DBG) {
4102                    loge("no dns provided for netId " + netId + ", so using defaults");
4103                }
4104            }
4105            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4106            try {
4107                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4108                    newLp.getDomains());
4109            } catch (Exception e) {
4110                loge("Exception in setDnsServersForNetwork: " + e);
4111            }
4112            final NetworkAgentInfo defaultNai = getDefaultNetwork();
4113            if (defaultNai != null && defaultNai.network.netId == netId) {
4114                setDefaultDnsSystemProperties(dnses);
4115            }
4116            flushVmDnsCache();
4117        } else if (flush) {
4118            try {
4119                mNetd.flushNetworkDnsCache(netId);
4120            } catch (Exception e) {
4121                loge("Exception in flushNetworkDnsCache: " + e);
4122            }
4123            flushVmDnsCache();
4124        }
4125    }
4126
4127    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4128        int last = 0;
4129        for (InetAddress dns : dnses) {
4130            ++last;
4131            String key = "net.dns" + last;
4132            String value = dns.getHostAddress();
4133            SystemProperties.set(key, value);
4134        }
4135        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4136            String key = "net.dns" + i;
4137            SystemProperties.set(key, "");
4138        }
4139        mNumDnsEntries = last;
4140    }
4141
4142    /**
4143     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4144     * augmented with any stateful capabilities implied from {@code networkAgent}
4145     * (e.g., validated status and captive portal status).
4146     *
4147     * @param nai the network having its capabilities updated.
4148     * @param networkCapabilities the new network capabilities.
4149     */
4150    private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
4151        // Don't modify caller's NetworkCapabilities.
4152        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4153        if (nai.lastValidated) {
4154            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4155        } else {
4156            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4157        }
4158        if (nai.lastCaptivePortalDetected) {
4159            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4160        } else {
4161            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4162        }
4163        if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4164            final int oldScore = nai.getCurrentScore();
4165            if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4166                    networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4167                try {
4168                    mNetd.setNetworkPermission(nai.network.netId,
4169                            networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4170                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4171                } catch (RemoteException e) {
4172                    loge("Exception in setNetworkPermission: " + e);
4173                }
4174            }
4175            synchronized (nai) {
4176                nai.networkCapabilities = networkCapabilities;
4177            }
4178            rematchAllNetworksAndRequests(nai, oldScore);
4179            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4180        }
4181    }
4182
4183    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4184        for (int i = 0; i < nai.networkRequests.size(); i++) {
4185            NetworkRequest nr = nai.networkRequests.valueAt(i);
4186            // Don't send listening requests to factories. b/17393458
4187            if (!isRequest(nr)) continue;
4188            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4189        }
4190    }
4191
4192    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4193        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4194        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4195            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4196                    networkRequest);
4197        }
4198    }
4199
4200    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4201            int notificationType) {
4202        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4203            Intent intent = new Intent();
4204            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4205            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4206            nri.mPendingIntentSent = true;
4207            sendIntent(nri.mPendingIntent, intent);
4208        }
4209        // else not handled
4210    }
4211
4212    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4213        mPendingIntentWakeLock.acquire();
4214        try {
4215            if (DBG) log("Sending " + pendingIntent);
4216            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4217        } catch (PendingIntent.CanceledException e) {
4218            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4219            mPendingIntentWakeLock.release();
4220            releasePendingNetworkRequest(pendingIntent);
4221        }
4222        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4223    }
4224
4225    @Override
4226    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4227            String resultData, Bundle resultExtras) {
4228        if (DBG) log("Finished sending " + pendingIntent);
4229        mPendingIntentWakeLock.release();
4230        // Release with a delay so the receiving client has an opportunity to put in its
4231        // own request.
4232        releasePendingNetworkRequestWithDelay(pendingIntent);
4233    }
4234
4235    private void callCallbackForRequest(NetworkRequestInfo nri,
4236            NetworkAgentInfo networkAgent, int notificationType) {
4237        if (nri.messenger == null) return;  // Default request has no msgr
4238        Bundle bundle = new Bundle();
4239        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4240                new NetworkRequest(nri.request));
4241        Message msg = Message.obtain();
4242        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4243                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4244            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4245        }
4246        switch (notificationType) {
4247            case ConnectivityManager.CALLBACK_LOSING: {
4248                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4249                break;
4250            }
4251            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4252                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4253                        new NetworkCapabilities(networkAgent.networkCapabilities));
4254                break;
4255            }
4256            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4257                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4258                        new LinkProperties(networkAgent.linkProperties));
4259                break;
4260            }
4261        }
4262        msg.what = notificationType;
4263        msg.setData(bundle);
4264        try {
4265            if (VDBG) {
4266                log("sending notification " + notifyTypeToName(notificationType) +
4267                        " for " + nri.request);
4268            }
4269            nri.messenger.send(msg);
4270        } catch (RemoteException e) {
4271            // may occur naturally in the race of binder death.
4272            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4273        }
4274    }
4275
4276    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4277        for (int i = 0; i < nai.networkRequests.size(); i++) {
4278            NetworkRequest nr = nai.networkRequests.valueAt(i);
4279            // Ignore listening requests.
4280            if (!isRequest(nr)) continue;
4281            loge("Dead network still had at least " + nr);
4282            break;
4283        }
4284        nai.asyncChannel.disconnect();
4285    }
4286
4287    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4288        if (oldNetwork == null) {
4289            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4290            return;
4291        }
4292        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4293        teardownUnneededNetwork(oldNetwork);
4294    }
4295
4296    private void makeDefault(NetworkAgentInfo newNetwork) {
4297        if (DBG) log("Switching to new default network: " + newNetwork);
4298        setupDataActivityTracking(newNetwork);
4299        try {
4300            mNetd.setDefaultNetId(newNetwork.network.netId);
4301        } catch (Exception e) {
4302            loge("Exception setting default network :" + e);
4303        }
4304        notifyLockdownVpn(newNetwork);
4305        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4306        updateTcpBufferSizes(newNetwork);
4307        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4308    }
4309
4310    // Handles a network appearing or improving its score.
4311    //
4312    // - Evaluates all current NetworkRequests that can be
4313    //   satisfied by newNetwork, and reassigns to newNetwork
4314    //   any such requests for which newNetwork is the best.
4315    //
4316    // - Lingers any validated Networks that as a result are no longer
4317    //   needed. A network is needed if it is the best network for
4318    //   one or more NetworkRequests, or if it is a VPN.
4319    //
4320    // - Tears down newNetwork if it just became validated
4321    //   but turns out to be unneeded.
4322    //
4323    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4324    //   networks that have no chance (i.e. even if validated)
4325    //   of becoming the highest scoring network.
4326    //
4327    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4328    // it does not remove NetworkRequests that other Networks could better satisfy.
4329    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4330    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4331    // as it performs better by a factor of the number of Networks.
4332    //
4333    // @param newNetwork is the network to be matched against NetworkRequests.
4334    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4335    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4336    //               validated) of becoming the highest scoring network.
4337    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
4338            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4339        if (!newNetwork.created) return;
4340        boolean keep = newNetwork.isVPN();
4341        boolean isNewDefault = false;
4342        NetworkAgentInfo oldDefaultNetwork = null;
4343        if (VDBG) log("rematching " + newNetwork.name());
4344        // Find and migrate to this Network any NetworkRequests for
4345        // which this network is now the best.
4346        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4347        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4348        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4349        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4350            final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4351            final boolean satisfies = newNetwork.satisfies(nri.request);
4352            if (newNetwork == currentNetwork && satisfies) {
4353                if (VDBG) {
4354                    log("Network " + newNetwork.name() + " was already satisfying" +
4355                            " request " + nri.request.requestId + ". No change.");
4356                }
4357                keep = true;
4358                continue;
4359            }
4360
4361            // check if it satisfies the NetworkCapabilities
4362            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4363            if (satisfies) {
4364                if (!nri.isRequest) {
4365                    // This is not a request, it's a callback listener.
4366                    // Add it to newNetwork regardless of score.
4367                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4368                    continue;
4369                }
4370
4371                // next check if it's better than any current network we're using for
4372                // this request
4373                if (VDBG) {
4374                    log("currentScore = " +
4375                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4376                            ", newScore = " + newNetwork.getCurrentScore());
4377                }
4378                if (currentNetwork == null ||
4379                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4380                    if (DBG) log("rematch for " + newNetwork.name());
4381                    if (currentNetwork != null) {
4382                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4383                        currentNetwork.networkRequests.remove(nri.request.requestId);
4384                        currentNetwork.networkLingered.add(nri.request);
4385                        affectedNetworks.add(currentNetwork);
4386                    } else {
4387                        if (DBG) log("   accepting network in place of null");
4388                    }
4389                    unlinger(newNetwork);
4390                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4391                    if (!newNetwork.addRequest(nri.request)) {
4392                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4393                    }
4394                    addedRequests.add(nri);
4395                    keep = true;
4396                    // Tell NetworkFactories about the new score, so they can stop
4397                    // trying to connect if they know they cannot match it.
4398                    // TODO - this could get expensive if we have alot of requests for this
4399                    // network.  Think about if there is a way to reduce this.  Push
4400                    // netid->request mapping to each factory?
4401                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4402                    if (mDefaultRequest.requestId == nri.request.requestId) {
4403                        isNewDefault = true;
4404                        oldDefaultNetwork = currentNetwork;
4405                    }
4406                }
4407            } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4408                // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4409                // mark it as no longer satisfying "nri".  Because networks are processed by
4410                // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4411                // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4412                // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4413                // This means this code doesn't have to handle the case where "currentNetwork" no
4414                // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4415                if (DBG) {
4416                    log("Network " + newNetwork.name() + " stopped satisfying" +
4417                            " request " + nri.request.requestId);
4418                }
4419                newNetwork.networkRequests.remove(nri.request.requestId);
4420                if (currentNetwork == newNetwork) {
4421                    mNetworkForRequestId.remove(nri.request.requestId);
4422                    sendUpdatedScoreToFactories(nri.request, 0);
4423                } else {
4424                    if (nri.isRequest == true) {
4425                        Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4426                                newNetwork.name() +
4427                                " without updating mNetworkForRequestId or factories!");
4428                    }
4429                }
4430                // TODO: technically, sending CALLBACK_LOST here is
4431                // incorrect if nri is a request (not a listen) and there
4432                // is a replacement network currently connected that can
4433                // satisfy it. However, the only capability that can both
4434                // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4435                // so this code is only incorrect for a network that loses
4436                // the TRUSTED capability, which is a rare case.
4437                callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
4438            }
4439        }
4440        // Linger any networks that are no longer needed.
4441        for (NetworkAgentInfo nai : affectedNetworks) {
4442            if (nai.lingering) {
4443                // Already lingered.  Nothing to do.  This can only happen if "nai" is in
4444                // "affectedNetworks" twice.  The reasoning being that to get added to
4445                // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4446                // (i.e. not lingered) so it could have only been lingered by this loop.
4447                // unneeded(nai) will be false and we'll call unlinger() below which would
4448                // be bad, so handle it here.
4449            } else if (unneeded(nai)) {
4450                linger(nai);
4451            } else {
4452                // Clear nai.networkLingered we might have added above.
4453                unlinger(nai);
4454            }
4455        }
4456        if (isNewDefault) {
4457            // Notify system services that this network is up.
4458            makeDefault(newNetwork);
4459            synchronized (ConnectivityService.this) {
4460                // have a new default network, release the transition wakelock in
4461                // a second if it's held.  The second pause is to allow apps
4462                // to reconnect over the new network
4463                if (mNetTransitionWakeLock.isHeld()) {
4464                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
4465                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4466                            mNetTransitionWakeLockSerialNumber, 0),
4467                            1000);
4468                }
4469            }
4470        }
4471
4472        // do this after the default net is switched, but
4473        // before LegacyTypeTracker sends legacy broadcasts
4474        for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4475
4476        if (isNewDefault) {
4477            // Maintain the illusion: since the legacy API only
4478            // understands one network at a time, we must pretend
4479            // that the current default network disconnected before
4480            // the new one connected.
4481            if (oldDefaultNetwork != null) {
4482                mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4483                                          oldDefaultNetwork, true);
4484            }
4485            mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4486            mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4487            notifyLockdownVpn(newNetwork);
4488        }
4489
4490        if (keep) {
4491            // Notify battery stats service about this network, both the normal
4492            // interface and any stacked links.
4493            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4494            try {
4495                final IBatteryStats bs = BatteryStatsService.getService();
4496                final int type = newNetwork.networkInfo.getType();
4497
4498                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4499                bs.noteNetworkInterfaceType(baseIface, type);
4500                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4501                    final String stackedIface = stacked.getInterfaceName();
4502                    bs.noteNetworkInterfaceType(stackedIface, type);
4503                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4504                }
4505            } catch (RemoteException ignored) {
4506            }
4507
4508            // This has to happen after the notifyNetworkCallbacks as that tickles each
4509            // ConnectivityManager instance so that legacy requests correctly bind dns
4510            // requests to this network.  The legacy users are listening for this bcast
4511            // and will generally do a dns request so they can ensureRouteToHost and if
4512            // they do that before the callbacks happen they'll use the default network.
4513            //
4514            // TODO: Is there still a race here? We send the broadcast
4515            // after sending the callback, but if the app can receive the
4516            // broadcast before the callback, it might still break.
4517            //
4518            // This *does* introduce a race where if the user uses the new api
4519            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4520            // they may get old info.  Reverse this after the old startUsing api is removed.
4521            // This is on top of the multiple intent sequencing referenced in the todo above.
4522            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4523                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4524                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4525                    // legacy type tracker filters out repeat adds
4526                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4527                }
4528            }
4529
4530            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4531            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4532            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4533            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4534            if (newNetwork.isVPN()) {
4535                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4536            }
4537        }
4538        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4539            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4540                if (unneeded(nai)) {
4541                    if (DBG) log("Reaping " + nai.name());
4542                    teardownUnneededNetwork(nai);
4543                }
4544            }
4545        }
4546    }
4547
4548    /**
4549     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4550     * being disconnected.
4551     * @param changed If only one Network's score or capabilities have been modified since the last
4552     *         time this function was called, pass this Network in this argument, otherwise pass
4553     *         null.
4554     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4555     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4556     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4557     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4558     *         network's score.
4559     */
4560    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4561        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4562        // to avoid the slowness.  It is not simply enough to process just "changed", for
4563        // example in the case where "changed"'s score decreases and another network should begin
4564        // satifying a NetworkRequest that "changed" currently satisfies.
4565
4566        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4567        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4568        // rematchNetworkAndRequests() handles.
4569        if (changed != null && oldScore < changed.getCurrentScore()) {
4570            rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
4571        } else {
4572            final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4573                    new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4574            // Rematch higher scoring networks first to prevent requests first matching a lower
4575            // scoring network and then a higher scoring network, which could produce multiple
4576            // callbacks and inadvertently unlinger networks.
4577            Arrays.sort(nais);
4578            for (NetworkAgentInfo nai : nais) {
4579                rematchNetworkAndRequests(nai,
4580                        // Only reap the last time through the loop.  Reaping before all rematching
4581                        // is complete could incorrectly teardown a network that hasn't yet been
4582                        // rematched.
4583                        (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
4584                                : ReapUnvalidatedNetworks.REAP);
4585            }
4586        }
4587    }
4588
4589    private void updateInetCondition(NetworkAgentInfo nai) {
4590        // Don't bother updating until we've graduated to validated at least once.
4591        if (!nai.everValidated) return;
4592        // For now only update icons for default connection.
4593        // TODO: Update WiFi and cellular icons separately. b/17237507
4594        if (!isDefaultNetwork(nai)) return;
4595
4596        int newInetCondition = nai.lastValidated ? 100 : 0;
4597        // Don't repeat publish.
4598        if (newInetCondition == mDefaultInetConditionPublished) return;
4599
4600        mDefaultInetConditionPublished = newInetCondition;
4601        sendInetConditionBroadcast(nai.networkInfo);
4602    }
4603
4604    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4605        if (mLockdownTracker != null) {
4606            if (nai != null && nai.isVPN()) {
4607                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4608            } else {
4609                mLockdownTracker.onNetworkInfoChanged();
4610            }
4611        }
4612    }
4613
4614    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4615        NetworkInfo.State state = newInfo.getState();
4616        NetworkInfo oldInfo = null;
4617        final int oldScore = networkAgent.getCurrentScore();
4618        synchronized (networkAgent) {
4619            oldInfo = networkAgent.networkInfo;
4620            networkAgent.networkInfo = newInfo;
4621        }
4622        notifyLockdownVpn(networkAgent);
4623
4624        if (oldInfo != null && oldInfo.getState() == state) {
4625            if (VDBG) log("ignoring duplicate network state non-change");
4626            return;
4627        }
4628        if (DBG) {
4629            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4630                    (oldInfo == null ? "null" : oldInfo.getState()) +
4631                    " to " + state);
4632        }
4633
4634        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4635            try {
4636                // This should never fail.  Specifying an already in use NetID will cause failure.
4637                if (networkAgent.isVPN()) {
4638                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4639                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4640                            (networkAgent.networkMisc == null ||
4641                                !networkAgent.networkMisc.allowBypass));
4642                } else {
4643                    mNetd.createPhysicalNetwork(networkAgent.network.netId,
4644                            networkAgent.networkCapabilities.hasCapability(
4645                                    NET_CAPABILITY_NOT_RESTRICTED) ?
4646                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4647                }
4648            } catch (Exception e) {
4649                loge("Error creating network " + networkAgent.network.netId + ": "
4650                        + e.getMessage());
4651                return;
4652            }
4653            networkAgent.created = true;
4654            updateLinkProperties(networkAgent, null);
4655            notifyIfacesChanged();
4656
4657            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4658            scheduleUnvalidatedPrompt(networkAgent);
4659
4660            if (networkAgent.isVPN()) {
4661                // Temporarily disable the default proxy (not global).
4662                synchronized (mProxyLock) {
4663                    if (!mDefaultProxyDisabled) {
4664                        mDefaultProxyDisabled = true;
4665                        if (mGlobalProxy == null && mDefaultProxy != null) {
4666                            sendProxyBroadcast(null);
4667                        }
4668                    }
4669                }
4670                // TODO: support proxy per network.
4671            }
4672
4673            // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4674            // be communicated to a particular NetworkAgent depends only on the network's immutable,
4675            // capabilities, so it only needs to be done once on initial connect, not every time the
4676            // network's capabilities change. Note that we do this before rematching the network,
4677            // so we could decide to tear it down immediately afterwards. That's fine though - on
4678            // disconnection NetworkAgents should stop any signal strength monitoring they have been
4679            // doing.
4680            updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
4681
4682            // Consider network even though it is not yet validated.
4683            rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
4684
4685            // This has to happen after matching the requests, because callbacks are just requests.
4686            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4687        } else if (state == NetworkInfo.State.DISCONNECTED) {
4688            networkAgent.asyncChannel.disconnect();
4689            if (networkAgent.isVPN()) {
4690                synchronized (mProxyLock) {
4691                    if (mDefaultProxyDisabled) {
4692                        mDefaultProxyDisabled = false;
4693                        if (mGlobalProxy == null && mDefaultProxy != null) {
4694                            sendProxyBroadcast(mDefaultProxy);
4695                        }
4696                    }
4697                }
4698            }
4699        } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4700                state == NetworkInfo.State.SUSPENDED) {
4701            // going into or coming out of SUSPEND: rescore and notify
4702            if (networkAgent.getCurrentScore() != oldScore) {
4703                rematchAllNetworksAndRequests(networkAgent, oldScore);
4704            }
4705            notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4706                    ConnectivityManager.CALLBACK_SUSPENDED :
4707                    ConnectivityManager.CALLBACK_RESUMED));
4708            mLegacyTypeTracker.update(networkAgent);
4709        }
4710    }
4711
4712    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4713        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4714        if (score < 0) {
4715            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4716                    ").  Bumping score to min of 0");
4717            score = 0;
4718        }
4719
4720        final int oldScore = nai.getCurrentScore();
4721        nai.setCurrentScore(score);
4722
4723        rematchAllNetworksAndRequests(nai, oldScore);
4724
4725        sendUpdatedScoreToFactories(nai);
4726    }
4727
4728    // notify only this one new request of the current state
4729    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4730        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4731        // TODO - read state from monitor to decide what to send.
4732//        if (nai.networkMonitor.isLingering()) {
4733//            notifyType = NetworkCallbacks.LOSING;
4734//        } else if (nai.networkMonitor.isEvaluating()) {
4735//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4736//        }
4737        if (nri.mPendingIntent == null) {
4738            callCallbackForRequest(nri, nai, notifyType);
4739        } else {
4740            sendPendingIntentForRequest(nri, nai, notifyType);
4741        }
4742    }
4743
4744    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
4745        // The NetworkInfo we actually send out has no bearing on the real
4746        // state of affairs. For example, if the default connection is mobile,
4747        // and a request for HIPRI has just gone away, we need to pretend that
4748        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4749        // the state to DISCONNECTED, even though the network is of type MOBILE
4750        // and is still connected.
4751        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4752        info.setType(type);
4753        if (state != DetailedState.DISCONNECTED) {
4754            info.setDetailedState(state, null, info.getExtraInfo());
4755            sendConnectedBroadcast(info);
4756        } else {
4757            info.setDetailedState(state, info.getReason(), info.getExtraInfo());
4758            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4759            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4760            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4761            if (info.isFailover()) {
4762                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4763                nai.networkInfo.setFailover(false);
4764            }
4765            if (info.getReason() != null) {
4766                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4767            }
4768            if (info.getExtraInfo() != null) {
4769                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4770            }
4771            NetworkAgentInfo newDefaultAgent = null;
4772            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4773                newDefaultAgent = getDefaultNetwork();
4774                if (newDefaultAgent != null) {
4775                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4776                            newDefaultAgent.networkInfo);
4777                } else {
4778                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4779                }
4780            }
4781            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4782                    mDefaultInetConditionPublished);
4783            sendStickyBroadcast(intent);
4784            if (newDefaultAgent != null) {
4785                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4786            }
4787        }
4788    }
4789
4790    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4791        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4792        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4793            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4794            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4795            if (VDBG) log(" sending notification for " + nr);
4796            if (nri.mPendingIntent == null) {
4797                callCallbackForRequest(nri, networkAgent, notifyType);
4798            } else {
4799                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4800            }
4801        }
4802    }
4803
4804    private String notifyTypeToName(int notifyType) {
4805        switch (notifyType) {
4806            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4807            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4808            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4809            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4810            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4811            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4812            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4813            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4814        }
4815        return "UNKNOWN";
4816    }
4817
4818    /**
4819     * Notify other system services that set of active ifaces has changed.
4820     */
4821    private void notifyIfacesChanged() {
4822        try {
4823            mStatsService.forceUpdateIfaces();
4824        } catch (Exception ignored) {
4825        }
4826    }
4827
4828    @Override
4829    public boolean addVpnAddress(String address, int prefixLength) {
4830        throwIfLockdownEnabled();
4831        int user = UserHandle.getUserId(Binder.getCallingUid());
4832        synchronized (mVpns) {
4833            return mVpns.get(user).addAddress(address, prefixLength);
4834        }
4835    }
4836
4837    @Override
4838    public boolean removeVpnAddress(String address, int prefixLength) {
4839        throwIfLockdownEnabled();
4840        int user = UserHandle.getUserId(Binder.getCallingUid());
4841        synchronized (mVpns) {
4842            return mVpns.get(user).removeAddress(address, prefixLength);
4843        }
4844    }
4845
4846    @Override
4847    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4848        throwIfLockdownEnabled();
4849        int user = UserHandle.getUserId(Binder.getCallingUid());
4850        boolean success;
4851        synchronized (mVpns) {
4852            success = mVpns.get(user).setUnderlyingNetworks(networks);
4853        }
4854        if (success) {
4855            notifyIfacesChanged();
4856        }
4857        return success;
4858    }
4859
4860    @Override
4861    public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4862            IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4863        enforceKeepalivePermission();
4864        mKeepaliveTracker.startNattKeepalive(
4865                getNetworkAgentInfoForNetwork(network),
4866                intervalSeconds, messenger, binder,
4867                srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4868    }
4869
4870    @Override
4871    public void stopKeepalive(Network network, int slot) {
4872        mHandler.sendMessage(mHandler.obtainMessage(
4873                NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4874    }
4875
4876    @Override
4877    public void factoryReset() {
4878        enforceConnectivityInternalPermission();
4879
4880        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4881            return;
4882        }
4883
4884        final int userId = UserHandle.getCallingUserId();
4885
4886        // Turn airplane mode off
4887        setAirplaneMode(false);
4888
4889        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4890            // Untether
4891            for (String tether : getTetheredIfaces()) {
4892                untether(tether);
4893            }
4894        }
4895
4896        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4897            // Turn VPN off
4898            VpnConfig vpnConfig = getVpnConfig(userId);
4899            if (vpnConfig != null) {
4900                if (vpnConfig.legacy) {
4901                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4902                } else {
4903                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4904                    // in the future without user intervention.
4905                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
4906
4907                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4908                }
4909            }
4910        }
4911    }
4912
4913    @VisibleForTesting
4914    public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4915            NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4916        return new NetworkMonitor(context, handler, nai, defaultRequest);
4917    }
4918
4919}
4920