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