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