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