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