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