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