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