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