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