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