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