/services/core/java/com/android/server/ConnectivityService.java

https://github.com/android/platform_frameworks_base · Java · 5779 lines · 4315 code · 603 blank · 861 comment · 1045 complexity · 1ef65e9554cdaf17bb6b75fc1136f041 MD5 · raw file

Large files are truncated click here to view the full file

  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. package com.android.server;
  17. import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
  18. import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
  19. import static android.net.ConnectivityManager.NETID_UNSET;
  20. import static android.net.ConnectivityManager.TYPE_ETHERNET;
  21. import static android.net.ConnectivityManager.TYPE_NONE;
  22. import static android.net.ConnectivityManager.TYPE_VPN;
  23. import static android.net.ConnectivityManager.getNetworkTypeName;
  24. import static android.net.ConnectivityManager.isNetworkTypeValid;
  25. import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
  26. import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
  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_NOT_ROAMING;
  31. import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
  32. import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
  33. import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
  34. import static android.net.NetworkCapabilities.TRANSPORT_VPN;
  35. import static com.android.internal.util.Preconditions.checkNotNull;
  36. import android.annotation.Nullable;
  37. import android.app.BroadcastOptions;
  38. import android.app.NotificationManager;
  39. import android.app.PendingIntent;
  40. import android.content.BroadcastReceiver;
  41. import android.content.ContentResolver;
  42. import android.content.Context;
  43. import android.content.Intent;
  44. import android.content.IntentFilter;
  45. import android.content.res.Configuration;
  46. import android.database.ContentObserver;
  47. import android.net.ConnectivityManager;
  48. import android.net.ConnectivityManager.PacketKeepalive;
  49. import android.net.IConnectivityManager;
  50. import android.net.INetworkManagementEventObserver;
  51. import android.net.INetworkPolicyListener;
  52. import android.net.INetworkPolicyManager;
  53. import android.net.INetworkStatsService;
  54. import android.net.LinkProperties;
  55. import android.net.LinkProperties.CompareResult;
  56. import android.net.MatchAllNetworkSpecifier;
  57. import android.net.Network;
  58. import android.net.NetworkAgent;
  59. import android.net.NetworkCapabilities;
  60. import android.net.NetworkConfig;
  61. import android.net.NetworkInfo;
  62. import android.net.NetworkInfo.DetailedState;
  63. import android.net.NetworkMisc;
  64. import android.net.NetworkPolicyManager;
  65. import android.net.NetworkQuotaInfo;
  66. import android.net.NetworkRequest;
  67. import android.net.NetworkSpecifier;
  68. import android.net.NetworkState;
  69. import android.net.NetworkUtils;
  70. import android.net.Proxy;
  71. import android.net.ProxyInfo;
  72. import android.net.RouteInfo;
  73. import android.net.UidRange;
  74. import android.net.Uri;
  75. import android.net.VpnService;
  76. import android.net.metrics.IpConnectivityLog;
  77. import android.net.metrics.NetworkEvent;
  78. import android.net.util.MultinetworkPolicyTracker;
  79. import android.os.Binder;
  80. import android.os.Build;
  81. import android.os.Bundle;
  82. import android.os.FileUtils;
  83. import android.os.Handler;
  84. import android.os.HandlerThread;
  85. import android.os.IBinder;
  86. import android.os.INetworkManagementService;
  87. import android.os.Looper;
  88. import android.os.Message;
  89. import android.os.Messenger;
  90. import android.os.ParcelFileDescriptor;
  91. import android.os.Parcelable;
  92. import android.os.PowerManager;
  93. import android.os.Process;
  94. import android.os.RemoteException;
  95. import android.os.ResultReceiver;
  96. import android.os.ServiceManager;
  97. import android.os.ServiceSpecificException;
  98. import android.os.SystemClock;
  99. import android.os.UserHandle;
  100. import android.os.UserManager;
  101. import android.provider.Settings;
  102. import android.security.Credentials;
  103. import android.security.KeyStore;
  104. import android.telephony.TelephonyManager;
  105. import android.text.TextUtils;
  106. import android.util.ArraySet;
  107. import android.util.LocalLog;
  108. import android.util.LocalLog.ReadOnlyLocalLog;
  109. import android.util.Log;
  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. import com.android.internal.R;
  116. import com.android.internal.annotations.GuardedBy;
  117. import com.android.internal.annotations.VisibleForTesting;
  118. import com.android.internal.app.IBatteryStats;
  119. import com.android.internal.net.LegacyVpnInfo;
  120. import com.android.internal.net.NetworkStatsFactory;
  121. import com.android.internal.net.VpnConfig;
  122. import com.android.internal.net.VpnInfo;
  123. import com.android.internal.net.VpnProfile;
  124. import com.android.internal.util.AsyncChannel;
  125. import com.android.internal.util.DumpUtils;
  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.DnsManager;
  133. import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
  134. import com.android.server.connectivity.IpConnectivityMetrics;
  135. import com.android.server.connectivity.KeepaliveTracker;
  136. import com.android.server.connectivity.LingerMonitor;
  137. import com.android.server.connectivity.MockableSystemProperties;
  138. import com.android.server.connectivity.NetworkAgentInfo;
  139. import com.android.server.connectivity.NetworkDiagnostics;
  140. import com.android.server.connectivity.NetworkMonitor;
  141. import com.android.server.connectivity.NetworkNotificationManager;
  142. import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
  143. import com.android.server.connectivity.PacManager;
  144. import com.android.server.connectivity.PermissionMonitor;
  145. import com.android.server.connectivity.Tethering;
  146. import com.android.server.connectivity.Vpn;
  147. import com.android.server.connectivity.tethering.TetheringDependencies;
  148. import com.android.server.net.BaseNetworkObserver;
  149. import com.android.server.net.LockdownVpnTracker;
  150. import com.android.server.net.NetworkPolicyManagerInternal;
  151. import com.google.android.collect.Lists;
  152. import org.xmlpull.v1.XmlPullParser;
  153. import org.xmlpull.v1.XmlPullParserException;
  154. import java.io.File;
  155. import java.io.FileDescriptor;
  156. import java.io.FileNotFoundException;
  157. import java.io.FileReader;
  158. import java.io.IOException;
  159. import java.io.PrintWriter;
  160. import java.net.Inet4Address;
  161. import java.net.InetAddress;
  162. import java.net.UnknownHostException;
  163. import java.util.ArrayDeque;
  164. import java.util.ArrayList;
  165. import java.util.Arrays;
  166. import java.util.Collection;
  167. import java.util.HashMap;
  168. import java.util.HashSet;
  169. import java.util.List;
  170. import java.util.Map;
  171. import java.util.Objects;
  172. import java.util.Set;
  173. import java.util.SortedSet;
  174. import java.util.TreeSet;
  175. /**
  176. * @hide
  177. */
  178. public class ConnectivityService extends IConnectivityManager.Stub
  179. implements PendingIntent.OnFinished {
  180. private static final String TAG = ConnectivityService.class.getSimpleName();
  181. public static final String DIAG_ARG = "--diag";
  182. public static final String SHORT_ARG = "--short";
  183. public static final String TETHERING_ARG = "tethering";
  184. private static final boolean DBG = true;
  185. private static final boolean VDBG = false;
  186. private static final boolean LOGD_RULES = false;
  187. private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
  188. // TODO: create better separation between radio types and network types
  189. // how long to wait before switching back to a radio's default network
  190. private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
  191. // system property that can override the above value
  192. private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
  193. "android.telephony.apn-restore";
  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. // Default to 30s linger time-out. Modifiable only for testing.
  198. private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
  199. private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
  200. @VisibleForTesting
  201. protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
  202. // How long to delay to removal of a pending intent based request.
  203. // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
  204. private final int mReleasePendingIntentDelayMs;
  205. private MockableSystemProperties mSystemProperties;
  206. private Tethering mTethering;
  207. private final PermissionMonitor mPermissionMonitor;
  208. private KeyStore mKeyStore;
  209. @GuardedBy("mVpns")
  210. private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
  211. // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
  212. // a direct call to LockdownVpnTracker.isEnabled().
  213. @GuardedBy("mVpns")
  214. private boolean mLockdownEnabled;
  215. @GuardedBy("mVpns")
  216. private LockdownVpnTracker mLockdownTracker;
  217. final private Context mContext;
  218. private int mNetworkPreference;
  219. // 0 is full bad, 100 is full good
  220. private int mDefaultInetConditionPublished = 0;
  221. private boolean mTestMode;
  222. private static ConnectivityService sServiceInstance;
  223. private INetworkManagementService mNetd;
  224. private INetworkStatsService mStatsService;
  225. private INetworkPolicyManager mPolicyManager;
  226. private NetworkPolicyManagerInternal mPolicyManagerInternal;
  227. private String mCurrentTcpBufferSizes;
  228. private static final int ENABLED = 1;
  229. private static final int DISABLED = 0;
  230. private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
  231. new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
  232. NetworkAgentInfo.class });
  233. private enum ReapUnvalidatedNetworks {
  234. // Tear down networks that have no chance (e.g. even if validated) of becoming
  235. // the highest scoring network satisfying a NetworkRequest. This should be passed when
  236. // all networks have been rematched against all NetworkRequests.
  237. REAP,
  238. // Don't reap networks. This should be passed when some networks have not yet been
  239. // rematched against all NetworkRequests.
  240. DONT_REAP
  241. };
  242. private enum UnneededFor {
  243. LINGER, // Determine whether this network is unneeded and should be lingered.
  244. TEARDOWN, // Determine whether this network is unneeded and should be torn down.
  245. }
  246. /**
  247. * used internally to change our mobile data enabled flag
  248. */
  249. private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
  250. /**
  251. * used internally to clear a wakelock when transitioning
  252. * from one net to another. Clear happens when we get a new
  253. * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
  254. * after a timeout if no network is found (typically 1 min).
  255. */
  256. private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
  257. /**
  258. * used internally to reload global proxy settings
  259. */
  260. private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
  261. /**
  262. * PAC manager has received new port.
  263. */
  264. private static final int EVENT_PROXY_HAS_CHANGED = 16;
  265. /**
  266. * used internally when registering NetworkFactories
  267. * obj = NetworkFactoryInfo
  268. */
  269. private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
  270. /**
  271. * used internally when registering NetworkAgents
  272. * obj = Messenger
  273. */
  274. private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
  275. /**
  276. * used to add a network request
  277. * includes a NetworkRequestInfo
  278. */
  279. private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
  280. /**
  281. * indicates a timeout period is over - check if we had a network yet or not
  282. * and if not, call the timeout callback (but leave the request live until they
  283. * cancel it.
  284. * includes a NetworkRequestInfo
  285. */
  286. private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
  287. /**
  288. * used to add a network listener - no request
  289. * includes a NetworkRequestInfo
  290. */
  291. private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
  292. /**
  293. * used to remove a network request, either a listener or a real request
  294. * arg1 = UID of caller
  295. * obj = NetworkRequest
  296. */
  297. private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
  298. /**
  299. * used internally when registering NetworkFactories
  300. * obj = Messenger
  301. */
  302. private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
  303. /**
  304. * used internally to expire a wakelock when transitioning
  305. * from one net to another. Expire happens when we fail to find
  306. * a new network (typically after 1 minute) -
  307. * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
  308. * a replacement network.
  309. */
  310. private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
  311. /**
  312. * Used internally to indicate the system is ready.
  313. */
  314. private static final int EVENT_SYSTEM_READY = 25;
  315. /**
  316. * used to add a network request with a pending intent
  317. * obj = NetworkRequestInfo
  318. */
  319. private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
  320. /**
  321. * used to remove a pending intent and its associated network request.
  322. * arg1 = UID of caller
  323. * obj = PendingIntent
  324. */
  325. private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
  326. /**
  327. * used to specify whether a network should be used even if unvalidated.
  328. * arg1 = whether to accept the network if it's unvalidated (1 or 0)
  329. * arg2 = whether to remember this choice in the future (1 or 0)
  330. * obj = network
  331. */
  332. private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
  333. /**
  334. * used to ask the user to confirm a connection to an unvalidated network.
  335. * obj = network
  336. */
  337. private static final int EVENT_PROMPT_UNVALIDATED = 29;
  338. /**
  339. * used internally to (re)configure mobile data always-on settings.
  340. */
  341. private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
  342. /**
  343. * used to add a network listener with a pending intent
  344. * obj = NetworkRequestInfo
  345. */
  346. private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
  347. /**
  348. * used to specify whether a network should not be penalized when it becomes unvalidated.
  349. */
  350. private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
  351. /**
  352. * used to trigger revalidation of a network.
  353. */
  354. private static final int EVENT_REVALIDATE_NETWORK = 36;
  355. // Handle changes in Private DNS settings.
  356. private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
  357. private static String eventName(int what) {
  358. return sMagicDecoderRing.get(what, Integer.toString(what));
  359. }
  360. /** Handler thread used for both of the handlers below. */
  361. @VisibleForTesting
  362. protected final HandlerThread mHandlerThread;
  363. /** Handler used for internal events. */
  364. final private InternalHandler mHandler;
  365. /** Handler used for incoming {@link NetworkStateTracker} events. */
  366. final private NetworkStateTrackerHandler mTrackerHandler;
  367. private final DnsManager mDnsManager;
  368. private boolean mSystemReady;
  369. private Intent mInitialBroadcast;
  370. private PowerManager.WakeLock mNetTransitionWakeLock;
  371. private int mNetTransitionWakeLockTimeout;
  372. private final PowerManager.WakeLock mPendingIntentWakeLock;
  373. // track the current default http proxy - tell the world if we get a new one (real change)
  374. private volatile ProxyInfo mDefaultProxy = null;
  375. private Object mProxyLock = new Object();
  376. private boolean mDefaultProxyDisabled = false;
  377. // track the global proxy.
  378. private ProxyInfo mGlobalProxy = null;
  379. private PacManager mPacManager = null;
  380. final private SettingsObserver mSettingsObserver;
  381. private UserManager mUserManager;
  382. NetworkConfig[] mNetConfigs;
  383. int mNetworksDefined;
  384. // the set of network types that can only be enabled by system/sig apps
  385. List mProtectedNetworks;
  386. private DataConnectionStats mDataConnectionStats;
  387. TelephonyManager mTelephonyManager;
  388. private KeepaliveTracker mKeepaliveTracker;
  389. private NetworkNotificationManager mNotifier;
  390. private LingerMonitor mLingerMonitor;
  391. // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
  392. private static final int MIN_NET_ID = 100; // some reserved marks
  393. private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
  394. private int mNextNetId = MIN_NET_ID;
  395. // sequence number of NetworkRequests
  396. private int mNextNetworkRequestId = 1;
  397. // NetworkRequest activity String log entries.
  398. private static final int MAX_NETWORK_REQUEST_LOGS = 20;
  399. private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
  400. // NetworkInfo blocked and unblocked String log entries
  401. private static final int MAX_NETWORK_INFO_LOGS = 40;
  402. private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
  403. private static final int MAX_WAKELOCK_LOGS = 20;
  404. private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
  405. private int mTotalWakelockAcquisitions = 0;
  406. private int mTotalWakelockReleases = 0;
  407. private long mTotalWakelockDurationMs = 0;
  408. private long mMaxWakelockDurationMs = 0;
  409. private long mLastWakeLockAcquireTimestamp = 0;
  410. // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
  411. private static final int MAX_VALIDATION_LOGS = 10;
  412. private static class ValidationLog {
  413. final Network mNetwork;
  414. final String mNetworkExtraInfo;
  415. final ReadOnlyLocalLog mLog;
  416. ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
  417. mNetwork = network;
  418. mNetworkExtraInfo = networkExtraInfo;
  419. mLog = log;
  420. }
  421. }
  422. private final ArrayDeque<ValidationLog> mValidationLogs =
  423. new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
  424. private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
  425. synchronized (mValidationLogs) {
  426. while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
  427. mValidationLogs.removeLast();
  428. }
  429. mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
  430. }
  431. }
  432. private final IpConnectivityLog mMetricsLog;
  433. @VisibleForTesting
  434. final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
  435. /**
  436. * Implements support for the legacy "one network per network type" model.
  437. *
  438. * We used to have a static array of NetworkStateTrackers, one for each
  439. * network type, but that doesn't work any more now that we can have,
  440. * for example, more that one wifi network. This class stores all the
  441. * NetworkAgentInfo objects that support a given type, but the legacy
  442. * API will only see the first one.
  443. *
  444. * It serves two main purposes:
  445. *
  446. * 1. Provide information about "the network for a given type" (since this
  447. * API only supports one).
  448. * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
  449. * the first network for a given type changes, or if the default network
  450. * changes.
  451. */
  452. private class LegacyTypeTracker {
  453. private static final boolean DBG = true;
  454. private static final boolean VDBG = false;
  455. /**
  456. * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
  457. * Each list holds references to all NetworkAgentInfos that are used to
  458. * satisfy requests for that network type.
  459. *
  460. * This array is built out at startup such that an unsupported network
  461. * doesn't get an ArrayList instance, making this a tristate:
  462. * unsupported, supported but not active and active.
  463. *
  464. * The actual lists are populated when we scan the network types that
  465. * are supported on this device.
  466. *
  467. * Threading model:
  468. * - addSupportedType() is only called in the constructor
  469. * - add(), update(), remove() are only called from the ConnectivityService handler thread.
  470. * They are therefore not thread-safe with respect to each other.
  471. * - getNetworkForType() can be called at any time on binder threads. It is synchronized
  472. * on mTypeLists to be thread-safe with respect to a concurrent remove call.
  473. * - dump is thread-safe with respect to concurrent add and remove calls.
  474. */
  475. private final ArrayList<NetworkAgentInfo> mTypeLists[];
  476. public LegacyTypeTracker() {
  477. mTypeLists = (ArrayList<NetworkAgentInfo>[])
  478. new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
  479. }
  480. public void addSupportedType(int type) {
  481. if (mTypeLists[type] != null) {
  482. throw new IllegalStateException(
  483. "legacy list for type " + type + "already initialized");
  484. }
  485. mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
  486. }
  487. public boolean isTypeSupported(int type) {
  488. return isNetworkTypeValid(type) && mTypeLists[type] != null;
  489. }
  490. public NetworkAgentInfo getNetworkForType(int type) {
  491. synchronized (mTypeLists) {
  492. if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
  493. return mTypeLists[type].get(0);
  494. }
  495. }
  496. return null;
  497. }
  498. private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
  499. boolean isDefaultNetwork) {
  500. if (DBG) {
  501. log("Sending " + state +
  502. " broadcast for type " + type + " " + nai.name() +
  503. " isDefaultNetwork=" + isDefaultNetwork);
  504. }
  505. }
  506. /** Adds the given network to the specified legacy type list. */
  507. public void add(int type, NetworkAgentInfo nai) {
  508. if (!isTypeSupported(type)) {
  509. return; // Invalid network type.
  510. }
  511. if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
  512. ArrayList<NetworkAgentInfo> list = mTypeLists[type];
  513. if (list.contains(nai)) {
  514. return;
  515. }
  516. synchronized (mTypeLists) {
  517. list.add(nai);
  518. }
  519. // Send a broadcast if this is the first network of its type or if it's the default.
  520. final boolean isDefaultNetwork = isDefaultNetwork(nai);
  521. if ((list.size() == 1) || isDefaultNetwork) {
  522. maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
  523. sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
  524. }
  525. }
  526. /** Removes the given network from the specified legacy type list. */
  527. public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
  528. ArrayList<NetworkAgentInfo> list = mTypeLists[type];
  529. if (list == null || list.isEmpty()) {
  530. return;
  531. }
  532. final boolean wasFirstNetwork = list.get(0).equals(nai);
  533. synchronized (mTypeLists) {
  534. if (!list.remove(nai)) {
  535. return;
  536. }
  537. }
  538. final DetailedState state = DetailedState.DISCONNECTED;
  539. if (wasFirstNetwork || wasDefault) {
  540. maybeLogBroadcast(nai, state, type, wasDefault);
  541. sendLegacyNetworkBroadcast(nai, state, type);
  542. }
  543. if (!list.isEmpty() && wasFirstNetwork) {
  544. if (DBG) log("Other network available for type " + type +
  545. ", sending connected broadcast");
  546. final NetworkAgentInfo replacement = list.get(0);
  547. maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
  548. sendLegacyNetworkBroadcast(replacement, state, type);
  549. }
  550. }
  551. /** Removes the given network from all legacy type lists. */
  552. public void remove(NetworkAgentInfo nai, boolean wasDefault) {
  553. if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
  554. for (int type = 0; type < mTypeLists.length; type++) {
  555. remove(type, nai, wasDefault);
  556. }
  557. }
  558. // send out another legacy broadcast - currently only used for suspend/unsuspend
  559. // toggle
  560. public void update(NetworkAgentInfo nai) {
  561. final boolean isDefault = isDefaultNetwork(nai);
  562. final DetailedState state = nai.networkInfo.getDetailedState();
  563. for (int type = 0; type < mTypeLists.length; type++) {
  564. final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
  565. final boolean contains = (list != null && list.contains(nai));
  566. final boolean isFirst = contains && (nai == list.get(0));
  567. if (isFirst || contains && isDefault) {
  568. maybeLogBroadcast(nai, state, type, isDefault);
  569. sendLegacyNetworkBroadcast(nai, state, type);
  570. }
  571. }
  572. }
  573. private String naiToString(NetworkAgentInfo nai) {
  574. String name = (nai != null) ? nai.name() : "null";
  575. String state = (nai.networkInfo != null) ?
  576. nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
  577. "???/???";
  578. return name + " " + state;
  579. }
  580. public void dump(IndentingPrintWriter pw) {
  581. pw.println("mLegacyTypeTracker:");
  582. pw.increaseIndent();
  583. pw.print("Supported types:");
  584. for (int type = 0; type < mTypeLists.length; type++) {
  585. if (mTypeLists[type] != null) pw.print(" " + type);
  586. }
  587. pw.println();
  588. pw.println("Current state:");
  589. pw.increaseIndent();
  590. synchronized (mTypeLists) {
  591. for (int type = 0; type < mTypeLists.length; type++) {
  592. if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
  593. for (NetworkAgentInfo nai : mTypeLists[type]) {
  594. pw.println(type + " " + naiToString(nai));
  595. }
  596. }
  597. }
  598. pw.decreaseIndent();
  599. pw.decreaseIndent();
  600. pw.println();
  601. }
  602. }
  603. private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
  604. public ConnectivityService(Context context, INetworkManagementService netManager,
  605. INetworkStatsService statsService, INetworkPolicyManager policyManager) {
  606. this(context, netManager, statsService, policyManager, new IpConnectivityLog());
  607. }
  608. @VisibleForTesting
  609. protected ConnectivityService(Context context, INetworkManagementService netManager,
  610. INetworkStatsService statsService, INetworkPolicyManager policyManager,
  611. IpConnectivityLog logger) {
  612. if (DBG) log("ConnectivityService starting up");
  613. mSystemProperties = getSystemProperties();
  614. mMetricsLog = logger;
  615. mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
  616. NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
  617. mNetworkRequests.put(mDefaultRequest, defaultNRI);
  618. mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
  619. mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
  620. NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
  621. mHandlerThread = new HandlerThread("ConnectivityServiceThread");
  622. mHandlerThread.start();
  623. mHandler = new InternalHandler(mHandlerThread.getLooper());
  624. mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
  625. mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
  626. Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
  627. mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
  628. mContext = checkNotNull(context, "missing Context");
  629. mNetd = checkNotNull(netManager, "missing INetworkManagementService");
  630. mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
  631. mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
  632. mPolicyManagerInternal = checkNotNull(
  633. LocalServices.getService(NetworkPolicyManagerInternal.class),
  634. "missing NetworkPolicyManagerInternal");
  635. mKeyStore = KeyStore.getInstance();
  636. mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
  637. try {
  638. mPolicyManager.registerListener(mPolicyListener);
  639. } catch (RemoteException e) {
  640. // ouch, no rules updates means some processes may never get network
  641. loge("unable to register INetworkPolicyListener" + e);
  642. }
  643. final PowerManager powerManager = (PowerManager) context.getSystemService(
  644. Context.POWER_SERVICE);
  645. mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  646. mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
  647. com.android.internal.R.integer.config_networkTransitionTimeout);
  648. mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  649. mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
  650. // TODO: What is the "correct" way to do determine if this is a wifi only device?
  651. boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
  652. log("wifiOnly=" + wifiOnly);
  653. String[] naStrings = context.getResources().getStringArray(
  654. com.android.internal.R.array.networkAttributes);
  655. for (String naString : naStrings) {
  656. try {
  657. NetworkConfig n = new NetworkConfig(naString);
  658. if (VDBG) log("naString=" + naString + " config=" + n);
  659. if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
  660. loge("Error in networkAttributes - ignoring attempt to define type " +
  661. n.type);
  662. continue;
  663. }
  664. if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
  665. log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
  666. n.type);
  667. continue;
  668. }
  669. if (mNetConfigs[n.type] != null) {
  670. loge("Error in networkAttributes - ignoring attempt to redefine type " +
  671. n.type);
  672. continue;
  673. }
  674. mLegacyTypeTracker.addSupportedType(n.type);
  675. mNetConfigs[n.type] = n;
  676. mNetworksDefined++;
  677. } catch(Exception e) {
  678. // ignore it - leave the entry null
  679. }
  680. }
  681. // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
  682. if (mNetConfigs[TYPE_VPN] == null) {
  683. // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
  684. // don't need to add TYPE_VPN to mNetConfigs.
  685. mLegacyTypeTracker.addSupportedType(TYPE_VPN);
  686. mNetworksDefined++; // used only in the log() statement below.
  687. }
  688. // Do the same for Ethernet, since it's often not specified in the configs, although many
  689. // devices can use it via USB host adapters.
  690. if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
  691. mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
  692. mNetworksDefined++;
  693. }
  694. if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
  695. mProtectedNetworks = new ArrayList<Integer>();
  696. int[] protectedNetworks = context.getResources().getIntArray(
  697. com.android.internal.R.array.config_protectedNetworks);
  698. for (int p : protectedNetworks) {
  699. if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
  700. mProtectedNetworks.add(p);
  701. } else {
  702. if (DBG) loge("Ignoring protectedNetwork " + p);
  703. }
  704. }
  705. mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
  706. && mSystemProperties.get("ro.build.type").equals("eng");
  707. mTethering = makeTethering();
  708. mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
  709. //set up the listener for user state for creating user VPNs
  710. IntentFilter intentFilter = new IntentFilter();
  711. intentFilter.addAction(Intent.ACTION_USER_STARTED);
  712. intentFilter.addAction(Intent.ACTION_USER_STOPPED);
  713. intentFilter.addAction(Intent.ACTION_USER_ADDED);
  714. intentFilter.addAction(Intent.ACTION_USER_REMOVED);
  715. intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
  716. mContext.registerReceiverAsUser(
  717. mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
  718. mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
  719. new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
  720. try {
  721. mNetd.registerObserver(mTethering);
  722. mNetd.registerObserver(mDataActivityObserver);
  723. } catch (RemoteException e) {
  724. loge("Error registering observer :" + e);
  725. }
  726. mSettingsObserver = new SettingsObserver(mContext, mHandler);
  727. registerSettingsCallbacks();
  728. mDataConnectionStats = new DataConnectionStats(mContext);
  729. mDataConnectionStats.startMonitoring();
  730. mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
  731. mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
  732. mKeepaliveTracker = new KeepaliveTracker(mHandler);
  733. mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
  734. mContext.getSystemService(NotificationManager.class));
  735. final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
  736. Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
  737. LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
  738. final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
  739. Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
  740. LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
  741. mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
  742. mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
  743. mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
  744. mMultinetworkPolicyTracker.start();
  745. mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
  746. registerPrivateDnsSettingsCallbacks();
  747. }
  748. private Tethering makeTethering() {
  749. // TODO: Move other elements into @Overridden getters.
  750. final TetheringDependencies deps = new TetheringDependencies();
  751. return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
  752. IoThread.get().getLooper(), new MockableSystemProperties(),
  753. deps);
  754. }
  755. private NetworkRequest createDefaultInternetRequestForTransport(
  756. int transportType, NetworkRequest.Type type) {
  757. NetworkCapabilities netCap = new NetworkCapabilities();
  758. netCap.addCapability(NET_CAPABILITY_INTERNET);
  759. netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
  760. if (transportType > -1) {
  761. netCap.addTransportType(transportType);
  762. }
  763. return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
  764. }
  765. // Used only for testing.
  766. // TODO: Delete this and either:
  767. // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
  768. // changing ContentResolver to make registerContentObserver non-final).
  769. // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
  770. // by subclassing SettingsObserver.
  771. @VisibleForTesting
  772. void updateMobileDataAlwaysOn() {
  773. mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
  774. }
  775. private void handleMobileDataAlwaysOn() {
  776. final boolean enable = toBool(Settings.Global.getInt(
  777. mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
  778. final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
  779. if (enable == isEnabled) {
  780. return; // Nothing to do.
  781. }
  782. if (enable) {
  783. handleRegisterNetworkRequest(new NetworkRequestInfo(
  784. null, mDefaultMobileDataRequest, new Binder()));
  785. } else {
  786. handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
  787. }
  788. }
  789. private void registerSettingsCallbacks() {
  790. // Watch for global HTTP proxy changes.
  791. mSettingsObserver.observe(
  792. Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
  793. EVENT_APPLY_GLOBAL_HTTP_PROXY);
  794. // Watch for whether or not to keep mobile data always on.
  795. mSettingsObserver.observe(
  796. Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
  797. EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
  798. }
  799. private void registerPrivateDnsSettingsCallbacks() {
  800. for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
  801. mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
  802. }
  803. }
  804. private synchronized int nextNetworkRequestId() {
  805. return mNextNetworkRequestId++;
  806. }
  807. @VisibleForTesting
  808. protected int reserveNetId() {
  809. synchronized (mNetworkForNetId) {
  810. for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
  811. int netId = mNextNetId;
  812. if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
  813. // Make sure NetID unused. http://b/16815182
  814. if (!mNetIdInUse.get(netId)) {
  815. mNetIdInUse.put(netId, true);
  816. return netId;
  817. }
  818. }
  819. }
  820. throw new IllegalStateException("No free netIds");
  821. }
  822. private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
  823. if (mLegacyTypeTracker.isTypeSupported(networkType)) {
  824. final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
  825. final NetworkState state;
  826. if (nai != null) {
  827. state = nai.getNetworkState();
  828. state.networkInfo.setType(networkType);
  829. } else {
  830. final NetworkInfo info = new NetworkInfo(networkType, 0,
  831. getNetworkTypeName(networkType), "");
  832. info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
  833. info.setIsAvailable(true);
  834. final NetworkCapabilities capabilities = new NetworkCapabilities();
  835. capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
  836. !info.isRoaming());
  837. state = new NetworkState(info, new LinkProperties(), capabilities,
  838. null, null, null);
  839. }
  840. filterNetworkStateForUid(state, uid, ignoreBlocked);
  841. return state;
  842. } else {
  843. return NetworkState.EMPTY;
  844. }
  845. }
  846. private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
  847. if (network == null) {
  848. return null;
  849. }
  850. synchronized (mNetworkForNetId) {
  851. return mNetworkForNetId.get(network.netId);
  852. }
  853. }
  854. private Network[] getVpnUnderlyingNetworks(int uid) {
  855. synchronized (mVpns) {
  856. if (!mLockdownEnabled) {
  857. int user = UserHandle.getUserId(uid);
  858. Vpn vpn = mVpns.get(user);
  859. if (vpn != null && vpn.appliesToUid(uid)) {
  860. return vpn.getUnderlyingNetworks();
  861. }
  862. }
  863. }
  864. return null;
  865. }
  866. private NetworkState getUnfilteredActiveNetworkState(int uid) {
  867. NetworkAgentInfo nai = getDefaultNetwork();
  868. final Network[] networks = getVpnUnderlyingNetworks(uid);
  869. if (networks != null) {
  870. // getUnderlyingNetworks() returns:
  871. // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
  872. // empty array => the VPN explicitly said "no default network".
  873. // non-empty array => the VPN specified one or more default networks; we use the
  874. // first one.
  875. if (networks.length > 0) {
  876. nai = getNetworkAgentInfoForNetwork(networks[0]);
  877. } else {
  878. nai = null;
  879. }
  880. }
  881. if (nai != null) {
  882. return nai.getNetworkState();
  883. } else {
  884. return NetworkState.EMPTY;
  885. }
  886. }
  887. /**
  888. * Check if UID should be blocked from using the network with the given LinkProperties.
  889. */
  890. private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
  891. boolean ignoreBlocked) {
  892. // Networks aren't blocked when ignoring blocked status
  893. if (ignoreBlocked) {
  894. return false;
  895. }
  896. // Networks are never blocked for system services
  897. // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
  898. if (isSystem(uid)) {
  899. return false;
  900. }
  901. synchronized (mVpns) {
  902. final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
  903. if (vpn != null && vpn.isBlockingUid(uid)) {
  904. return true;
  905. }
  906. }
  907. final String iface = (lp == null ? "" : lp.getInterfaceName());
  908. return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
  909. }
  910. private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
  911. if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
  912. return;
  913. }
  914. final boolean blocked;
  915. synchronized (mBlockedAppUids) {
  916. if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
  917. blocked = true;
  918. } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
  919. blocked = false;
  920. } else {
  921. return;
  922. }
  923. }
  924. String action = blocked ? "BLOCKED" : "UNBLOCKED";
  925. log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
  926. mNetworkInfoBlockingLogs.log(action + " " + uid);
  927. }
  928. /**
  929. * Apply any relevant filters to {@link NetworkState} for the given UID. For
  930. * example, this may mark the network as {@link DetailedState#BLOCKED} based
  931. * on {@link #isNetworkWithLinkPropertiesBlocked}.
  932. */
  933. private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
  934. if (state == null || state.networkInfo == null || state.linkProperties == null) return;
  935. if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
  936. state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
  937. }
  938. synchronized (mVpns) {
  939. if (mLockdownTracker != null) {
  940. mLockdownTracker.augmentNetworkInfo(state.networkInfo);
  941. }
  942. }
  943. }
  944. /**
  945. * Return NetworkInfo for the active (i.e., connected) network interface.
  946. * It is assumed that at most one network is active at a time. If more
  947. * than one is active, it is indeterminate which will be returned.
  948. * @return the info for the active network, or {@code null} if none is
  949. * active
  950. */
  951. @Override
  952. public NetworkInfo getActiveNetworkInfo() {
  953. enforceAccessPermission();
  954. final int uid = Binder.getCallingUid();
  955. final NetworkState state = getUnfilteredActiveNetworkState(uid);
  956. filterNetworkStateForUid(state, uid, false);
  957. maybeLogBlockedNetworkInfo(state.networkInfo, uid);
  958. return state.networkInfo;
  959. }
  960. @Override
  961. public Network getActiveNetwork() {
  962. enforceAccessPermission();
  963. return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
  964. }
  965. @Override
  966. public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
  967. enforceConnectivityInternalPermission();
  968. return getActiveNetworkForUidInternal(uid, ignoreBlocked);
  969. }
  970. private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
  971. final int user = UserHandle.getUserId(uid);
  972. int vpnNetId = NETID_UNSET;
  973. synchronized (mVpns) {
  974. final Vpn vpn = mVpns.get(user);
  975. if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
  976. }
  977. NetworkAgentInfo nai;
  978. if (vpnNetId != NETID_UNSET) {
  979. synchronized (mNetworkForNetId) {
  980. nai = mNetworkForNetId.get(vpnNetId);
  981. }
  982. if (nai != null) return nai.network;
  983. }
  984. nai = getDefaultNetwork();
  985. if (nai != null
  986. && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
  987. nai = null;
  988. }
  989. return nai != null ? nai.network : null;
  990. }
  991. // Public because it's used by mLockdownTracker.
  992. public NetworkInfo getActiveNetworkInfoUnfiltered() {
  993. enforceAccessPermission();
  994. final int uid = Binder.getCallingUid();
  995. NetworkState state = getUnfilteredActiveNetworkState(uid);
  996. return state.networkInfo;
  997. }
  998. @Override
  999. public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
  1000. enforceConnectivityInternalPermission();
  1001. final NetworkState state = getUnfilteredActiveNetworkState(uid);
  1002. filterNetworkStateForUid(state, uid, ignoreBlocked);
  1003. return state.networkInfo;
  1004. }
  1005. @Override
  1006. public NetworkInfo getNetworkInfo(int networkType) {
  1007. enforceAccessPermission();
  1008. final int uid = Binder.getCallingUid();
  1009. if (getVpnUnderlyingNetworks(uid) != null) {
  1010. // A VPN is active, so we may need to return one of its underlying networks. This
  1011. // information is not available in LegacyTypeTracker, so we have to get it from
  1012. // getUnfilteredActiveNetworkState.
  1013. final NetworkState state = getUnfilteredActiveNetworkState(uid);
  1014. if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
  1015. filterNetworkStateForUid(state, uid, false);
  1016. return state.networkInfo;
  1017. }
  1018. }
  1019. final NetworkState state = getFilteredNetworkState(networkType, uid, false);
  1020. return state.networkInfo;
  1021. }
  1022. @Override
  1023. public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
  1024. enforceAccessPermission();
  1025. final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  1026. if (nai != null) {
  1027. final NetworkState state = nai.getNetworkState();
  1028. filterNetworkStateForUid(state, uid, ignoreBlocked);
  1029. return state.networkInfo;
  1030. } else {
  1031. return null;
  1032. }
  1033. }
  1034. @Override
  1035. public NetworkInfo[] getAllNetworkInfo() {
  1036. enforceAccessPermission();
  1037. final ArrayList<NetworkInfo> result = Lists.newArrayList();
  1038. for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
  1039. networkType++) {
  1040. NetworkInfo info = getNetworkInfo(networkType);
  1041. if (info != null) {
  1042. result.add(info);
  1043. }
  1044. }
  1045. return result.toArray(new NetworkInfo[result.size()]);
  1046. }
  1047. @Override
  1048. public Network getNetworkForType(int networkType) {
  1049. enforceAccessPermission();
  1050. final int uid = Binder.getCallingUid();
  1051. NetworkState state = getFilteredNetworkState(networkType, uid, false);
  1052. if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
  1053. return state.network;
  1054. }
  1055. return null;
  1056. }
  1057. @Override
  1058. public Network[] getAllNetworks() {
  1059. enforceAccessPermission();
  1060. synchronized (mNetworkForNetId) {
  1061. final Network[] result = new Network[mNetworkForNetId.size()];
  1062. for (int i = 0; i < mNetworkForNetId.size(); i++) {
  1063. result[i] = mN