/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

  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] = mNetworkForNetId.valueAt(i).network;
  1064. }
  1065. return result;
  1066. }
  1067. }
  1068. @Override
  1069. public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
  1070. // The basic principle is: if an app's traffic could possibly go over a
  1071. // network, without the app doing anything multinetwork-specific,
  1072. // (hence, by "default"), then include that network's capabilities in
  1073. // the array.
  1074. //
  1075. // In the normal case, app traffic only goes over the system's default
  1076. // network connection, so that's the only network returned.
  1077. //
  1078. // With a VPN in force, some app traffic may go into the VPN, and thus
  1079. // over whatever underlying networks the VPN specifies, while other app
  1080. // traffic may go over the system default network (e.g.: a split-tunnel
  1081. // VPN, or an app disallowed by the VPN), so the set of networks
  1082. // returned includes the VPN's underlying networks and the system
  1083. // default.
  1084. enforceAccessPermission();
  1085. HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
  1086. NetworkAgentInfo nai = getDefaultNetwork();
  1087. NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
  1088. if (nc != null) {
  1089. result.put(nai.network, nc);
  1090. }
  1091. synchronized (mVpns) {
  1092. if (!mLockdownEnabled) {
  1093. Vpn vpn = mVpns.get(userId);
  1094. if (vpn != null) {
  1095. Network[] networks = vpn.getUnderlyingNetworks();
  1096. if (networks != null) {
  1097. for (Network network : networks) {
  1098. nai = getNetworkAgentInfoForNetwork(network);
  1099. nc = getNetworkCapabilitiesInternal(nai);
  1100. if (nc != null) {
  1101. result.put(network, nc);
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. }
  1108. NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
  1109. out = result.values().toArray(out);
  1110. return out;
  1111. }
  1112. @Override
  1113. public boolean isNetworkSupported(int networkType) {
  1114. enforceAccessPermission();
  1115. return mLegacyTypeTracker.isTypeSupported(networkType);
  1116. }
  1117. /**
  1118. * Return LinkProperties for the active (i.e., connected) default
  1119. * network interface. It is assumed that at most one default network
  1120. * is active at a time. If more than one is active, it is indeterminate
  1121. * which will be returned.
  1122. * @return the ip properties for the active network, or {@code null} if
  1123. * none is active
  1124. */
  1125. @Override
  1126. public LinkProperties getActiveLinkProperties() {
  1127. enforceAccessPermission();
  1128. final int uid = Binder.getCallingUid();
  1129. NetworkState state = getUnfilteredActiveNetworkState(uid);
  1130. return state.linkProperties;
  1131. }
  1132. @Override
  1133. public LinkProperties getLinkPropertiesForType(int networkType) {
  1134. enforceAccessPermission();
  1135. NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
  1136. if (nai != null) {
  1137. synchronized (nai) {
  1138. return new LinkProperties(nai.linkProperties);
  1139. }
  1140. }
  1141. return null;
  1142. }
  1143. // TODO - this should be ALL networks
  1144. @Override
  1145. public LinkProperties getLinkProperties(Network network) {
  1146. enforceAccessPermission();
  1147. return getLinkProperties(getNetworkAgentInfoForNetwork(network));
  1148. }
  1149. private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
  1150. if (nai == null) {
  1151. return null;
  1152. }
  1153. synchronized (nai) {
  1154. return new LinkProperties(nai.linkProperties);
  1155. }
  1156. }
  1157. private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
  1158. if (nai != null) {
  1159. synchronized (nai) {
  1160. if (nai.networkCapabilities != null) {
  1161. // TODO : don't remove the UIDs when communicating with processes
  1162. // that have the NETWORK_SETTINGS permission.
  1163. return networkCapabilitiesWithoutUids(nai.networkCapabilities);
  1164. }
  1165. }
  1166. }
  1167. return null;
  1168. }
  1169. @Override
  1170. public NetworkCapabilities getNetworkCapabilities(Network network) {
  1171. enforceAccessPermission();
  1172. return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
  1173. }
  1174. private NetworkCapabilities networkCapabilitiesWithoutUids(NetworkCapabilities nc) {
  1175. return new NetworkCapabilities(nc).setUids(null);
  1176. }
  1177. @Override
  1178. public NetworkState[] getAllNetworkState() {
  1179. // Require internal since we're handing out IMSI details
  1180. enforceConnectivityInternalPermission();
  1181. final ArrayList<NetworkState> result = Lists.newArrayList();
  1182. for (Network network : getAllNetworks()) {
  1183. final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  1184. if (nai != null) {
  1185. // TODO (b/73321673) : NetworkState contains a copy of the
  1186. // NetworkCapabilities, which may contain UIDs of apps to which the
  1187. // network applies. Should the UIDs be cleared so as not to leak or
  1188. // interfere ?
  1189. result.add(nai.getNetworkState());
  1190. }
  1191. }
  1192. return result.toArray(new NetworkState[result.size()]);
  1193. }
  1194. @Override
  1195. @Deprecated
  1196. public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
  1197. Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
  1198. + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
  1199. return new NetworkQuotaInfo();
  1200. }
  1201. @Override
  1202. public boolean isActiveNetworkMetered() {
  1203. enforceAccessPermission();
  1204. final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
  1205. if (caps != null) {
  1206. return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
  1207. } else {
  1208. // Always return the most conservative value
  1209. return true;
  1210. }
  1211. }
  1212. private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
  1213. @Override
  1214. public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
  1215. int deviceType = Integer.parseInt(label);
  1216. sendDataActivityBroadcast(deviceType, active, tsNanos);
  1217. }
  1218. };
  1219. /**
  1220. * Ensure that a network route exists to deliver traffic to the specified
  1221. * host via the specified network interface.
  1222. * @param networkType the type of the network over which traffic to the
  1223. * specified host is to be routed
  1224. * @param hostAddress the IP address of the host to which the route is
  1225. * desired
  1226. * @return {@code true} on success, {@code false} on failure
  1227. */
  1228. @Override
  1229. public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
  1230. enforceChangePermission();
  1231. if (mProtectedNetworks.contains(networkType)) {
  1232. enforceConnectivityInternalPermission();
  1233. }
  1234. InetAddress addr;
  1235. try {
  1236. addr = InetAddress.getByAddress(hostAddress);
  1237. } catch (UnknownHostException e) {
  1238. if (DBG) log("requestRouteToHostAddress got " + e.toString());
  1239. return false;
  1240. }
  1241. if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
  1242. if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
  1243. return false;
  1244. }
  1245. NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
  1246. if (nai == null) {
  1247. if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
  1248. if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
  1249. } else {
  1250. if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
  1251. }
  1252. return false;
  1253. }
  1254. DetailedState netState;
  1255. synchronized (nai) {
  1256. netState = nai.networkInfo.getDetailedState();
  1257. }
  1258. if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
  1259. if (VDBG) {
  1260. log("requestRouteToHostAddress on down network "
  1261. + "(" + networkType + ") - dropped"
  1262. + " netState=" + netState);
  1263. }
  1264. return false;
  1265. }
  1266. final int uid = Binder.getCallingUid();
  1267. final long token = Binder.clearCallingIdentity();
  1268. try {
  1269. LinkProperties lp;
  1270. int netId;
  1271. synchronized (nai) {
  1272. lp = nai.linkProperties;
  1273. netId = nai.network.netId;
  1274. }
  1275. boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
  1276. if (DBG) log("requestRouteToHostAddress ok=" + ok);
  1277. return ok;
  1278. } finally {
  1279. Binder.restoreCallingIdentity(token);
  1280. }
  1281. }
  1282. private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
  1283. RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
  1284. if (bestRoute == null) {
  1285. bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
  1286. } else {
  1287. String iface = bestRoute.getInterface();
  1288. if (bestRoute.getGateway().equals(addr)) {
  1289. // if there is no better route, add the implied hostroute for our gateway
  1290. bestRoute = RouteInfo.makeHostRoute(addr, iface);
  1291. } else {
  1292. // if we will connect to this through another route, add a direct route
  1293. // to it's gateway
  1294. bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
  1295. }
  1296. }
  1297. if (DBG) log("Adding legacy route " + bestRoute +
  1298. " for UID/PID " + uid + "/" + Binder.getCallingPid());
  1299. try {
  1300. mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
  1301. } catch (Exception e) {
  1302. // never crash - catch them all
  1303. if (DBG) loge("Exception trying to add a route: " + e);
  1304. return false;
  1305. }
  1306. return true;
  1307. }
  1308. private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
  1309. @Override
  1310. public void onUidRulesChanged(int uid, int uidRules) {
  1311. // TODO: notify UID when it has requested targeted updates
  1312. }
  1313. @Override
  1314. public void onRestrictBackgroundChanged(boolean restrictBackground) {
  1315. // TODO: relocate this specific callback in Tethering.
  1316. if (restrictBackground) {
  1317. log("onRestrictBackgroundChanged(true): disabling tethering");
  1318. mTethering.untetherAll();
  1319. }
  1320. }
  1321. };
  1322. /**
  1323. * Require that the caller is either in the same user or has appropriate permission to interact
  1324. * across users.
  1325. *
  1326. * @param userId Target user for whatever operation the current IPC is supposed to perform.
  1327. */
  1328. private void enforceCrossUserPermission(int userId) {
  1329. if (userId == UserHandle.getCallingUserId()) {
  1330. // Not a cross-user call.
  1331. return;
  1332. }
  1333. mContext.enforceCallingOrSelfPermission(
  1334. android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
  1335. "ConnectivityService");
  1336. }
  1337. private void enforceInternetPermission() {
  1338. mContext.enforceCallingOrSelfPermission(
  1339. android.Manifest.permission.INTERNET,
  1340. "ConnectivityService");
  1341. }
  1342. private void enforceAccessPermission() {
  1343. mContext.enforceCallingOrSelfPermission(
  1344. android.Manifest.permission.ACCESS_NETWORK_STATE,
  1345. "ConnectivityService");
  1346. }
  1347. private void enforceChangePermission() {
  1348. ConnectivityManager.enforceChangePermission(mContext);
  1349. }
  1350. private void enforceSettingsPermission() {
  1351. mContext.enforceCallingOrSelfPermission(
  1352. android.Manifest.permission.NETWORK_SETTINGS,
  1353. "ConnectivityService");
  1354. }
  1355. private void enforceTetherAccessPermission() {
  1356. mContext.enforceCallingOrSelfPermission(
  1357. android.Manifest.permission.ACCESS_NETWORK_STATE,
  1358. "ConnectivityService");
  1359. }
  1360. private void enforceConnectivityInternalPermission() {
  1361. mContext.enforceCallingOrSelfPermission(
  1362. android.Manifest.permission.CONNECTIVITY_INTERNAL,
  1363. "ConnectivityService");
  1364. }
  1365. private void enforceConnectivityRestrictedNetworksPermission() {
  1366. try {
  1367. mContext.enforceCallingOrSelfPermission(
  1368. android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
  1369. "ConnectivityService");
  1370. return;
  1371. } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
  1372. enforceConnectivityInternalPermission();
  1373. }
  1374. private void enforceKeepalivePermission() {
  1375. mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
  1376. }
  1377. // Public because it's used by mLockdownTracker.
  1378. public void sendConnectedBroadcast(NetworkInfo info) {
  1379. enforceConnectivityInternalPermission();
  1380. sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
  1381. }
  1382. private void sendInetConditionBroadcast(NetworkInfo info) {
  1383. sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
  1384. }
  1385. private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
  1386. synchronized (mVpns) {
  1387. if (mLockdownTracker != null) {
  1388. info = new NetworkInfo(info);
  1389. mLockdownTracker.augmentNetworkInfo(info);
  1390. }
  1391. }
  1392. Intent intent = new Intent(bcastType);
  1393. intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
  1394. intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
  1395. if (info.isFailover()) {
  1396. intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
  1397. info.setFailover(false);
  1398. }
  1399. if (info.getReason() != null) {
  1400. intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
  1401. }
  1402. if (info.getExtraInfo() != null) {
  1403. intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
  1404. info.getExtraInfo());
  1405. }
  1406. intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
  1407. return intent;
  1408. }
  1409. private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
  1410. sendStickyBroadcast(makeGeneralIntent(info, bcastType));
  1411. }
  1412. private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
  1413. Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
  1414. intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
  1415. intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
  1416. intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
  1417. final long ident = Binder.clearCallingIdentity();
  1418. try {
  1419. mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
  1420. RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
  1421. } finally {
  1422. Binder.restoreCallingIdentity(ident);
  1423. }
  1424. }
  1425. private void sendStickyBroadcast(Intent intent) {
  1426. synchronized (this) {
  1427. if (!mSystemReady) {
  1428. mInitialBroadcast = new Intent(intent);
  1429. }
  1430. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
  1431. if (VDBG) {
  1432. log("sendStickyBroadcast: action=" + intent.getAction());
  1433. }
  1434. Bundle options = null;
  1435. final long ident = Binder.clearCallingIdentity();
  1436. if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
  1437. final NetworkInfo ni = intent.getParcelableExtra(
  1438. ConnectivityManager.EXTRA_NETWORK_INFO);
  1439. if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
  1440. intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
  1441. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
  1442. } else {
  1443. BroadcastOptions opts = BroadcastOptions.makeBasic();
  1444. opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
  1445. options = opts.toBundle();
  1446. }
  1447. final IBatteryStats bs = BatteryStatsService.getService();
  1448. try {
  1449. bs.noteConnectivityChanged(intent.getIntExtra(
  1450. ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
  1451. ni != null ? ni.getState().toString() : "?");
  1452. } catch (RemoteException e) {
  1453. }
  1454. }
  1455. try {
  1456. mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
  1457. } finally {
  1458. Binder.restoreCallingIdentity(ident);
  1459. }
  1460. }
  1461. }
  1462. void systemReady() {
  1463. loadGlobalProxy();
  1464. synchronized (this) {
  1465. mSystemReady = true;
  1466. if (mInitialBroadcast != null) {
  1467. mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
  1468. mInitialBroadcast = null;
  1469. }
  1470. }
  1471. // load the global proxy at startup
  1472. mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
  1473. // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
  1474. // for user to unlock device too.
  1475. updateLockdownVpn();
  1476. // Configure whether mobile data is always on.
  1477. mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
  1478. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
  1479. mPermissionMonitor.startMonitoring();
  1480. }
  1481. /**
  1482. * Setup data activity tracking for the given network.
  1483. *
  1484. * Every {@code setupDataActivityTracking} should be paired with a
  1485. * {@link #removeDataActivityTracking} for cleanup.
  1486. */
  1487. private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
  1488. final String iface = networkAgent.linkProperties.getInterfaceName();
  1489. final int timeout;
  1490. int type = ConnectivityManager.TYPE_NONE;
  1491. if (networkAgent.networkCapabilities.hasTransport(
  1492. NetworkCapabilities.TRANSPORT_CELLULAR)) {
  1493. timeout = Settings.Global.getInt(mContext.getContentResolver(),
  1494. Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
  1495. 10);
  1496. type = ConnectivityManager.TYPE_MOBILE;
  1497. } else if (networkAgent.networkCapabilities.hasTransport(
  1498. NetworkCapabilities.TRANSPORT_WIFI)) {
  1499. timeout = Settings.Global.getInt(mContext.getContentResolver(),
  1500. Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
  1501. 15);
  1502. type = ConnectivityManager.TYPE_WIFI;
  1503. } else {
  1504. // do not track any other networks
  1505. timeout = 0;
  1506. }
  1507. if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
  1508. try {
  1509. mNetd.addIdleTimer(iface, timeout, type);
  1510. } catch (Exception e) {
  1511. // You shall not crash!
  1512. loge("Exception in setupDataActivityTracking " + e);
  1513. }
  1514. }
  1515. }
  1516. /**
  1517. * Remove data activity tracking when network disconnects.
  1518. */
  1519. private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
  1520. final String iface = networkAgent.linkProperties.getInterfaceName();
  1521. final NetworkCapabilities caps = networkAgent.networkCapabilities;
  1522. if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
  1523. caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
  1524. try {
  1525. // the call fails silently if no idletimer setup for this interface
  1526. mNetd.removeIdleTimer(iface);
  1527. } catch (Exception e) {
  1528. loge("Exception in removeDataActivityTracking " + e);
  1529. }
  1530. }
  1531. }
  1532. /**
  1533. * Reads the network specific MTU size from reources.
  1534. * and set it on it's iface.
  1535. */
  1536. private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
  1537. final String iface = newLp.getInterfaceName();
  1538. final int mtu = newLp.getMtu();
  1539. if (oldLp == null && mtu == 0) {
  1540. // Silently ignore unset MTU value.
  1541. return;
  1542. }
  1543. if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
  1544. if (VDBG) log("identical MTU - not setting");
  1545. return;
  1546. }
  1547. if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
  1548. if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
  1549. return;
  1550. }
  1551. // Cannot set MTU without interface name
  1552. if (TextUtils.isEmpty(iface)) {
  1553. loge("Setting MTU size with null iface.");
  1554. return;
  1555. }
  1556. try {
  1557. if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
  1558. mNetd.setMtu(iface, mtu);
  1559. } catch (Exception e) {
  1560. Slog.e(TAG, "exception in setMtu()" + e);
  1561. }
  1562. }
  1563. private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
  1564. private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
  1565. // Overridden for testing purposes to avoid writing to SystemProperties.
  1566. @VisibleForTesting
  1567. protected MockableSystemProperties getSystemProperties() {
  1568. return new MockableSystemProperties();
  1569. }
  1570. private void updateTcpBufferSizes(NetworkAgentInfo nai) {
  1571. if (isDefaultNetwork(nai) == false) {
  1572. return;
  1573. }
  1574. String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
  1575. String[] values = null;
  1576. if (tcpBufferSizes != null) {
  1577. values = tcpBufferSizes.split(",");
  1578. }
  1579. if (values == null || values.length != 6) {
  1580. if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
  1581. tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
  1582. values = tcpBufferSizes.split(",");
  1583. }
  1584. if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
  1585. try {
  1586. if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
  1587. final String prefix = "/sys/kernel/ipv4/tcp_";
  1588. FileUtils.stringToFile(prefix + "rmem_min", values[0]);
  1589. FileUtils.stringToFile(prefix + "rmem_def", values[1]);
  1590. FileUtils.stringToFile(prefix + "rmem_max", values[2]);
  1591. FileUtils.stringToFile(prefix + "wmem_min", values[3]);
  1592. FileUtils.stringToFile(prefix + "wmem_def", values[4]);
  1593. FileUtils.stringToFile(prefix + "wmem_max", values[5]);
  1594. mCurrentTcpBufferSizes = tcpBufferSizes;
  1595. } catch (IOException e) {
  1596. loge("Can't set TCP buffer sizes:" + e);
  1597. }
  1598. Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
  1599. Settings.Global.TCP_DEFAULT_INIT_RWND,
  1600. mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
  1601. final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
  1602. if (rwndValue != 0) {
  1603. mSystemProperties.set(sysctlKey, rwndValue.toString());
  1604. }
  1605. }
  1606. @Override
  1607. public int getRestoreDefaultNetworkDelay(int networkType) {
  1608. String restoreDefaultNetworkDelayStr = mSystemProperties.get(
  1609. NETWORK_RESTORE_DELAY_PROP_NAME);
  1610. if(restoreDefaultNetworkDelayStr != null &&
  1611. restoreDefaultNetworkDelayStr.length() != 0) {
  1612. try {
  1613. return Integer.parseInt(restoreDefaultNetworkDelayStr);
  1614. } catch (NumberFormatException e) {
  1615. }
  1616. }
  1617. // if the system property isn't set, use the value for the apn type
  1618. int ret = RESTORE_DEFAULT_NETWORK_DELAY;
  1619. if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
  1620. (mNetConfigs[networkType] != null)) {
  1621. ret = mNetConfigs[networkType].restoreTime;
  1622. }
  1623. return ret;
  1624. }
  1625. private boolean argsContain(String[] args, String target) {
  1626. for (String arg : args) {
  1627. if (target.equals(arg)) return true;
  1628. }
  1629. return false;
  1630. }
  1631. private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
  1632. final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
  1633. final long DIAG_TIME_MS = 5000;
  1634. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  1635. // Start gathering diagnostic information.
  1636. netDiags.add(new NetworkDiagnostics(
  1637. nai.network,
  1638. new LinkProperties(nai.linkProperties), // Must be a copy.
  1639. DIAG_TIME_MS));
  1640. }
  1641. for (NetworkDiagnostics netDiag : netDiags) {
  1642. pw.println();
  1643. netDiag.waitForMeasurements();
  1644. netDiag.dump(pw);
  1645. }
  1646. }
  1647. @Override
  1648. protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
  1649. final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
  1650. if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
  1651. if (argsContain(args, DIAG_ARG)) {
  1652. dumpNetworkDiagnostics(pw);
  1653. return;
  1654. } else if (argsContain(args, TETHERING_ARG)) {
  1655. mTethering.dump(fd, pw, args);
  1656. return;
  1657. }
  1658. pw.print("NetworkFactories for:");
  1659. for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
  1660. pw.print(" " + nfi.name);
  1661. }
  1662. pw.println();
  1663. pw.println();
  1664. final NetworkAgentInfo defaultNai = getDefaultNetwork();
  1665. pw.print("Active default network: ");
  1666. if (defaultNai == null) {
  1667. pw.println("none");
  1668. } else {
  1669. pw.println(defaultNai.network.netId);
  1670. }
  1671. pw.println();
  1672. pw.println("Current Networks:");
  1673. pw.increaseIndent();
  1674. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  1675. pw.println(nai.toString());
  1676. pw.increaseIndent();
  1677. pw.println(String.format(
  1678. "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
  1679. nai.numForegroundNetworkRequests(),
  1680. nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
  1681. nai.numBackgroundNetworkRequests(),
  1682. nai.numNetworkRequests()));
  1683. pw.increaseIndent();
  1684. for (int i = 0; i < nai.numNetworkRequests(); i++) {
  1685. pw.println(nai.requestAt(i).toString());
  1686. }
  1687. pw.decreaseIndent();
  1688. pw.println("Lingered:");
  1689. pw.increaseIndent();
  1690. nai.dumpLingerTimers(pw);
  1691. pw.decreaseIndent();
  1692. pw.decreaseIndent();
  1693. }
  1694. pw.decreaseIndent();
  1695. pw.println();
  1696. pw.println("Network Requests:");
  1697. pw.increaseIndent();
  1698. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  1699. pw.println(nri.toString());
  1700. }
  1701. pw.println();
  1702. pw.decreaseIndent();
  1703. mLegacyTypeTracker.dump(pw);
  1704. pw.println();
  1705. mTethering.dump(fd, pw, args);
  1706. pw.println();
  1707. mKeepaliveTracker.dump(pw);
  1708. pw.println();
  1709. dumpAvoidBadWifiSettings(pw);
  1710. if (argsContain(args, SHORT_ARG) == false) {
  1711. pw.println();
  1712. synchronized (mValidationLogs) {
  1713. pw.println("mValidationLogs (most recent first):");
  1714. for (ValidationLog p : mValidationLogs) {
  1715. pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
  1716. pw.increaseIndent();
  1717. p.mLog.dump(fd, pw, args);
  1718. pw.decreaseIndent();
  1719. }
  1720. }
  1721. pw.println();
  1722. pw.println("mNetworkRequestInfoLogs (most recent first):");
  1723. pw.increaseIndent();
  1724. mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
  1725. pw.decreaseIndent();
  1726. pw.println();
  1727. pw.println("mNetworkInfoBlockingLogs (most recent first):");
  1728. pw.increaseIndent();
  1729. mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
  1730. pw.decreaseIndent();
  1731. pw.println();
  1732. pw.println("NetTransition WakeLock activity (most recent first):");
  1733. pw.increaseIndent();
  1734. pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
  1735. pw.println("total releases: " + mTotalWakelockReleases);
  1736. pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
  1737. pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
  1738. if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
  1739. long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
  1740. pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
  1741. }
  1742. mWakelockLogs.reverseDump(fd, pw, args);
  1743. pw.decreaseIndent();
  1744. }
  1745. }
  1746. private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
  1747. if (nai.network == null) return false;
  1748. final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
  1749. if (officialNai != null && officialNai.equals(nai)) return true;
  1750. if (officialNai != null || VDBG) {
  1751. loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
  1752. " - " + nai);
  1753. }
  1754. return false;
  1755. }
  1756. // must be stateless - things change under us.
  1757. private class NetworkStateTrackerHandler extends Handler {
  1758. public NetworkStateTrackerHandler(Looper looper) {
  1759. super(looper);
  1760. }
  1761. private boolean maybeHandleAsyncChannelMessage(Message msg) {
  1762. switch (msg.what) {
  1763. default:
  1764. return false;
  1765. case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
  1766. handleAsyncChannelHalfConnect(msg);
  1767. break;
  1768. }
  1769. case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
  1770. NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
  1771. if (nai != null) nai.asyncChannel.disconnect();
  1772. break;
  1773. }
  1774. case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
  1775. handleAsyncChannelDisconnected(msg);
  1776. break;
  1777. }
  1778. }
  1779. return true;
  1780. }
  1781. private void maybeHandleNetworkAgentMessage(Message msg) {
  1782. NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
  1783. if (nai == null) {
  1784. if (VDBG) {
  1785. log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
  1786. }
  1787. return;
  1788. }
  1789. switch (msg.what) {
  1790. case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
  1791. final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
  1792. if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
  1793. networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
  1794. networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
  1795. Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
  1796. }
  1797. updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
  1798. break;
  1799. }
  1800. case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
  1801. handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
  1802. break;
  1803. }
  1804. case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
  1805. NetworkInfo info = (NetworkInfo) msg.obj;
  1806. updateNetworkInfo(nai, info);
  1807. break;
  1808. }
  1809. case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
  1810. Integer score = (Integer) msg.obj;
  1811. if (score != null) updateNetworkScore(nai, score.intValue());
  1812. break;
  1813. }
  1814. case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
  1815. if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
  1816. loge("ERROR: already-connected network explicitly selected.");
  1817. }
  1818. nai.networkMisc.explicitlySelected = true;
  1819. nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
  1820. break;
  1821. }
  1822. case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
  1823. mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
  1824. break;
  1825. }
  1826. }
  1827. }
  1828. private boolean maybeHandleNetworkMonitorMessage(Message msg) {
  1829. switch (msg.what) {
  1830. default:
  1831. return false;
  1832. case NetworkMonitor.EVENT_NETWORK_TESTED: {
  1833. final NetworkAgentInfo nai;
  1834. synchronized (mNetworkForNetId) {
  1835. nai = mNetworkForNetId.get(msg.arg2);
  1836. }
  1837. if (nai == null) break;
  1838. final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
  1839. final boolean wasValidated = nai.lastValidated;
  1840. final boolean wasDefault = isDefaultNetwork(nai);
  1841. final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
  1842. ? (PrivateDnsConfig) msg.obj : null;
  1843. final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
  1844. final boolean reevaluationRequired;
  1845. final String logMsg;
  1846. if (valid) {
  1847. reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
  1848. logMsg = (DBG && (privateDnsCfg != null))
  1849. ? " with " + privateDnsCfg.toString() : "";
  1850. } else {
  1851. reevaluationRequired = false;
  1852. logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
  1853. ? " with redirect to " + redirectUrl : "";
  1854. }
  1855. if (DBG) {
  1856. log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
  1857. }
  1858. // If there is a change in Private DNS configuration,
  1859. // trigger reevaluation of the network to test it.
  1860. if (reevaluationRequired) {
  1861. nai.networkMonitor.sendMessage(
  1862. NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
  1863. break;
  1864. }
  1865. if (valid != nai.lastValidated) {
  1866. if (wasDefault) {
  1867. metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
  1868. SystemClock.elapsedRealtime(), valid);
  1869. }
  1870. final int oldScore = nai.getCurrentScore();
  1871. nai.lastValidated = valid;
  1872. nai.everValidated |= valid;
  1873. updateCapabilities(oldScore, nai, nai.networkCapabilities);
  1874. // If score has changed, rebroadcast to NetworkFactories. b/17726566
  1875. if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
  1876. }
  1877. updateInetCondition(nai);
  1878. // Let the NetworkAgent know the state of its network
  1879. Bundle redirectUrlBundle = new Bundle();
  1880. redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
  1881. nai.asyncChannel.sendMessage(
  1882. NetworkAgent.CMD_REPORT_NETWORK_STATUS,
  1883. (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
  1884. 0, redirectUrlBundle);
  1885. if (wasValidated && !nai.lastValidated) {
  1886. handleNetworkUnvalidated(nai);
  1887. }
  1888. break;
  1889. }
  1890. case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
  1891. final int netId = msg.arg2;
  1892. final boolean visible = toBool(msg.arg1);
  1893. final NetworkAgentInfo nai;
  1894. synchronized (mNetworkForNetId) {
  1895. nai = mNetworkForNetId.get(netId);
  1896. }
  1897. // If captive portal status has changed, update capabilities or disconnect.
  1898. if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
  1899. final int oldScore = nai.getCurrentScore();
  1900. nai.lastCaptivePortalDetected = visible;
  1901. nai.everCaptivePortalDetected |= visible;
  1902. if (nai.lastCaptivePortalDetected &&
  1903. Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
  1904. if (DBG) log("Avoiding captive portal network: " + nai.name());
  1905. nai.asyncChannel.sendMessage(
  1906. NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
  1907. teardownUnneededNetwork(nai);
  1908. break;
  1909. }
  1910. updateCapabilities(oldScore, nai, nai.networkCapabilities);
  1911. }
  1912. if (!visible) {
  1913. mNotifier.clearNotification(netId);
  1914. } else {
  1915. if (nai == null) {
  1916. loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
  1917. break;
  1918. }
  1919. if (!nai.networkMisc.provisioningNotificationDisabled) {
  1920. mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
  1921. (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
  1922. }
  1923. }
  1924. break;
  1925. }
  1926. case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
  1927. final NetworkAgentInfo nai;
  1928. synchronized (mNetworkForNetId) {
  1929. nai = mNetworkForNetId.get(msg.arg2);
  1930. }
  1931. if (nai == null) break;
  1932. final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
  1933. final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
  1934. if (nai.lastValidated && reevaluationRequired) {
  1935. nai.networkMonitor.sendMessage(
  1936. NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
  1937. }
  1938. break;
  1939. }
  1940. }
  1941. return true;
  1942. }
  1943. private int getCaptivePortalMode() {
  1944. return Settings.Global.getInt(mContext.getContentResolver(),
  1945. Settings.Global.CAPTIVE_PORTAL_MODE,
  1946. Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
  1947. }
  1948. private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
  1949. switch (msg.what) {
  1950. default:
  1951. return false;
  1952. case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
  1953. NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
  1954. if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
  1955. handleLingerComplete(nai);
  1956. }
  1957. break;
  1958. }
  1959. }
  1960. return true;
  1961. }
  1962. @Override
  1963. public void handleMessage(Message msg) {
  1964. if (!maybeHandleAsyncChannelMessage(msg) &&
  1965. !maybeHandleNetworkMonitorMessage(msg) &&
  1966. !maybeHandleNetworkAgentInfoMessage(msg)) {
  1967. maybeHandleNetworkAgentMessage(msg);
  1968. }
  1969. }
  1970. }
  1971. private void handlePrivateDnsSettingsChanged() {
  1972. final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
  1973. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  1974. // Private DNS only ever applies to networks that might provide
  1975. // Internet access and therefore also require validation.
  1976. if (!NetworkMonitor.isValidationRequired(
  1977. mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
  1978. continue;
  1979. }
  1980. // Notify the NetworkMonitor thread in case it needs to cancel or
  1981. // schedule DNS resolutions. If a DNS resolution is required the
  1982. // result will be sent back to us.
  1983. nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
  1984. if (!cfg.inStrictMode()) {
  1985. // No strict mode hostname DNS resolution needed, so just update
  1986. // DNS settings directly. In opportunistic and "off" modes this
  1987. // just reprograms netd with the network-supplied DNS servers
  1988. // (and of course the boolean of whether or not to attempt TLS).
  1989. //
  1990. // TODO: Consider code flow parity with strict mode, i.e. having
  1991. // NetworkMonitor relay the PrivateDnsConfig back to us and then
  1992. // performing this call at that time.
  1993. updatePrivateDns(nai, cfg);
  1994. }
  1995. }
  1996. }
  1997. private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
  1998. final boolean reevaluationRequired = true;
  1999. final boolean dontReevaluate = false;
  2000. final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
  2001. updateDnses(nai.linkProperties, null, nai.network.netId);
  2002. if (newCfg == null) {
  2003. if (oldCfg == null) return dontReevaluate;
  2004. return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
  2005. }
  2006. if (oldCfg == null) {
  2007. return newCfg.useTls ? reevaluationRequired : dontReevaluate;
  2008. }
  2009. if (oldCfg.useTls != newCfg.useTls) {
  2010. return reevaluationRequired;
  2011. }
  2012. if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
  2013. return reevaluationRequired;
  2014. }
  2015. return dontReevaluate;
  2016. }
  2017. private void updateLingerState(NetworkAgentInfo nai, long now) {
  2018. // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
  2019. // 2. If the network was lingering and there are now requests, unlinger it.
  2020. // 3. If this network is unneeded (which implies it is not lingering), and there is at least
  2021. // one lingered request, start lingering.
  2022. nai.updateLingerTimer();
  2023. if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
  2024. if (DBG) log("Unlingering " + nai.name());
  2025. nai.unlinger();
  2026. logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
  2027. } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
  2028. int lingerTime = (int) (nai.getLingerExpiry() - now);
  2029. if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
  2030. nai.linger();
  2031. logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
  2032. notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
  2033. }
  2034. }
  2035. private void handleAsyncChannelHalfConnect(Message msg) {
  2036. AsyncChannel ac = (AsyncChannel) msg.obj;
  2037. if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
  2038. if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
  2039. if (VDBG) log("NetworkFactory connected");
  2040. // A network factory has connected. Send it all current NetworkRequests.
  2041. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  2042. if (nri.request.isListen()) continue;
  2043. NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
  2044. ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
  2045. (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
  2046. }
  2047. } else {
  2048. loge("Error connecting NetworkFactory");
  2049. mNetworkFactoryInfos.remove(msg.obj);
  2050. }
  2051. } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
  2052. if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
  2053. if (VDBG) log("NetworkAgent connected");
  2054. // A network agent has requested a connection. Establish the connection.
  2055. mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
  2056. sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
  2057. } else {
  2058. loge("Error connecting NetworkAgent");
  2059. NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
  2060. if (nai != null) {
  2061. final boolean wasDefault = isDefaultNetwork(nai);
  2062. synchronized (mNetworkForNetId) {
  2063. mNetworkForNetId.remove(nai.network.netId);
  2064. mNetIdInUse.delete(nai.network.netId);
  2065. }
  2066. // Just in case.
  2067. mLegacyTypeTracker.remove(nai, wasDefault);
  2068. }
  2069. }
  2070. }
  2071. }
  2072. private void handleAsyncChannelDisconnected(Message msg) {
  2073. NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
  2074. if (nai != null) {
  2075. if (DBG) {
  2076. log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
  2077. }
  2078. // A network agent has disconnected.
  2079. // TODO - if we move the logic to the network agent (have them disconnect
  2080. // because they lost all their requests or because their score isn't good)
  2081. // then they would disconnect organically, report their new state and then
  2082. // disconnect the channel.
  2083. if (nai.networkInfo.isConnected()) {
  2084. nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
  2085. null, null);
  2086. }
  2087. final boolean wasDefault = isDefaultNetwork(nai);
  2088. if (wasDefault) {
  2089. mDefaultInetConditionPublished = 0;
  2090. // Log default network disconnection before required book-keeping.
  2091. // Let rematchAllNetworksAndRequests() below record a new default network event
  2092. // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
  2093. // whose timestamps tell how long it takes to recover a default network.
  2094. long now = SystemClock.elapsedRealtime();
  2095. metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
  2096. }
  2097. notifyIfacesChangedForNetworkStats();
  2098. // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
  2099. // by other networks that are already connected. Perhaps that can be done by
  2100. // sending all CALLBACK_LOST messages (for requests, not listens) at the end
  2101. // of rematchAllNetworksAndRequests
  2102. notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
  2103. mKeepaliveTracker.handleStopAllKeepalives(nai,
  2104. ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
  2105. for (String iface : nai.linkProperties.getAllInterfaceNames()) {
  2106. // Disable wakeup packet monitoring for each interface.
  2107. wakeupModifyInterface(iface, nai.networkCapabilities, false);
  2108. }
  2109. nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
  2110. mNetworkAgentInfos.remove(msg.replyTo);
  2111. nai.maybeStopClat();
  2112. synchronized (mNetworkForNetId) {
  2113. // Remove the NetworkAgent, but don't mark the netId as
  2114. // available until we've told netd to delete it below.
  2115. mNetworkForNetId.remove(nai.network.netId);
  2116. }
  2117. // Remove all previously satisfied requests.
  2118. for (int i = 0; i < nai.numNetworkRequests(); i++) {
  2119. NetworkRequest request = nai.requestAt(i);
  2120. NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
  2121. if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
  2122. clearNetworkForRequest(request.requestId);
  2123. sendUpdatedScoreToFactories(request, 0);
  2124. }
  2125. }
  2126. nai.clearLingerState();
  2127. if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
  2128. removeDataActivityTracking(nai);
  2129. notifyLockdownVpn(nai);
  2130. ensureNetworkTransitionWakelock(nai.name());
  2131. }
  2132. mLegacyTypeTracker.remove(nai, wasDefault);
  2133. rematchAllNetworksAndRequests(null, 0);
  2134. mLingerMonitor.noteDisconnect(nai);
  2135. if (nai.created) {
  2136. // Tell netd to clean up the configuration for this network
  2137. // (routing rules, DNS, etc).
  2138. // This may be slow as it requires a lot of netd shelling out to ip and
  2139. // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
  2140. // after we've rematched networks with requests which should make a potential
  2141. // fallback network the default or requested a new network from the
  2142. // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
  2143. // long time.
  2144. try {
  2145. mNetd.removeNetwork(nai.network.netId);
  2146. } catch (Exception e) {
  2147. loge("Exception removing network: " + e);
  2148. }
  2149. mDnsManager.removeNetwork(nai.network);
  2150. }
  2151. synchronized (mNetworkForNetId) {
  2152. mNetIdInUse.delete(nai.network.netId);
  2153. }
  2154. } else {
  2155. NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
  2156. if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
  2157. }
  2158. }
  2159. // If this method proves to be too slow then we can maintain a separate
  2160. // pendingIntent => NetworkRequestInfo map.
  2161. // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
  2162. private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
  2163. Intent intent = pendingIntent.getIntent();
  2164. for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
  2165. PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
  2166. if (existingPendingIntent != null &&
  2167. existingPendingIntent.getIntent().filterEquals(intent)) {
  2168. return entry.getValue();
  2169. }
  2170. }
  2171. return null;
  2172. }
  2173. private void handleRegisterNetworkRequestWithIntent(Message msg) {
  2174. final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
  2175. NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
  2176. if (existingRequest != null) { // remove the existing request.
  2177. if (DBG) log("Replacing " + existingRequest.request + " with "
  2178. + nri.request + " because their intents matched.");
  2179. handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
  2180. }
  2181. handleRegisterNetworkRequest(nri);
  2182. }
  2183. private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
  2184. mNetworkRequests.put(nri.request, nri);
  2185. mNetworkRequestInfoLogs.log("REGISTER " + nri);
  2186. if (nri.request.isListen()) {
  2187. for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
  2188. if (nri.request.networkCapabilities.hasSignalStrength() &&
  2189. network.satisfiesImmutableCapabilitiesOf(nri.request)) {
  2190. updateSignalStrengthThresholds(network, "REGISTER", nri.request);
  2191. }
  2192. }
  2193. }
  2194. rematchAllNetworksAndRequests(null, 0);
  2195. if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
  2196. sendUpdatedScoreToFactories(nri.request, 0);
  2197. }
  2198. }
  2199. private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
  2200. int callingUid) {
  2201. NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
  2202. if (nri != null) {
  2203. handleReleaseNetworkRequest(nri.request, callingUid);
  2204. }
  2205. }
  2206. // Determines whether the network is the best (or could become the best, if it validated), for
  2207. // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
  2208. // on the value of reason:
  2209. //
  2210. // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
  2211. // then it should be torn down.
  2212. // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
  2213. // then it should be lingered.
  2214. private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
  2215. final int numRequests;
  2216. switch (reason) {
  2217. case TEARDOWN:
  2218. numRequests = nai.numRequestNetworkRequests();
  2219. break;
  2220. case LINGER:
  2221. numRequests = nai.numForegroundNetworkRequests();
  2222. break;
  2223. default:
  2224. Slog.wtf(TAG, "Invalid reason. Cannot happen.");
  2225. return true;
  2226. }
  2227. if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
  2228. return false;
  2229. }
  2230. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  2231. if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
  2232. // Background requests don't affect lingering.
  2233. continue;
  2234. }
  2235. // If this Network is already the highest scoring Network for a request, or if
  2236. // there is hope for it to become one if it validated, then it is needed.
  2237. if (nri.request.isRequest() && nai.satisfies(nri.request) &&
  2238. (nai.isSatisfyingRequest(nri.request.requestId) ||
  2239. // Note that this catches two important cases:
  2240. // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
  2241. // is currently satisfying the request. This is desirable when
  2242. // cellular ends up validating but WiFi does not.
  2243. // 2. Unvalidated WiFi will not be reaped when validated cellular
  2244. // is currently satisfying the request. This is desirable when
  2245. // WiFi ends up validating and out scoring cellular.
  2246. getNetworkForRequest(nri.request.requestId).getCurrentScore() <
  2247. nai.getCurrentScoreAsValidated())) {
  2248. return false;
  2249. }
  2250. }
  2251. return true;
  2252. }
  2253. private NetworkRequestInfo getNriForAppRequest(
  2254. NetworkRequest request, int callingUid, String requestedOperation) {
  2255. final NetworkRequestInfo nri = mNetworkRequests.get(request);
  2256. if (nri != null) {
  2257. if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
  2258. log(String.format("UID %d attempted to %s for unowned request %s",
  2259. callingUid, requestedOperation, nri));
  2260. return null;
  2261. }
  2262. }
  2263. return nri;
  2264. }
  2265. private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
  2266. if (mNetworkRequests.get(nri.request) == null) {
  2267. return;
  2268. }
  2269. if (getNetworkForRequest(nri.request.requestId) != null) {
  2270. return;
  2271. }
  2272. if (VDBG || (DBG && nri.request.isRequest())) {
  2273. log("releasing " + nri.request + " (timeout)");
  2274. }
  2275. handleRemoveNetworkRequest(nri);
  2276. callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
  2277. }
  2278. private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
  2279. final NetworkRequestInfo nri =
  2280. getNriForAppRequest(request, callingUid, "release NetworkRequest");
  2281. if (nri == null) {
  2282. return;
  2283. }
  2284. if (VDBG || (DBG && nri.request.isRequest())) {
  2285. log("releasing " + nri.request + " (release request)");
  2286. }
  2287. handleRemoveNetworkRequest(nri);
  2288. }
  2289. private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
  2290. nri.unlinkDeathRecipient();
  2291. mNetworkRequests.remove(nri.request);
  2292. synchronized (mUidToNetworkRequestCount) {
  2293. int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
  2294. if (requests < 1) {
  2295. Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
  2296. nri.mUid);
  2297. } else if (requests == 1) {
  2298. mUidToNetworkRequestCount.removeAt(
  2299. mUidToNetworkRequestCount.indexOfKey(nri.mUid));
  2300. } else {
  2301. mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
  2302. }
  2303. }
  2304. mNetworkRequestInfoLogs.log("RELEASE " + nri);
  2305. if (nri.request.isRequest()) {
  2306. boolean wasKept = false;
  2307. NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
  2308. if (nai != null) {
  2309. boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
  2310. nai.removeRequest(nri.request.requestId);
  2311. if (VDBG) {
  2312. log(" Removing from current network " + nai.name() +
  2313. ", leaving " + nai.numNetworkRequests() + " requests.");
  2314. }
  2315. // If there are still lingered requests on this network, don't tear it down,
  2316. // but resume lingering instead.
  2317. updateLingerState(nai, SystemClock.elapsedRealtime());
  2318. if (unneeded(nai, UnneededFor.TEARDOWN)) {
  2319. if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
  2320. teardownUnneededNetwork(nai);
  2321. } else {
  2322. wasKept = true;
  2323. }
  2324. clearNetworkForRequest(nri.request.requestId);
  2325. if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
  2326. // Went from foreground to background.
  2327. updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
  2328. }
  2329. }
  2330. // TODO: remove this code once we know that the Slog.wtf is never hit.
  2331. //
  2332. // Find all networks that are satisfying this request and remove the request
  2333. // from their request lists.
  2334. // TODO - it's my understanding that for a request there is only a single
  2335. // network satisfying it, so this loop is wasteful
  2336. for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
  2337. if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
  2338. Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
  2339. otherNai.name() + ", but mNetworkAgentInfos says " +
  2340. (nai != null ? nai.name() : "null"));
  2341. }
  2342. }
  2343. // Maintain the illusion. When this request arrived, we might have pretended
  2344. // that a network connected to serve it, even though the network was already
  2345. // connected. Now that this request has gone away, we might have to pretend
  2346. // that the network disconnected. LegacyTypeTracker will generate that
  2347. // phantom disconnect for this type.
  2348. if (nri.request.legacyType != TYPE_NONE && nai != null) {
  2349. boolean doRemove = true;
  2350. if (wasKept) {
  2351. // check if any of the remaining requests for this network are for the
  2352. // same legacy type - if so, don't remove the nai
  2353. for (int i = 0; i < nai.numNetworkRequests(); i++) {
  2354. NetworkRequest otherRequest = nai.requestAt(i);
  2355. if (otherRequest.legacyType == nri.request.legacyType &&
  2356. otherRequest.isRequest()) {
  2357. if (DBG) log(" still have other legacy request - leaving");
  2358. doRemove = false;
  2359. }
  2360. }
  2361. }
  2362. if (doRemove) {
  2363. mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
  2364. }
  2365. }
  2366. for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
  2367. nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
  2368. nri.request);
  2369. }
  2370. } else {
  2371. // listens don't have a singular affectedNetwork. Check all networks to see
  2372. // if this listen request applies and remove it.
  2373. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  2374. nai.removeRequest(nri.request.requestId);
  2375. if (nri.request.networkCapabilities.hasSignalStrength() &&
  2376. nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
  2377. updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
  2378. }
  2379. }
  2380. }
  2381. }
  2382. @Override
  2383. public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
  2384. enforceConnectivityInternalPermission();
  2385. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
  2386. encodeBool(accept), encodeBool(always), network));
  2387. }
  2388. @Override
  2389. public void setAvoidUnvalidated(Network network) {
  2390. enforceConnectivityInternalPermission();
  2391. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
  2392. }
  2393. private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
  2394. if (DBG) log("handleSetAcceptUnvalidated network=" + network +
  2395. " accept=" + accept + " always=" + always);
  2396. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2397. if (nai == null) {
  2398. // Nothing to do.
  2399. return;
  2400. }
  2401. if (nai.everValidated) {
  2402. // The network validated while the dialog box was up. Take no action.
  2403. return;
  2404. }
  2405. if (!nai.networkMisc.explicitlySelected) {
  2406. Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
  2407. }
  2408. if (accept != nai.networkMisc.acceptUnvalidated) {
  2409. int oldScore = nai.getCurrentScore();
  2410. nai.networkMisc.acceptUnvalidated = accept;
  2411. rematchAllNetworksAndRequests(nai, oldScore);
  2412. sendUpdatedScoreToFactories(nai);
  2413. }
  2414. if (always) {
  2415. nai.asyncChannel.sendMessage(
  2416. NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
  2417. }
  2418. if (!accept) {
  2419. // Tell the NetworkAgent to not automatically reconnect to the network.
  2420. nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
  2421. // Teardown the nework.
  2422. teardownUnneededNetwork(nai);
  2423. }
  2424. }
  2425. private void handleSetAvoidUnvalidated(Network network) {
  2426. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2427. if (nai == null || nai.lastValidated) {
  2428. // Nothing to do. The network either disconnected or revalidated.
  2429. return;
  2430. }
  2431. if (!nai.avoidUnvalidated) {
  2432. int oldScore = nai.getCurrentScore();
  2433. nai.avoidUnvalidated = true;
  2434. rematchAllNetworksAndRequests(nai, oldScore);
  2435. sendUpdatedScoreToFactories(nai);
  2436. }
  2437. }
  2438. private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
  2439. if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
  2440. mHandler.sendMessageDelayed(
  2441. mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
  2442. PROMPT_UNVALIDATED_DELAY_MS);
  2443. }
  2444. @Override
  2445. public void startCaptivePortalApp(Network network) {
  2446. enforceConnectivityInternalPermission();
  2447. mHandler.post(() -> {
  2448. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2449. if (nai == null) return;
  2450. if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
  2451. nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
  2452. });
  2453. }
  2454. public boolean avoidBadWifi() {
  2455. return mMultinetworkPolicyTracker.getAvoidBadWifi();
  2456. }
  2457. private void rematchForAvoidBadWifiUpdate() {
  2458. rematchAllNetworksAndRequests(null, 0);
  2459. for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
  2460. if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
  2461. sendUpdatedScoreToFactories(nai);
  2462. }
  2463. }
  2464. }
  2465. // TODO: Evaluate whether this is of interest to other consumers of
  2466. // MultinetworkPolicyTracker and worth moving out of here.
  2467. private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
  2468. final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
  2469. if (!configRestrict) {
  2470. pw.println("Bad Wi-Fi avoidance: unrestricted");
  2471. return;
  2472. }
  2473. pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
  2474. pw.increaseIndent();
  2475. pw.println("Config restrict: " + configRestrict);
  2476. final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
  2477. String description;
  2478. // Can't use a switch statement because strings are legal case labels, but null is not.
  2479. if ("0".equals(value)) {
  2480. description = "get stuck";
  2481. } else if (value == null) {
  2482. description = "prompt";
  2483. } else if ("1".equals(value)) {
  2484. description = "avoid";
  2485. } else {
  2486. description = value + " (?)";
  2487. }
  2488. pw.println("User setting: " + description);
  2489. pw.println("Network overrides:");
  2490. pw.increaseIndent();
  2491. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  2492. if (nai.avoidUnvalidated) {
  2493. pw.println(nai.name());
  2494. }
  2495. }
  2496. pw.decreaseIndent();
  2497. pw.decreaseIndent();
  2498. }
  2499. private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
  2500. final String action;
  2501. switch (type) {
  2502. case NO_INTERNET:
  2503. action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
  2504. break;
  2505. case LOST_INTERNET:
  2506. action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
  2507. break;
  2508. default:
  2509. Slog.wtf(TAG, "Unknown notification type " + type);
  2510. return;
  2511. }
  2512. Intent intent = new Intent(action);
  2513. intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
  2514. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  2515. intent.setClassName("com.android.settings",
  2516. "com.android.settings.wifi.WifiNoInternetDialog");
  2517. PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
  2518. mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
  2519. mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
  2520. }
  2521. private void handlePromptUnvalidated(Network network) {
  2522. if (VDBG) log("handlePromptUnvalidated " + network);
  2523. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2524. // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
  2525. // we haven't already been told to switch to it regardless of whether it validated or not.
  2526. // Also don't prompt on captive portals because we're already prompting the user to sign in.
  2527. if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
  2528. !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
  2529. return;
  2530. }
  2531. showValidationNotification(nai, NotificationType.NO_INTERNET);
  2532. }
  2533. private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
  2534. NetworkCapabilities nc = nai.networkCapabilities;
  2535. if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
  2536. if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
  2537. mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
  2538. showValidationNotification(nai, NotificationType.LOST_INTERNET);
  2539. }
  2540. }
  2541. @Override
  2542. public int getMultipathPreference(Network network) {
  2543. enforceAccessPermission();
  2544. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2545. if (nai != null && nai.networkCapabilities
  2546. .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
  2547. return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
  2548. }
  2549. return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
  2550. }
  2551. private class InternalHandler extends Handler {
  2552. public InternalHandler(Looper looper) {
  2553. super(looper);
  2554. }
  2555. @Override
  2556. public void handleMessage(Message msg) {
  2557. switch (msg.what) {
  2558. case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
  2559. case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
  2560. handleReleaseNetworkTransitionWakelock(msg.what);
  2561. break;
  2562. }
  2563. case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
  2564. handleDeprecatedGlobalHttpProxy();
  2565. break;
  2566. }
  2567. case EVENT_PROXY_HAS_CHANGED: {
  2568. handleApplyDefaultProxy((ProxyInfo)msg.obj);
  2569. break;
  2570. }
  2571. case EVENT_REGISTER_NETWORK_FACTORY: {
  2572. handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
  2573. break;
  2574. }
  2575. case EVENT_UNREGISTER_NETWORK_FACTORY: {
  2576. handleUnregisterNetworkFactory((Messenger)msg.obj);
  2577. break;
  2578. }
  2579. case EVENT_REGISTER_NETWORK_AGENT: {
  2580. handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
  2581. break;
  2582. }
  2583. case EVENT_REGISTER_NETWORK_REQUEST:
  2584. case EVENT_REGISTER_NETWORK_LISTENER: {
  2585. handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
  2586. break;
  2587. }
  2588. case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
  2589. case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
  2590. handleRegisterNetworkRequestWithIntent(msg);
  2591. break;
  2592. }
  2593. case EVENT_TIMEOUT_NETWORK_REQUEST: {
  2594. NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
  2595. handleTimedOutNetworkRequest(nri);
  2596. break;
  2597. }
  2598. case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
  2599. handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
  2600. break;
  2601. }
  2602. case EVENT_RELEASE_NETWORK_REQUEST: {
  2603. handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
  2604. break;
  2605. }
  2606. case EVENT_SET_ACCEPT_UNVALIDATED: {
  2607. Network network = (Network) msg.obj;
  2608. handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
  2609. break;
  2610. }
  2611. case EVENT_SET_AVOID_UNVALIDATED: {
  2612. handleSetAvoidUnvalidated((Network) msg.obj);
  2613. break;
  2614. }
  2615. case EVENT_PROMPT_UNVALIDATED: {
  2616. handlePromptUnvalidated((Network) msg.obj);
  2617. break;
  2618. }
  2619. case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
  2620. handleMobileDataAlwaysOn();
  2621. break;
  2622. }
  2623. // Sent by KeepaliveTracker to process an app request on the state machine thread.
  2624. case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
  2625. mKeepaliveTracker.handleStartKeepalive(msg);
  2626. break;
  2627. }
  2628. // Sent by KeepaliveTracker to process an app request on the state machine thread.
  2629. case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
  2630. NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
  2631. int slot = msg.arg1;
  2632. int reason = msg.arg2;
  2633. mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
  2634. break;
  2635. }
  2636. case EVENT_SYSTEM_READY: {
  2637. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  2638. nai.networkMonitor.systemReady = true;
  2639. }
  2640. break;
  2641. }
  2642. case EVENT_REVALIDATE_NETWORK: {
  2643. handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
  2644. break;
  2645. }
  2646. case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
  2647. handlePrivateDnsSettingsChanged();
  2648. break;
  2649. }
  2650. }
  2651. }
  2652. // javadoc from interface
  2653. @Override
  2654. public int tether(String iface, String callerPkg) {
  2655. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2656. if (isTetheringSupported()) {
  2657. final int status = mTethering.tether(iface);
  2658. return status;
  2659. } else {
  2660. return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
  2661. }
  2662. }
  2663. // javadoc from interface
  2664. @Override
  2665. public int untether(String iface, String callerPkg) {
  2666. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2667. if (isTetheringSupported()) {
  2668. final int status = mTethering.untether(iface);
  2669. return status;
  2670. } else {
  2671. return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
  2672. }
  2673. }
  2674. // javadoc from interface
  2675. @Override
  2676. public int getLastTetherError(String iface) {
  2677. enforceTetherAccessPermission();
  2678. if (isTetheringSupported()) {
  2679. return mTethering.getLastTetherError(iface);
  2680. } else {
  2681. return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
  2682. }
  2683. }
  2684. // TODO - proper iface API for selection by property, inspection, etc
  2685. @Override
  2686. public String[] getTetherableUsbRegexs() {
  2687. enforceTetherAccessPermission();
  2688. if (isTetheringSupported()) {
  2689. return mTethering.getTetherableUsbRegexs();
  2690. } else {
  2691. return new String[0];
  2692. }
  2693. }
  2694. @Override
  2695. public String[] getTetherableWifiRegexs() {
  2696. enforceTetherAccessPermission();
  2697. if (isTetheringSupported()) {
  2698. return mTethering.getTetherableWifiRegexs();
  2699. } else {
  2700. return new String[0];
  2701. }
  2702. }
  2703. @Override
  2704. public String[] getTetherableBluetoothRegexs() {
  2705. enforceTetherAccessPermission();
  2706. if (isTetheringSupported()) {
  2707. return mTethering.getTetherableBluetoothRegexs();
  2708. } else {
  2709. return new String[0];
  2710. }
  2711. }
  2712. @Override
  2713. public int setUsbTethering(boolean enable, String callerPkg) {
  2714. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2715. if (isTetheringSupported()) {
  2716. return mTethering.setUsbTethering(enable);
  2717. } else {
  2718. return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
  2719. }
  2720. }
  2721. // TODO - move iface listing, queries, etc to new module
  2722. // javadoc from interface
  2723. @Override
  2724. public String[] getTetherableIfaces() {
  2725. enforceTetherAccessPermission();
  2726. return mTethering.getTetherableIfaces();
  2727. }
  2728. @Override
  2729. public String[] getTetheredIfaces() {
  2730. enforceTetherAccessPermission();
  2731. return mTethering.getTetheredIfaces();
  2732. }
  2733. @Override
  2734. public String[] getTetheringErroredIfaces() {
  2735. enforceTetherAccessPermission();
  2736. return mTethering.getErroredIfaces();
  2737. }
  2738. @Override
  2739. public String[] getTetheredDhcpRanges() {
  2740. enforceConnectivityInternalPermission();
  2741. return mTethering.getTetheredDhcpRanges();
  2742. }
  2743. @Override
  2744. public boolean isTetheringSupported(String callerPkg) {
  2745. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2746. return isTetheringSupported();
  2747. }
  2748. // if ro.tether.denied = true we default to no tethering
  2749. // gservices could set the secure setting to 1 though to enable it on a build where it
  2750. // had previously been turned off.
  2751. private boolean isTetheringSupported() {
  2752. int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
  2753. boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
  2754. Settings.Global.TETHER_SUPPORTED, defaultVal));
  2755. boolean tetherEnabledInSettings = tetherSupported
  2756. && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
  2757. // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
  2758. boolean adminUser = false;
  2759. final long token = Binder.clearCallingIdentity();
  2760. try {
  2761. adminUser = mUserManager.isAdminUser();
  2762. } finally {
  2763. Binder.restoreCallingIdentity(token);
  2764. }
  2765. return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
  2766. }
  2767. @Override
  2768. public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
  2769. String callerPkg) {
  2770. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2771. if (!isTetheringSupported()) {
  2772. receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
  2773. return;
  2774. }
  2775. mTethering.startTethering(type, receiver, showProvisioningUi);
  2776. }
  2777. @Override
  2778. public void stopTethering(int type, String callerPkg) {
  2779. ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
  2780. mTethering.stopTethering(type);
  2781. }
  2782. // Called when we lose the default network and have no replacement yet.
  2783. // This will automatically be cleared after X seconds or a new default network
  2784. // becomes CONNECTED, whichever happens first. The timer is started by the
  2785. // first caller and not restarted by subsequent callers.
  2786. private void ensureNetworkTransitionWakelock(String forWhom) {
  2787. synchronized (this) {
  2788. if (mNetTransitionWakeLock.isHeld()) {
  2789. return;
  2790. }
  2791. mNetTransitionWakeLock.acquire();
  2792. mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
  2793. mTotalWakelockAcquisitions++;
  2794. }
  2795. mWakelockLogs.log("ACQUIRE for " + forWhom);
  2796. Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
  2797. mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
  2798. }
  2799. // Called when we gain a new default network to release the network transition wakelock in a
  2800. // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
  2801. // message is cancelled.
  2802. private void scheduleReleaseNetworkTransitionWakelock() {
  2803. synchronized (this) {
  2804. if (!mNetTransitionWakeLock.isHeld()) {
  2805. return; // expiry message released the lock first.
  2806. }
  2807. }
  2808. // Cancel self timeout on wakelock hold.
  2809. mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
  2810. Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
  2811. mHandler.sendMessageDelayed(msg, 1000);
  2812. }
  2813. // Called when either message of ensureNetworkTransitionWakelock or
  2814. // scheduleReleaseNetworkTransitionWakelock is processed.
  2815. private void handleReleaseNetworkTransitionWakelock(int eventId) {
  2816. String event = eventName(eventId);
  2817. synchronized (this) {
  2818. if (!mNetTransitionWakeLock.isHeld()) {
  2819. mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
  2820. Slog.w(TAG, "expected Net Transition WakeLock to be held");
  2821. return;
  2822. }
  2823. mNetTransitionWakeLock.release();
  2824. long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
  2825. mTotalWakelockDurationMs += lockDuration;
  2826. mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
  2827. mTotalWakelockReleases++;
  2828. }
  2829. mWakelockLogs.log(String.format("RELEASE (%s)", event));
  2830. }
  2831. // 100 percent is full good, 0 is full bad.
  2832. @Override
  2833. public void reportInetCondition(int networkType, int percentage) {
  2834. NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
  2835. if (nai == null) return;
  2836. reportNetworkConnectivity(nai.network, percentage > 50);
  2837. }
  2838. @Override
  2839. public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
  2840. enforceAccessPermission();
  2841. enforceInternetPermission();
  2842. final int uid = Binder.getCallingUid();
  2843. final int connectivityInfo = encodeBool(hasConnectivity);
  2844. mHandler.sendMessage(
  2845. mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
  2846. }
  2847. private void handleReportNetworkConnectivity(
  2848. Network network, int uid, boolean hasConnectivity) {
  2849. final NetworkAgentInfo nai;
  2850. if (network == null) {
  2851. nai = getDefaultNetwork();
  2852. } else {
  2853. nai = getNetworkAgentInfoForNetwork(network);
  2854. }
  2855. if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
  2856. nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
  2857. return;
  2858. }
  2859. // Revalidate if the app report does not match our current validated state.
  2860. if (hasConnectivity == nai.lastValidated) {
  2861. return;
  2862. }
  2863. if (DBG) {
  2864. int netid = nai.network.netId;
  2865. log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
  2866. }
  2867. // Validating a network that has not yet connected could result in a call to
  2868. // rematchNetworkAndRequests() which is not meant to work on such networks.
  2869. if (!nai.everConnected) {
  2870. return;
  2871. }
  2872. LinkProperties lp = getLinkProperties(nai);
  2873. if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
  2874. return;
  2875. }
  2876. nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
  2877. }
  2878. private ProxyInfo getDefaultProxy() {
  2879. // this information is already available as a world read/writable jvm property
  2880. // so this API change wouldn't have a benifit. It also breaks the passing
  2881. // of proxy info to all the JVMs.
  2882. // enforceAccessPermission();
  2883. synchronized (mProxyLock) {
  2884. ProxyInfo ret = mGlobalProxy;
  2885. if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
  2886. return ret;
  2887. }
  2888. }
  2889. @Override
  2890. public ProxyInfo getProxyForNetwork(Network network) {
  2891. if (network == null) return getDefaultProxy();
  2892. final ProxyInfo globalProxy = getGlobalProxy();
  2893. if (globalProxy != null) return globalProxy;
  2894. if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
  2895. // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
  2896. // caller may not have.
  2897. final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
  2898. if (nai == null) return null;
  2899. synchronized (nai) {
  2900. final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
  2901. if (proxyInfo == null) return null;
  2902. return new ProxyInfo(proxyInfo);
  2903. }
  2904. }
  2905. // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
  2906. // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
  2907. // proxy is null then there is no proxy in place).
  2908. private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
  2909. if (proxy != null && TextUtils.isEmpty(proxy.getHost())
  2910. && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
  2911. proxy = null;
  2912. }
  2913. return proxy;
  2914. }
  2915. // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
  2916. // better for determining if a new proxy broadcast is necessary:
  2917. // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
  2918. // avoid unnecessary broadcasts.
  2919. // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
  2920. // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
  2921. // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
  2922. // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
  2923. // all set.
  2924. private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
  2925. a = canonicalizeProxyInfo(a);
  2926. b = canonicalizeProxyInfo(b);
  2927. // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
  2928. // hosts even when PAC URLs are present to account for the legacy PAC resolver.
  2929. return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
  2930. }
  2931. public void setGlobalProxy(ProxyInfo proxyProperties) {
  2932. enforceConnectivityInternalPermission();
  2933. synchronized (mProxyLock) {
  2934. if (proxyProperties == mGlobalProxy) return;
  2935. if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
  2936. if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
  2937. String host = "";
  2938. int port = 0;
  2939. String exclList = "";
  2940. String pacFileUrl = "";
  2941. if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
  2942. !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
  2943. if (!proxyProperties.isValid()) {
  2944. if (DBG)
  2945. log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
  2946. return;
  2947. }
  2948. mGlobalProxy = new ProxyInfo(proxyProperties);
  2949. host = mGlobalProxy.getHost();
  2950. port = mGlobalProxy.getPort();
  2951. exclList = mGlobalProxy.getExclusionListAsString();
  2952. if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
  2953. pacFileUrl = proxyProperties.getPacFileUrl().toString();
  2954. }
  2955. } else {
  2956. mGlobalProxy = null;
  2957. }
  2958. ContentResolver res = mContext.getContentResolver();
  2959. final long token = Binder.clearCallingIdentity();
  2960. try {
  2961. Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
  2962. Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
  2963. Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
  2964. exclList);
  2965. Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
  2966. } finally {
  2967. Binder.restoreCallingIdentity(token);
  2968. }
  2969. if (mGlobalProxy == null) {
  2970. proxyProperties = mDefaultProxy;
  2971. }
  2972. sendProxyBroadcast(proxyProperties);
  2973. }
  2974. }
  2975. private void loadGlobalProxy() {
  2976. ContentResolver res = mContext.getContentResolver();
  2977. String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
  2978. int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
  2979. String exclList = Settings.Global.getString(res,
  2980. Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
  2981. String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
  2982. if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
  2983. ProxyInfo proxyProperties;
  2984. if (!TextUtils.isEmpty(pacFileUrl)) {
  2985. proxyProperties = new ProxyInfo(pacFileUrl);
  2986. } else {
  2987. proxyProperties = new ProxyInfo(host, port, exclList);
  2988. }
  2989. if (!proxyProperties.isValid()) {
  2990. if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
  2991. return;
  2992. }
  2993. synchronized (mProxyLock) {
  2994. mGlobalProxy = proxyProperties;
  2995. }
  2996. }
  2997. }
  2998. public ProxyInfo getGlobalProxy() {
  2999. // this information is already available as a world read/writable jvm property
  3000. // so this API change wouldn't have a benifit. It also breaks the passing
  3001. // of proxy info to all the JVMs.
  3002. // enforceAccessPermission();
  3003. synchronized (mProxyLock) {
  3004. return mGlobalProxy;
  3005. }
  3006. }
  3007. private void handleApplyDefaultProxy(ProxyInfo proxy) {
  3008. if (proxy != null && TextUtils.isEmpty(proxy.getHost())
  3009. && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
  3010. proxy = null;
  3011. }
  3012. synchronized (mProxyLock) {
  3013. if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
  3014. if (mDefaultProxy == proxy) return; // catches repeated nulls
  3015. if (proxy != null && !proxy.isValid()) {
  3016. if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
  3017. return;
  3018. }
  3019. // This call could be coming from the PacManager, containing the port of the local
  3020. // proxy. If this new proxy matches the global proxy then copy this proxy to the
  3021. // global (to get the correct local port), and send a broadcast.
  3022. // TODO: Switch PacManager to have its own message to send back rather than
  3023. // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
  3024. if ((mGlobalProxy != null) && (proxy != null)
  3025. && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
  3026. && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
  3027. mGlobalProxy = proxy;
  3028. sendProxyBroadcast(mGlobalProxy);
  3029. return;
  3030. }
  3031. mDefaultProxy = proxy;
  3032. if (mGlobalProxy != null) return;
  3033. if (!mDefaultProxyDisabled) {
  3034. sendProxyBroadcast(proxy);
  3035. }
  3036. }
  3037. }
  3038. // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
  3039. // This method gets called when any network changes proxy, but the broadcast only ever contains
  3040. // the default proxy (even if it hasn't changed).
  3041. // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
  3042. // world where an app might be bound to a non-default network.
  3043. private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
  3044. ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
  3045. ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
  3046. if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
  3047. sendProxyBroadcast(getDefaultProxy());
  3048. }
  3049. }
  3050. private void handleDeprecatedGlobalHttpProxy() {
  3051. String proxy = Settings.Global.getString(mContext.getContentResolver(),
  3052. Settings.Global.HTTP_PROXY);
  3053. if (!TextUtils.isEmpty(proxy)) {
  3054. String data[] = proxy.split(":");
  3055. if (data.length == 0) {
  3056. return;
  3057. }
  3058. String proxyHost = data[0];
  3059. int proxyPort = 8080;
  3060. if (data.length > 1) {
  3061. try {
  3062. proxyPort = Integer.parseInt(data[1]);
  3063. } catch (NumberFormatException e) {
  3064. return;
  3065. }
  3066. }
  3067. ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
  3068. setGlobalProxy(p);
  3069. }
  3070. }
  3071. private void sendProxyBroadcast(ProxyInfo proxy) {
  3072. if (proxy == null) proxy = new ProxyInfo("", 0, "");
  3073. if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
  3074. if (DBG) log("sending Proxy Broadcast for " + proxy);
  3075. Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
  3076. intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
  3077. Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
  3078. intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
  3079. final long ident = Binder.clearCallingIdentity();
  3080. try {
  3081. mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
  3082. } finally {
  3083. Binder.restoreCallingIdentity(ident);
  3084. }
  3085. }
  3086. private static class SettingsObserver extends ContentObserver {
  3087. final private HashMap<Uri, Integer> mUriEventMap;
  3088. final private Context mContext;
  3089. final private Handler mHandler;
  3090. SettingsObserver(Context context, Handler handler) {
  3091. super(null);
  3092. mUriEventMap = new HashMap<Uri, Integer>();
  3093. mContext = context;
  3094. mHandler = handler;
  3095. }
  3096. void observe(Uri uri, int what) {
  3097. mUriEventMap.put(uri, what);
  3098. final ContentResolver resolver = mContext.getContentResolver();
  3099. resolver.registerContentObserver(uri, false, this);
  3100. }
  3101. @Override
  3102. public void onChange(boolean selfChange) {
  3103. Slog.wtf(TAG, "Should never be reached.");
  3104. }
  3105. @Override
  3106. public void onChange(boolean selfChange, Uri uri) {
  3107. final Integer what = mUriEventMap.get(uri);
  3108. if (what != null) {
  3109. mHandler.obtainMessage(what.intValue()).sendToTarget();
  3110. } else {
  3111. loge("No matching event to send for URI=" + uri);
  3112. }
  3113. }
  3114. }
  3115. private static void log(String s) {
  3116. Slog.d(TAG, s);
  3117. }
  3118. private static void loge(String s) {
  3119. Slog.e(TAG, s);
  3120. }
  3121. private static void loge(String s, Throwable t) {
  3122. Slog.e(TAG, s, t);
  3123. }
  3124. /**
  3125. * Prepare for a VPN application.
  3126. * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
  3127. * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
  3128. *
  3129. * @param oldPackage Package name of the application which currently controls VPN, which will
  3130. * be replaced. If there is no such application, this should should either be
  3131. * {@code null} or {@link VpnConfig.LEGACY_VPN}.
  3132. * @param newPackage Package name of the application which should gain control of VPN, or
  3133. * {@code null} to disable.
  3134. * @param userId User for whom to prepare the new VPN.
  3135. *
  3136. * @hide
  3137. */
  3138. @Override
  3139. public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
  3140. int userId) {
  3141. enforceCrossUserPermission(userId);
  3142. synchronized (mVpns) {
  3143. throwIfLockdownEnabled();
  3144. Vpn vpn = mVpns.get(userId);
  3145. if (vpn != null) {
  3146. return vpn.prepare(oldPackage, newPackage);
  3147. } else {
  3148. return false;
  3149. }
  3150. }
  3151. }
  3152. /**
  3153. * Set whether the VPN package has the ability to launch VPNs without user intervention.
  3154. * This method is used by system-privileged apps.
  3155. * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
  3156. * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
  3157. *
  3158. * @param packageName The package for which authorization state should change.
  3159. * @param userId User for whom {@code packageName} is installed.
  3160. * @param authorized {@code true} if this app should be able to start a VPN connection without
  3161. * explicit user approval, {@code false} if not.
  3162. *
  3163. * @hide
  3164. */
  3165. @Override
  3166. public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
  3167. enforceCrossUserPermission(userId);
  3168. synchronized (mVpns) {
  3169. Vpn vpn = mVpns.get(userId);
  3170. if (vpn != null) {
  3171. vpn.setPackageAuthorization(packageName, authorized);
  3172. }
  3173. }
  3174. }
  3175. /**
  3176. * Configure a TUN interface and return its file descriptor. Parameters
  3177. * are encoded and opaque to this class. This method is used by VpnBuilder
  3178. * and not available in ConnectivityManager. Permissions are checked in
  3179. * Vpn class.
  3180. * @hide
  3181. */
  3182. @Override
  3183. public ParcelFileDescriptor establishVpn(VpnConfig config) {
  3184. int user = UserHandle.getUserId(Binder.getCallingUid());
  3185. synchronized (mVpns) {
  3186. throwIfLockdownEnabled();
  3187. return mVpns.get(user).establish(config);
  3188. }
  3189. }
  3190. /**
  3191. * Start legacy VPN, controlling native daemons as needed. Creates a
  3192. * secondary thread to perform connection work, returning quickly.
  3193. */
  3194. @Override
  3195. public void startLegacyVpn(VpnProfile profile) {
  3196. int user = UserHandle.getUserId(Binder.getCallingUid());
  3197. final LinkProperties egress = getActiveLinkProperties();
  3198. if (egress == null) {
  3199. throw new IllegalStateException("Missing active network connection");
  3200. }
  3201. synchronized (mVpns) {
  3202. throwIfLockdownEnabled();
  3203. mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
  3204. }
  3205. }
  3206. /**
  3207. * Return the information of the ongoing legacy VPN. This method is used
  3208. * by VpnSettings and not available in ConnectivityManager. Permissions
  3209. * are checked in Vpn class.
  3210. */
  3211. @Override
  3212. public LegacyVpnInfo getLegacyVpnInfo(int userId) {
  3213. enforceCrossUserPermission(userId);
  3214. synchronized (mVpns) {
  3215. return mVpns.get(userId).getLegacyVpnInfo();
  3216. }
  3217. }
  3218. /**
  3219. * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
  3220. * and not available in ConnectivityManager.
  3221. */
  3222. @Override
  3223. public VpnInfo[] getAllVpnInfo() {
  3224. enforceConnectivityInternalPermission();
  3225. synchronized (mVpns) {
  3226. if (mLockdownEnabled) {
  3227. return new VpnInfo[0];
  3228. }
  3229. List<VpnInfo> infoList = new ArrayList<>();
  3230. for (int i = 0; i < mVpns.size(); i++) {
  3231. VpnInfo info = createVpnInfo(mVpns.valueAt(i));
  3232. if (info != null) {
  3233. infoList.add(info);
  3234. }
  3235. }
  3236. return infoList.toArray(new VpnInfo[infoList.size()]);
  3237. }
  3238. }
  3239. /**
  3240. * @return VPN information for accounting, or null if we can't retrieve all required
  3241. * information, e.g primary underlying iface.
  3242. */
  3243. @Nullable
  3244. private VpnInfo createVpnInfo(Vpn vpn) {
  3245. VpnInfo info = vpn.getVpnInfo();
  3246. if (info == null) {
  3247. return null;
  3248. }
  3249. Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
  3250. // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
  3251. // the underlyingNetworks list.
  3252. if (underlyingNetworks == null) {
  3253. NetworkAgentInfo defaultNetwork = getDefaultNetwork();
  3254. if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
  3255. info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
  3256. }
  3257. } else if (underlyingNetworks.length > 0) {
  3258. LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
  3259. if (linkProperties != null) {
  3260. info.primaryUnderlyingIface = linkProperties.getInterfaceName();
  3261. }
  3262. }
  3263. return info.primaryUnderlyingIface == null ? null : info;
  3264. }
  3265. /**
  3266. * Returns the information of the ongoing VPN for {@code userId}. This method is used by
  3267. * VpnDialogs and not available in ConnectivityManager.
  3268. * Permissions are checked in Vpn class.
  3269. * @hide
  3270. */
  3271. @Override
  3272. public VpnConfig getVpnConfig(int userId) {
  3273. enforceCrossUserPermission(userId);
  3274. synchronized (mVpns) {
  3275. Vpn vpn = mVpns.get(userId);
  3276. if (vpn != null) {
  3277. return vpn.getVpnConfig();
  3278. } else {
  3279. return null;
  3280. }
  3281. }
  3282. }
  3283. @Override
  3284. public boolean updateLockdownVpn() {
  3285. if (Binder.getCallingUid() != Process.SYSTEM_UID) {
  3286. Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
  3287. return false;
  3288. }
  3289. synchronized (mVpns) {
  3290. // Tear down existing lockdown if profile was removed
  3291. mLockdownEnabled = LockdownVpnTracker.isEnabled();
  3292. if (mLockdownEnabled) {
  3293. byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
  3294. if (profileTag == null) {
  3295. Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
  3296. return false;
  3297. }
  3298. String profileName = new String(profileTag);
  3299. final VpnProfile profile = VpnProfile.decode(
  3300. profileName, mKeyStore.get(Credentials.VPN + profileName));
  3301. if (profile == null) {
  3302. Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
  3303. setLockdownTracker(null);
  3304. return true;
  3305. }
  3306. int user = UserHandle.getUserId(Binder.getCallingUid());
  3307. Vpn vpn = mVpns.get(user);
  3308. if (vpn == null) {
  3309. Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
  3310. return false;
  3311. }
  3312. setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
  3313. } else {
  3314. setLockdownTracker(null);
  3315. }
  3316. }
  3317. return true;
  3318. }
  3319. /**
  3320. * Internally set new {@link LockdownVpnTracker}, shutting down any existing
  3321. * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
  3322. */
  3323. @GuardedBy("mVpns")
  3324. private void setLockdownTracker(LockdownVpnTracker tracker) {
  3325. // Shutdown any existing tracker
  3326. final LockdownVpnTracker existing = mLockdownTracker;
  3327. mLockdownTracker = null;
  3328. if (existing != null) {
  3329. existing.shutdown();
  3330. }
  3331. if (tracker != null) {
  3332. mLockdownTracker = tracker;
  3333. mLockdownTracker.init();
  3334. }
  3335. }
  3336. @GuardedBy("mVpns")
  3337. private void throwIfLockdownEnabled() {
  3338. if (mLockdownEnabled) {
  3339. throw new IllegalStateException("Unavailable in lockdown mode");
  3340. }
  3341. }
  3342. /**
  3343. * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
  3344. * some setup and then call {@code establish()} to connect.
  3345. *
  3346. * @return {@code true} if the service was started, the service was already connected, or there
  3347. * was no always-on VPN to start. {@code false} otherwise.
  3348. */
  3349. private boolean startAlwaysOnVpn(int userId) {
  3350. synchronized (mVpns) {
  3351. Vpn vpn = mVpns.get(userId);
  3352. if (vpn == null) {
  3353. // Shouldn't happen as all codepaths that point here should have checked the Vpn
  3354. // exists already.
  3355. Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
  3356. return false;
  3357. }
  3358. return vpn.startAlwaysOnVpn();
  3359. }
  3360. }
  3361. @Override
  3362. public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
  3363. enforceSettingsPermission();
  3364. enforceCrossUserPermission(userId);
  3365. synchronized (mVpns) {
  3366. Vpn vpn = mVpns.get(userId);
  3367. if (vpn == null) {
  3368. Slog.w(TAG, "User " + userId + " has no Vpn configuration");
  3369. return false;
  3370. }
  3371. return vpn.isAlwaysOnPackageSupported(packageName);
  3372. }
  3373. }
  3374. @Override
  3375. public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
  3376. enforceConnectivityInternalPermission();
  3377. enforceCrossUserPermission(userId);
  3378. synchronized (mVpns) {
  3379. // Can't set always-on VPN if legacy VPN is already in lockdown mode.
  3380. if (LockdownVpnTracker.isEnabled()) {
  3381. return false;
  3382. }
  3383. Vpn vpn = mVpns.get(userId);
  3384. if (vpn == null) {
  3385. Slog.w(TAG, "User " + userId + " has no Vpn configuration");
  3386. return false;
  3387. }
  3388. if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
  3389. return false;
  3390. }
  3391. if (!startAlwaysOnVpn(userId)) {
  3392. vpn.setAlwaysOnPackage(null, false);
  3393. return false;
  3394. }
  3395. }
  3396. return true;
  3397. }
  3398. @Override
  3399. public String getAlwaysOnVpnPackage(int userId) {
  3400. enforceConnectivityInternalPermission();
  3401. enforceCrossUserPermission(userId);
  3402. synchronized (mVpns) {
  3403. Vpn vpn = mVpns.get(userId);
  3404. if (vpn == null) {
  3405. Slog.w(TAG, "User " + userId + " has no Vpn configuration");
  3406. return null;
  3407. }
  3408. return vpn.getAlwaysOnPackage();
  3409. }
  3410. }
  3411. @Override
  3412. public int checkMobileProvisioning(int suggestedTimeOutMs) {
  3413. // TODO: Remove? Any reason to trigger a provisioning check?
  3414. return -1;
  3415. }
  3416. /** Location to an updatable file listing carrier provisioning urls.
  3417. * An example:
  3418. *
  3419. * <?xml version="1.0" encoding="utf-8"?>
  3420. * <provisioningUrls>
  3421. * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
  3422. * </provisioningUrls>
  3423. */
  3424. private static final String PROVISIONING_URL_PATH =
  3425. "/data/misc/radio/provisioning_urls.xml";
  3426. private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
  3427. /** XML tag for root element. */
  3428. private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
  3429. /** XML tag for individual url */
  3430. private static final String TAG_PROVISIONING_URL = "provisioningUrl";
  3431. /** XML attribute for mcc */
  3432. private static final String ATTR_MCC = "mcc";
  3433. /** XML attribute for mnc */
  3434. private static final String ATTR_MNC = "mnc";
  3435. private String getProvisioningUrlBaseFromFile() {
  3436. FileReader fileReader = null;
  3437. XmlPullParser parser = null;
  3438. Configuration config = mContext.getResources().getConfiguration();
  3439. try {
  3440. fileReader = new FileReader(mProvisioningUrlFile);
  3441. parser = Xml.newPullParser();
  3442. parser.setInput(fileReader);
  3443. XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
  3444. while (true) {
  3445. XmlUtils.nextElement(parser);
  3446. String element = parser.getName();
  3447. if (element == null) break;
  3448. if (element.equals(TAG_PROVISIONING_URL)) {
  3449. String mcc = parser.getAttributeValue(null, ATTR_MCC);
  3450. try {
  3451. if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
  3452. String mnc = parser.getAttributeValue(null, ATTR_MNC);
  3453. if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
  3454. parser.next();
  3455. if (parser.getEventType() == XmlPullParser.TEXT) {
  3456. return parser.getText();
  3457. }
  3458. }
  3459. }
  3460. } catch (NumberFormatException e) {
  3461. loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
  3462. }
  3463. }
  3464. }
  3465. return null;
  3466. } catch (FileNotFoundException e) {
  3467. loge("Carrier Provisioning Urls file not found");
  3468. } catch (XmlPullParserException e) {
  3469. loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
  3470. } catch (IOException e) {
  3471. loge("I/O exception reading Carrier Provisioning Urls file: " + e);
  3472. } finally {
  3473. if (fileReader != null) {
  3474. try {
  3475. fileReader.close();
  3476. } catch (IOException e) {}
  3477. }
  3478. }
  3479. return null;
  3480. }
  3481. @Override
  3482. public String getMobileProvisioningUrl() {
  3483. enforceConnectivityInternalPermission();
  3484. String url = getProvisioningUrlBaseFromFile();
  3485. if (TextUtils.isEmpty(url)) {
  3486. url = mContext.getResources().getString(R.string.mobile_provisioning_url);
  3487. log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
  3488. } else {
  3489. log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
  3490. }
  3491. // populate the iccid, imei and phone number in the provisioning url.
  3492. if (!TextUtils.isEmpty(url)) {
  3493. String phoneNumber = mTelephonyManager.getLine1Number();
  3494. if (TextUtils.isEmpty(phoneNumber)) {
  3495. phoneNumber = "0000000000";
  3496. }
  3497. url = String.format(url,
  3498. mTelephonyManager.getSimSerialNumber() /* ICCID */,
  3499. mTelephonyManager.getDeviceId() /* IMEI */,
  3500. phoneNumber /* Phone numer */);
  3501. }
  3502. return url;
  3503. }
  3504. @Override
  3505. public void setProvisioningNotificationVisible(boolean visible, int networkType,
  3506. String action) {
  3507. enforceConnectivityInternalPermission();
  3508. if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
  3509. return;
  3510. }
  3511. final long ident = Binder.clearCallingIdentity();
  3512. try {
  3513. // Concatenate the range of types onto the range of NetIDs.
  3514. int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
  3515. mNotifier.setProvNotificationVisible(visible, id, action);
  3516. } finally {
  3517. Binder.restoreCallingIdentity(ident);
  3518. }
  3519. }
  3520. @Override
  3521. public void setAirplaneMode(boolean enable) {
  3522. enforceConnectivityInternalPermission();
  3523. final long ident = Binder.clearCallingIdentity();
  3524. try {
  3525. final ContentResolver cr = mContext.getContentResolver();
  3526. Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
  3527. Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
  3528. intent.putExtra("state", enable);
  3529. mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
  3530. } finally {
  3531. Binder.restoreCallingIdentity(ident);
  3532. }
  3533. }
  3534. private void onUserStart(int userId) {
  3535. synchronized (mVpns) {
  3536. Vpn userVpn = mVpns.get(userId);
  3537. if (userVpn != null) {
  3538. loge("Starting user already has a VPN");
  3539. return;
  3540. }
  3541. userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
  3542. mVpns.put(userId, userVpn);
  3543. if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
  3544. updateLockdownVpn();
  3545. }
  3546. }
  3547. }
  3548. private void onUserStop(int userId) {
  3549. synchronized (mVpns) {
  3550. Vpn userVpn = mVpns.get(userId);
  3551. if (userVpn == null) {
  3552. loge("Stopped user has no VPN");
  3553. return;
  3554. }
  3555. userVpn.onUserStopped();
  3556. mVpns.delete(userId);
  3557. }
  3558. }
  3559. private void onUserAdded(int userId) {
  3560. synchronized (mVpns) {
  3561. final int vpnsSize = mVpns.size();
  3562. for (int i = 0; i < vpnsSize; i++) {
  3563. Vpn vpn = mVpns.valueAt(i);
  3564. vpn.onUserAdded(userId);
  3565. }
  3566. }
  3567. }
  3568. private void onUserRemoved(int userId) {
  3569. synchronized (mVpns) {
  3570. final int vpnsSize = mVpns.size();
  3571. for (int i = 0; i < vpnsSize; i++) {
  3572. Vpn vpn = mVpns.valueAt(i);
  3573. vpn.onUserRemoved(userId);
  3574. }
  3575. }
  3576. }
  3577. private void onUserUnlocked(int userId) {
  3578. synchronized (mVpns) {
  3579. // User present may be sent because of an unlock, which might mean an unlocked keystore.
  3580. if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
  3581. updateLockdownVpn();
  3582. } else {
  3583. startAlwaysOnVpn(userId);
  3584. }
  3585. }
  3586. }
  3587. private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
  3588. @Override
  3589. public void onReceive(Context context, Intent intent) {
  3590. final String action = intent.getAction();
  3591. final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
  3592. if (userId == UserHandle.USER_NULL) return;
  3593. if (Intent.ACTION_USER_STARTED.equals(action)) {
  3594. onUserStart(userId);
  3595. } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
  3596. onUserStop(userId);
  3597. } else if (Intent.ACTION_USER_ADDED.equals(action)) {
  3598. onUserAdded(userId);
  3599. } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
  3600. onUserRemoved(userId);
  3601. } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
  3602. onUserUnlocked(userId);
  3603. }
  3604. }
  3605. };
  3606. private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
  3607. @Override
  3608. public void onReceive(Context context, Intent intent) {
  3609. // Try creating lockdown tracker, since user present usually means
  3610. // unlocked keystore.
  3611. updateLockdownVpn();
  3612. mContext.unregisterReceiver(this);
  3613. }
  3614. };
  3615. private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
  3616. new HashMap<Messenger, NetworkFactoryInfo>();
  3617. private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
  3618. new HashMap<NetworkRequest, NetworkRequestInfo>();
  3619. private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
  3620. // Map from UID to number of NetworkRequests that UID has filed.
  3621. @GuardedBy("mUidToNetworkRequestCount")
  3622. private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
  3623. private static class NetworkFactoryInfo {
  3624. public final String name;
  3625. public final Messenger messenger;
  3626. public final AsyncChannel asyncChannel;
  3627. public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
  3628. this.name = name;
  3629. this.messenger = messenger;
  3630. this.asyncChannel = asyncChannel;
  3631. }
  3632. }
  3633. private void ensureNetworkRequestHasType(NetworkRequest request) {
  3634. if (request.type == NetworkRequest.Type.NONE) {
  3635. throw new IllegalArgumentException(
  3636. "All NetworkRequests in ConnectivityService must have a type");
  3637. }
  3638. }
  3639. /**
  3640. * Tracks info about the requester.
  3641. * Also used to notice when the calling process dies so we can self-expire
  3642. */
  3643. private class NetworkRequestInfo implements IBinder.DeathRecipient {
  3644. final NetworkRequest request;
  3645. final PendingIntent mPendingIntent;
  3646. boolean mPendingIntentSent;
  3647. private final IBinder mBinder;
  3648. final int mPid;
  3649. final int mUid;
  3650. final Messenger messenger;
  3651. NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
  3652. request = r;
  3653. ensureNetworkRequestHasType(request);
  3654. mPendingIntent = pi;
  3655. messenger = null;
  3656. mBinder = null;
  3657. mPid = getCallingPid();
  3658. mUid = getCallingUid();
  3659. enforceRequestCountLimit();
  3660. }
  3661. NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
  3662. super();
  3663. messenger = m;
  3664. request = r;
  3665. ensureNetworkRequestHasType(request);
  3666. mBinder = binder;
  3667. mPid = getCallingPid();
  3668. mUid = getCallingUid();
  3669. mPendingIntent = null;
  3670. enforceRequestCountLimit();
  3671. try {
  3672. mBinder.linkToDeath(this, 0);
  3673. } catch (RemoteException e) {
  3674. binderDied();
  3675. }
  3676. }
  3677. private void enforceRequestCountLimit() {
  3678. synchronized (mUidToNetworkRequestCount) {
  3679. int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
  3680. if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
  3681. throw new ServiceSpecificException(
  3682. ConnectivityManager.Errors.TOO_MANY_REQUESTS);
  3683. }
  3684. mUidToNetworkRequestCount.put(mUid, networkRequests);
  3685. }
  3686. }
  3687. void unlinkDeathRecipient() {
  3688. if (mBinder != null) {
  3689. mBinder.unlinkToDeath(this, 0);
  3690. }
  3691. }
  3692. public void binderDied() {
  3693. log("ConnectivityService NetworkRequestInfo binderDied(" +
  3694. request + ", " + mBinder + ")");
  3695. releaseNetworkRequest(request);
  3696. }
  3697. public String toString() {
  3698. return "uid/pid:" + mUid + "/" + mPid + " " + request +
  3699. (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
  3700. }
  3701. }
  3702. private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
  3703. final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
  3704. if (badCapability != null) {
  3705. throw new IllegalArgumentException("Cannot request network with " + badCapability);
  3706. }
  3707. }
  3708. private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
  3709. final SortedSet<Integer> thresholds = new TreeSet();
  3710. synchronized (nai) {
  3711. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  3712. if (nri.request.networkCapabilities.hasSignalStrength() &&
  3713. nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
  3714. thresholds.add(nri.request.networkCapabilities.getSignalStrength());
  3715. }
  3716. }
  3717. }
  3718. return new ArrayList<Integer>(thresholds);
  3719. }
  3720. private void updateSignalStrengthThresholds(
  3721. NetworkAgentInfo nai, String reason, NetworkRequest request) {
  3722. ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
  3723. Bundle thresholds = new Bundle();
  3724. thresholds.putIntegerArrayList("thresholds", thresholdsArray);
  3725. if (VDBG || (DBG && !"CONNECT".equals(reason))) {
  3726. String detail;
  3727. if (request != null && request.networkCapabilities.hasSignalStrength()) {
  3728. detail = reason + " " + request.networkCapabilities.getSignalStrength();
  3729. } else {
  3730. detail = reason;
  3731. }
  3732. log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
  3733. detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
  3734. }
  3735. nai.asyncChannel.sendMessage(
  3736. android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
  3737. 0, 0, thresholds);
  3738. }
  3739. private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
  3740. if (nc == null) {
  3741. return;
  3742. }
  3743. NetworkSpecifier ns = nc.getNetworkSpecifier();
  3744. if (ns == null) {
  3745. return;
  3746. }
  3747. MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
  3748. ns.assertValidFromUid(Binder.getCallingUid());
  3749. }
  3750. @Override
  3751. public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
  3752. Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
  3753. final NetworkRequest.Type type = (networkCapabilities == null)
  3754. ? NetworkRequest.Type.TRACK_DEFAULT
  3755. : NetworkRequest.Type.REQUEST;
  3756. // If the requested networkCapabilities is null, take them instead from
  3757. // the default network request. This allows callers to keep track of
  3758. // the system default network.
  3759. if (type == NetworkRequest.Type.TRACK_DEFAULT) {
  3760. networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
  3761. networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
  3762. enforceAccessPermission();
  3763. } else {
  3764. networkCapabilities = new NetworkCapabilities(networkCapabilities);
  3765. enforceNetworkRequestPermissions(networkCapabilities);
  3766. // TODO: this is incorrect. We mark the request as metered or not depending on the state
  3767. // of the app when the request is filed, but we never change the request if the app
  3768. // changes network state. http://b/29964605
  3769. enforceMeteredApnPolicy(networkCapabilities);
  3770. }
  3771. ensureRequestableCapabilities(networkCapabilities);
  3772. // Set the UID range for this request to the single UID of the requester.
  3773. // This will overwrite any allowed UIDs in the requested capabilities. Though there
  3774. // are no visible methods to set the UIDs, an app could use reflection to try and get
  3775. // networks for other apps so it's essential that the UIDs are overwritten.
  3776. // TODO : don't forcefully set the UID when communicating with processes
  3777. // that have the NETWORK_SETTINGS permission.
  3778. networkCapabilities.setSingleUid(Binder.getCallingUid());
  3779. if (timeoutMs < 0) {
  3780. throw new IllegalArgumentException("Bad timeout specified");
  3781. }
  3782. ensureValidNetworkSpecifier(networkCapabilities);
  3783. NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
  3784. nextNetworkRequestId(), type);
  3785. NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
  3786. if (DBG) log("requestNetwork for " + nri);
  3787. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
  3788. if (timeoutMs > 0) {
  3789. mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
  3790. nri), timeoutMs);
  3791. }
  3792. return networkRequest;
  3793. }
  3794. private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
  3795. if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
  3796. enforceConnectivityRestrictedNetworksPermission();
  3797. } else {
  3798. enforceChangePermission();
  3799. }
  3800. }
  3801. @Override
  3802. public boolean requestBandwidthUpdate(Network network) {
  3803. enforceAccessPermission();
  3804. NetworkAgentInfo nai = null;
  3805. if (network == null) {
  3806. return false;
  3807. }
  3808. synchronized (mNetworkForNetId) {
  3809. nai = mNetworkForNetId.get(network.netId);
  3810. }
  3811. if (nai != null) {
  3812. nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
  3813. return true;
  3814. }
  3815. return false;
  3816. }
  3817. private boolean isSystem(int uid) {
  3818. return uid < Process.FIRST_APPLICATION_UID;
  3819. }
  3820. private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
  3821. final int uid = Binder.getCallingUid();
  3822. if (isSystem(uid)) {
  3823. // Exemption for system uid.
  3824. return;
  3825. }
  3826. if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
  3827. // Policy already enforced.
  3828. return;
  3829. }
  3830. if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
  3831. // If UID is restricted, don't allow them to bring up metered APNs.
  3832. networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
  3833. }
  3834. }
  3835. @Override
  3836. public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
  3837. PendingIntent operation) {
  3838. checkNotNull(operation, "PendingIntent cannot be null.");
  3839. networkCapabilities = new NetworkCapabilities(networkCapabilities);
  3840. enforceNetworkRequestPermissions(networkCapabilities);
  3841. enforceMeteredApnPolicy(networkCapabilities);
  3842. ensureRequestableCapabilities(networkCapabilities);
  3843. ensureValidNetworkSpecifier(networkCapabilities);
  3844. // TODO : don't forcefully set the UID when communicating with processes
  3845. // that have the NETWORK_SETTINGS permission.
  3846. networkCapabilities.setSingleUid(Binder.getCallingUid());
  3847. NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
  3848. nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
  3849. NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
  3850. if (DBG) log("pendingRequest for " + nri);
  3851. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
  3852. nri));
  3853. return networkRequest;
  3854. }
  3855. private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
  3856. mHandler.sendMessageDelayed(
  3857. mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
  3858. getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
  3859. }
  3860. @Override
  3861. public void releasePendingNetworkRequest(PendingIntent operation) {
  3862. checkNotNull(operation, "PendingIntent cannot be null.");
  3863. mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
  3864. getCallingUid(), 0, operation));
  3865. }
  3866. // In order to implement the compatibility measure for pre-M apps that call
  3867. // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
  3868. // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
  3869. // This ensures it has permission to do so.
  3870. private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
  3871. if (nc == null) {
  3872. return false;
  3873. }
  3874. int[] transportTypes = nc.getTransportTypes();
  3875. if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
  3876. return false;
  3877. }
  3878. try {
  3879. mContext.enforceCallingOrSelfPermission(
  3880. android.Manifest.permission.ACCESS_WIFI_STATE,
  3881. "ConnectivityService");
  3882. } catch (SecurityException e) {
  3883. return false;
  3884. }
  3885. return true;
  3886. }
  3887. @Override
  3888. public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
  3889. Messenger messenger, IBinder binder) {
  3890. if (!hasWifiNetworkListenPermission(networkCapabilities)) {
  3891. enforceAccessPermission();
  3892. }
  3893. NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
  3894. // TODO : don't forcefully set the UIDs when communicating with processes
  3895. // that have the NETWORK_SETTINGS permission.
  3896. nc.setSingleUid(Binder.getCallingUid());
  3897. if (!ConnectivityManager.checkChangePermission(mContext)) {
  3898. // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
  3899. // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
  3900. // onLost and onAvailable callbacks when networks move in and out of the background.
  3901. // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
  3902. // can't request networks.
  3903. nc.addCapability(NET_CAPABILITY_FOREGROUND);
  3904. }
  3905. ensureValidNetworkSpecifier(networkCapabilities);
  3906. NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
  3907. NetworkRequest.Type.LISTEN);
  3908. NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
  3909. if (VDBG) log("listenForNetwork for " + nri);
  3910. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
  3911. return networkRequest;
  3912. }
  3913. @Override
  3914. public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
  3915. PendingIntent operation) {
  3916. checkNotNull(operation, "PendingIntent cannot be null.");
  3917. if (!hasWifiNetworkListenPermission(networkCapabilities)) {
  3918. enforceAccessPermission();
  3919. }
  3920. ensureValidNetworkSpecifier(networkCapabilities);
  3921. final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
  3922. // TODO : don't forcefully set the UIDs when communicating with processes
  3923. // that have the NETWORK_SETTINGS permission.
  3924. nc.setSingleUid(Binder.getCallingUid());
  3925. NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
  3926. NetworkRequest.Type.LISTEN);
  3927. NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
  3928. if (VDBG) log("pendingListenForNetwork for " + nri);
  3929. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
  3930. }
  3931. @Override
  3932. public void releaseNetworkRequest(NetworkRequest networkRequest) {
  3933. ensureNetworkRequestHasType(networkRequest);
  3934. mHandler.sendMessage(mHandler.obtainMessage(
  3935. EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
  3936. }
  3937. @Override
  3938. public void registerNetworkFactory(Messenger messenger, String name) {
  3939. enforceConnectivityInternalPermission();
  3940. NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
  3941. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
  3942. }
  3943. private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
  3944. if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
  3945. mNetworkFactoryInfos.put(nfi.messenger, nfi);
  3946. nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
  3947. }
  3948. @Override
  3949. public void unregisterNetworkFactory(Messenger messenger) {
  3950. enforceConnectivityInternalPermission();
  3951. mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
  3952. }
  3953. private void handleUnregisterNetworkFactory(Messenger messenger) {
  3954. NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
  3955. if (nfi == null) {
  3956. loge("Failed to find Messenger in unregisterNetworkFactory");
  3957. return;
  3958. }
  3959. if (DBG) log("unregisterNetworkFactory for " + nfi.name);
  3960. }
  3961. /**
  3962. * NetworkAgentInfo supporting a request by requestId.
  3963. * These have already been vetted (their Capabilities satisfy the request)
  3964. * and the are the highest scored network available.
  3965. * the are keyed off the Requests requestId.
  3966. */
  3967. // NOTE: Accessed on multiple threads, must be synchronized on itself.
  3968. @GuardedBy("mNetworkForRequestId")
  3969. private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
  3970. new SparseArray<NetworkAgentInfo>();
  3971. // NOTE: Accessed on multiple threads, must be synchronized on itself.
  3972. @GuardedBy("mNetworkForNetId")
  3973. private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
  3974. new SparseArray<NetworkAgentInfo>();
  3975. // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
  3976. // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
  3977. // there may not be a strict 1:1 correlation between the two.
  3978. @GuardedBy("mNetworkForNetId")
  3979. private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
  3980. // NetworkAgentInfo keyed off its connecting messenger
  3981. // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
  3982. // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
  3983. private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
  3984. new HashMap<Messenger, NetworkAgentInfo>();
  3985. @GuardedBy("mBlockedAppUids")
  3986. private final HashSet<Integer> mBlockedAppUids = new HashSet();
  3987. // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
  3988. private final NetworkRequest mDefaultRequest;
  3989. // Request used to optionally keep mobile data active even when higher
  3990. // priority networks like Wi-Fi are active.
  3991. private final NetworkRequest mDefaultMobileDataRequest;
  3992. private NetworkAgentInfo getNetworkForRequest(int requestId) {
  3993. synchronized (mNetworkForRequestId) {
  3994. return mNetworkForRequestId.get(requestId);
  3995. }
  3996. }
  3997. private void clearNetworkForRequest(int requestId) {
  3998. synchronized (mNetworkForRequestId) {
  3999. mNetworkForRequestId.remove(requestId);
  4000. }
  4001. }
  4002. private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
  4003. synchronized (mNetworkForRequestId) {
  4004. mNetworkForRequestId.put(requestId, nai);
  4005. }
  4006. }
  4007. private NetworkAgentInfo getDefaultNetwork() {
  4008. return getNetworkForRequest(mDefaultRequest.requestId);
  4009. }
  4010. private boolean isDefaultNetwork(NetworkAgentInfo nai) {
  4011. return nai == getDefaultNetwork();
  4012. }
  4013. private boolean isDefaultRequest(NetworkRequestInfo nri) {
  4014. return nri.request.requestId == mDefaultRequest.requestId;
  4015. }
  4016. public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
  4017. LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
  4018. int currentScore, NetworkMisc networkMisc) {
  4019. enforceConnectivityInternalPermission();
  4020. LinkProperties lp = new LinkProperties(linkProperties);
  4021. lp.ensureDirectlyConnectedRoutes();
  4022. // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
  4023. // satisfies mDefaultRequest.
  4024. final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
  4025. final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
  4026. new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
  4027. mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
  4028. // Make sure the network capabilities reflect what the agent info says.
  4029. nai.networkCapabilities = mixInCapabilities(nai, nc);
  4030. synchronized (this) {
  4031. nai.networkMonitor.systemReady = mSystemReady;
  4032. }
  4033. addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
  4034. networkInfo.getExtraInfo());
  4035. if (DBG) log("registerNetworkAgent " + nai);
  4036. mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
  4037. return nai.network.netId;
  4038. }
  4039. private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
  4040. if (VDBG) log("Got NetworkAgent Messenger");
  4041. mNetworkAgentInfos.put(na.messenger, na);
  4042. synchronized (mNetworkForNetId) {
  4043. mNetworkForNetId.put(na.network.netId, na);
  4044. }
  4045. na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
  4046. NetworkInfo networkInfo = na.networkInfo;
  4047. na.networkInfo = null;
  4048. updateNetworkInfo(na, networkInfo);
  4049. updateUids(na, null, na.networkCapabilities);
  4050. }
  4051. private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
  4052. LinkProperties newLp = networkAgent.linkProperties;
  4053. int netId = networkAgent.network.netId;
  4054. // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
  4055. // we do anything else, make sure its LinkProperties are accurate.
  4056. if (networkAgent.clatd != null) {
  4057. networkAgent.clatd.fixupLinkProperties(oldLp);
  4058. }
  4059. updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
  4060. updateMtu(newLp, oldLp);
  4061. // TODO - figure out what to do for clat
  4062. // for (LinkProperties lp : newLp.getStackedLinks()) {
  4063. // updateMtu(lp, null);
  4064. // }
  4065. updateTcpBufferSizes(networkAgent);
  4066. updateRoutes(newLp, oldLp, netId);
  4067. updateDnses(newLp, oldLp, netId);
  4068. // Start or stop clat accordingly to network state.
  4069. networkAgent.updateClat(mNetd);
  4070. if (isDefaultNetwork(networkAgent)) {
  4071. handleApplyDefaultProxy(newLp.getHttpProxy());
  4072. } else {
  4073. updateProxy(newLp, oldLp, networkAgent);
  4074. }
  4075. // TODO - move this check to cover the whole function
  4076. if (!Objects.equals(newLp, oldLp)) {
  4077. notifyIfacesChangedForNetworkStats();
  4078. notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
  4079. }
  4080. mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
  4081. }
  4082. private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
  4083. // Marks are only available on WiFi interaces. Checking for
  4084. // marks on unsupported interfaces is harmless.
  4085. if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
  4086. return;
  4087. }
  4088. int mark = mContext.getResources().getInteger(
  4089. com.android.internal.R.integer.config_networkWakeupPacketMark);
  4090. int mask = mContext.getResources().getInteger(
  4091. com.android.internal.R.integer.config_networkWakeupPacketMask);
  4092. // Mask/mark of zero will not detect anything interesting.
  4093. // Don't install rules unless both values are nonzero.
  4094. if (mark == 0 || mask == 0) {
  4095. return;
  4096. }
  4097. final String prefix = "iface:" + iface;
  4098. try {
  4099. if (add) {
  4100. mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
  4101. } else {
  4102. mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
  4103. }
  4104. } catch (Exception e) {
  4105. loge("Exception modifying wakeup packet monitoring: " + e);
  4106. }
  4107. }
  4108. private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
  4109. NetworkCapabilities caps) {
  4110. CompareResult<String> interfaceDiff = new CompareResult<String>(
  4111. oldLp != null ? oldLp.getAllInterfaceNames() : null,
  4112. newLp != null ? newLp.getAllInterfaceNames() : null);
  4113. for (String iface : interfaceDiff.added) {
  4114. try {
  4115. if (DBG) log("Adding iface " + iface + " to network " + netId);
  4116. mNetd.addInterfaceToNetwork(iface, netId);
  4117. wakeupModifyInterface(iface, caps, true);
  4118. } catch (Exception e) {
  4119. loge("Exception adding interface: " + e);
  4120. }
  4121. }
  4122. for (String iface : interfaceDiff.removed) {
  4123. try {
  4124. if (DBG) log("Removing iface " + iface + " from network " + netId);
  4125. wakeupModifyInterface(iface, caps, false);
  4126. mNetd.removeInterfaceFromNetwork(iface, netId);
  4127. } catch (Exception e) {
  4128. loge("Exception removing interface: " + e);
  4129. }
  4130. }
  4131. }
  4132. /**
  4133. * Have netd update routes from oldLp to newLp.
  4134. * @return true if routes changed between oldLp and newLp
  4135. */
  4136. private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
  4137. // Compare the route diff to determine which routes should be added and removed.
  4138. CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
  4139. oldLp != null ? oldLp.getAllRoutes() : null,
  4140. newLp != null ? newLp.getAllRoutes() : null);
  4141. // add routes before removing old in case it helps with continuous connectivity
  4142. // do this twice, adding non-nexthop routes first, then routes they are dependent on
  4143. for (RouteInfo route : routeDiff.added) {
  4144. if (route.hasGateway()) continue;
  4145. if (VDBG) log("Adding Route [" + route + "] to network " + netId);
  4146. try {
  4147. mNetd.addRoute(netId, route);
  4148. } catch (Exception e) {
  4149. if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
  4150. loge("Exception in addRoute for non-gateway: " + e);
  4151. }
  4152. }
  4153. }
  4154. for (RouteInfo route : routeDiff.added) {
  4155. if (route.hasGateway() == false) continue;
  4156. if (VDBG) log("Adding Route [" + route + "] to network " + netId);
  4157. try {
  4158. mNetd.addRoute(netId, route);
  4159. } catch (Exception e) {
  4160. if ((route.getGateway() instanceof Inet4Address) || VDBG) {
  4161. loge("Exception in addRoute for gateway: " + e);
  4162. }
  4163. }
  4164. }
  4165. for (RouteInfo route : routeDiff.removed) {
  4166. if (VDBG) log("Removing Route [" + route + "] from network " + netId);
  4167. try {
  4168. mNetd.removeRoute(netId, route);
  4169. } catch (Exception e) {
  4170. loge("Exception in removeRoute: " + e);
  4171. }
  4172. }
  4173. return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
  4174. }
  4175. private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
  4176. if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
  4177. return; // no updating necessary
  4178. }
  4179. final NetworkAgentInfo defaultNai = getDefaultNetwork();
  4180. final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
  4181. if (DBG) {
  4182. final Collection<InetAddress> dnses = newLp.getDnsServers();
  4183. log("Setting DNS servers for network " + netId + " to " + dnses);
  4184. }
  4185. try {
  4186. mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
  4187. } catch (Exception e) {
  4188. loge("Exception in setDnsConfigurationForNetwork: " + e);
  4189. }
  4190. }
  4191. private String getNetworkPermission(NetworkCapabilities nc) {
  4192. // TODO: make these permission strings AIDL constants instead.
  4193. if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
  4194. return NetworkManagementService.PERMISSION_SYSTEM;
  4195. }
  4196. if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
  4197. return NetworkManagementService.PERMISSION_NETWORK;
  4198. }
  4199. return null;
  4200. }
  4201. /**
  4202. * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
  4203. * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
  4204. * and foreground status).
  4205. */
  4206. private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
  4207. // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
  4208. if (nai.everConnected &&
  4209. !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
  4210. // TODO: consider not complaining when a network agent degrades its capabilities if this
  4211. // does not cause any request (that is not a listen) currently matching that agent to
  4212. // stop being matched by the updated agent.
  4213. String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
  4214. if (!TextUtils.isEmpty(diff)) {
  4215. Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
  4216. }
  4217. }
  4218. // Don't modify caller's NetworkCapabilities.
  4219. NetworkCapabilities newNc = new NetworkCapabilities(nc);
  4220. if (nai.lastValidated) {
  4221. newNc.addCapability(NET_CAPABILITY_VALIDATED);
  4222. } else {
  4223. newNc.removeCapability(NET_CAPABILITY_VALIDATED);
  4224. }
  4225. if (nai.lastCaptivePortalDetected) {
  4226. newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
  4227. } else {
  4228. newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
  4229. }
  4230. if (nai.isBackgroundNetwork()) {
  4231. newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
  4232. } else {
  4233. newNc.addCapability(NET_CAPABILITY_FOREGROUND);
  4234. }
  4235. if (nai.isSuspended()) {
  4236. newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
  4237. } else {
  4238. newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
  4239. }
  4240. return newNc;
  4241. }
  4242. /**
  4243. * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
  4244. *
  4245. * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
  4246. * capabilities we manage and store in {@code nai}, such as validated status and captive
  4247. * portal status)
  4248. * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
  4249. * potentially triggers rematches.
  4250. * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
  4251. * change.)
  4252. *
  4253. * @param oldScore score of the network before any of the changes that prompted us
  4254. * to call this function.
  4255. * @param nai the network having its capabilities updated.
  4256. * @param nc the new network capabilities.
  4257. */
  4258. private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
  4259. NetworkCapabilities newNc = mixInCapabilities(nai, nc);
  4260. if (Objects.equals(nai.networkCapabilities, newNc)) return;
  4261. final String oldPermission = getNetworkPermission(nai.networkCapabilities);
  4262. final String newPermission = getNetworkPermission(newNc);
  4263. if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
  4264. try {
  4265. mNetd.setNetworkPermission(nai.network.netId, newPermission);
  4266. } catch (RemoteException e) {
  4267. loge("Exception in setNetworkPermission: " + e);
  4268. }
  4269. }
  4270. final NetworkCapabilities prevNc;
  4271. synchronized (nai) {
  4272. prevNc = nai.networkCapabilities;
  4273. nai.networkCapabilities = newNc;
  4274. }
  4275. updateUids(nai, prevNc, newNc);
  4276. if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
  4277. // If the requestable capabilities haven't changed, and the score hasn't changed, then
  4278. // the change we're processing can't affect any requests, it can only affect the listens
  4279. // on this network. We might have been called by rematchNetworkAndRequests when a
  4280. // network changed foreground state.
  4281. processListenRequests(nai, true);
  4282. } else {
  4283. // If the requestable capabilities have changed or the score changed, we can't have been
  4284. // called by rematchNetworkAndRequests, so it's safe to start a rematch.
  4285. rematchAllNetworksAndRequests(nai, oldScore);
  4286. notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
  4287. }
  4288. // Report changes that are interesting for network statistics tracking.
  4289. if (prevNc != null) {
  4290. final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
  4291. newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
  4292. final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
  4293. newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
  4294. if (meteredChanged || roamingChanged) {
  4295. notifyIfacesChangedForNetworkStats();
  4296. }
  4297. }
  4298. if (!newNc.hasTransport(TRANSPORT_VPN)) {
  4299. // Tell VPNs about updated capabilities, since they may need to
  4300. // bubble those changes through.
  4301. synchronized (mVpns) {
  4302. for (int i = 0; i < mVpns.size(); i++) {
  4303. final Vpn vpn = mVpns.valueAt(i);
  4304. vpn.updateCapabilities();
  4305. }
  4306. }
  4307. }
  4308. }
  4309. private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
  4310. NetworkCapabilities newNc) {
  4311. Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
  4312. Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
  4313. if (null == prevRanges) prevRanges = new ArraySet<>();
  4314. if (null == newRanges) newRanges = new ArraySet<>();
  4315. final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
  4316. prevRanges.removeAll(newRanges);
  4317. newRanges.removeAll(prevRangesCopy);
  4318. try {
  4319. if (!newRanges.isEmpty()) {
  4320. final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
  4321. newRanges.toArray(addedRangesArray);
  4322. mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
  4323. }
  4324. if (!prevRanges.isEmpty()) {
  4325. final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
  4326. prevRanges.toArray(removedRangesArray);
  4327. mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
  4328. }
  4329. } catch (Exception e) {
  4330. // Never crash!
  4331. loge("Exception in updateUids: " + e);
  4332. }
  4333. }
  4334. public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
  4335. if (mNetworkForNetId.get(nai.network.netId) != nai) {
  4336. // Ignore updates for disconnected networks
  4337. return;
  4338. }
  4339. // newLp is already a defensive copy.
  4340. newLp.ensureDirectlyConnectedRoutes();
  4341. if (VDBG) {
  4342. log("Update of LinkProperties for " + nai.name() +
  4343. "; created=" + nai.created +
  4344. "; everConnected=" + nai.everConnected);
  4345. }
  4346. LinkProperties oldLp = nai.linkProperties;
  4347. synchronized (nai) {
  4348. nai.linkProperties = newLp;
  4349. }
  4350. if (nai.everConnected) {
  4351. updateLinkProperties(nai, oldLp);
  4352. }
  4353. }
  4354. private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
  4355. for (int i = 0; i < nai.numNetworkRequests(); i++) {
  4356. NetworkRequest nr = nai.requestAt(i);
  4357. // Don't send listening requests to factories. b/17393458
  4358. if (nr.isListen()) continue;
  4359. sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
  4360. }
  4361. }
  4362. private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
  4363. if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
  4364. for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
  4365. nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
  4366. networkRequest);
  4367. }
  4368. }
  4369. private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
  4370. int notificationType) {
  4371. if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
  4372. Intent intent = new Intent();
  4373. intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
  4374. intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
  4375. nri.mPendingIntentSent = true;
  4376. sendIntent(nri.mPendingIntent, intent);
  4377. }
  4378. // else not handled
  4379. }
  4380. private void sendIntent(PendingIntent pendingIntent, Intent intent) {
  4381. mPendingIntentWakeLock.acquire();
  4382. try {
  4383. if (DBG) log("Sending " + pendingIntent);
  4384. pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
  4385. } catch (PendingIntent.CanceledException e) {
  4386. if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
  4387. mPendingIntentWakeLock.release();
  4388. releasePendingNetworkRequest(pendingIntent);
  4389. }
  4390. // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
  4391. }
  4392. @Override
  4393. public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
  4394. String resultData, Bundle resultExtras) {
  4395. if (DBG) log("Finished sending " + pendingIntent);
  4396. mPendingIntentWakeLock.release();
  4397. // Release with a delay so the receiving client has an opportunity to put in its
  4398. // own request.
  4399. releasePendingNetworkRequestWithDelay(pendingIntent);
  4400. }
  4401. private void callCallbackForRequest(NetworkRequestInfo nri,
  4402. NetworkAgentInfo networkAgent, int notificationType, int arg1) {
  4403. if (nri.messenger == null) {
  4404. return; // Default request has no msgr
  4405. }
  4406. Bundle bundle = new Bundle();
  4407. // TODO: check if defensive copies of data is needed.
  4408. putParcelable(bundle, new NetworkRequest(nri.request));
  4409. Message msg = Message.obtain();
  4410. if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
  4411. putParcelable(bundle, networkAgent.network);
  4412. }
  4413. switch (notificationType) {
  4414. case ConnectivityManager.CALLBACK_AVAILABLE: {
  4415. putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
  4416. putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
  4417. break;
  4418. }
  4419. case ConnectivityManager.CALLBACK_LOSING: {
  4420. msg.arg1 = arg1;
  4421. break;
  4422. }
  4423. case ConnectivityManager.CALLBACK_CAP_CHANGED: {
  4424. // networkAgent can't be null as it has been accessed a few lines above.
  4425. final NetworkCapabilities nc =
  4426. networkCapabilitiesWithoutUids(networkAgent.networkCapabilities);
  4427. putParcelable(bundle, nc);
  4428. break;
  4429. }
  4430. case ConnectivityManager.CALLBACK_IP_CHANGED: {
  4431. putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
  4432. break;
  4433. }
  4434. }
  4435. msg.what = notificationType;
  4436. msg.setData(bundle);
  4437. try {
  4438. if (VDBG) {
  4439. String notification = ConnectivityManager.getCallbackName(notificationType);
  4440. log("sending notification " + notification + " for " + nri.request);
  4441. }
  4442. nri.messenger.send(msg);
  4443. } catch (RemoteException e) {
  4444. // may occur naturally in the race of binder death.
  4445. loge("RemoteException caught trying to send a callback msg for " + nri.request);
  4446. }
  4447. }
  4448. private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
  4449. bundle.putParcelable(t.getClass().getSimpleName(), t);
  4450. }
  4451. private void teardownUnneededNetwork(NetworkAgentInfo nai) {
  4452. if (nai.numRequestNetworkRequests() != 0) {
  4453. for (int i = 0; i < nai.numNetworkRequests(); i++) {
  4454. NetworkRequest nr = nai.requestAt(i);
  4455. // Ignore listening requests.
  4456. if (nr.isListen()) continue;
  4457. loge("Dead network still had at least " + nr);
  4458. break;
  4459. }
  4460. }
  4461. nai.asyncChannel.disconnect();
  4462. }
  4463. private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
  4464. if (oldNetwork == null) {
  4465. loge("Unknown NetworkAgentInfo in handleLingerComplete");
  4466. return;
  4467. }
  4468. if (DBG) log("handleLingerComplete for " + oldNetwork.name());
  4469. // If we get here it means that the last linger timeout for this network expired. So there
  4470. // must be no other active linger timers, and we must stop lingering.
  4471. oldNetwork.clearLingerState();
  4472. if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
  4473. // Tear the network down.
  4474. teardownUnneededNetwork(oldNetwork);
  4475. } else {
  4476. // Put the network in the background.
  4477. updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
  4478. oldNetwork.networkCapabilities);
  4479. }
  4480. }
  4481. private void makeDefault(NetworkAgentInfo newNetwork) {
  4482. if (DBG) log("Switching to new default network: " + newNetwork);
  4483. setupDataActivityTracking(newNetwork);
  4484. try {
  4485. mNetd.setDefaultNetId(newNetwork.network.netId);
  4486. } catch (Exception e) {
  4487. loge("Exception setting default network :" + e);
  4488. }
  4489. notifyLockdownVpn(newNetwork);
  4490. handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
  4491. updateTcpBufferSizes(newNetwork);
  4492. mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
  4493. notifyIfacesChangedForNetworkStats();
  4494. }
  4495. private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
  4496. // For consistency with previous behaviour, send onLost callbacks before onAvailable.
  4497. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  4498. NetworkRequest nr = nri.request;
  4499. if (!nr.isListen()) continue;
  4500. if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
  4501. nai.removeRequest(nri.request.requestId);
  4502. callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
  4503. }
  4504. }
  4505. if (capabilitiesChanged) {
  4506. notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
  4507. }
  4508. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  4509. NetworkRequest nr = nri.request;
  4510. if (!nr.isListen()) continue;
  4511. if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
  4512. nai.addRequest(nr);
  4513. notifyNetworkAvailable(nai, nri);
  4514. }
  4515. }
  4516. }
  4517. // Handles a network appearing or improving its score.
  4518. //
  4519. // - Evaluates all current NetworkRequests that can be
  4520. // satisfied by newNetwork, and reassigns to newNetwork
  4521. // any such requests for which newNetwork is the best.
  4522. //
  4523. // - Lingers any validated Networks that as a result are no longer
  4524. // needed. A network is needed if it is the best network for
  4525. // one or more NetworkRequests, or if it is a VPN.
  4526. //
  4527. // - Tears down newNetwork if it just became validated
  4528. // but turns out to be unneeded.
  4529. //
  4530. // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
  4531. // networks that have no chance (i.e. even if validated)
  4532. // of becoming the highest scoring network.
  4533. //
  4534. // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
  4535. // it does not remove NetworkRequests that other Networks could better satisfy.
  4536. // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
  4537. // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
  4538. // as it performs better by a factor of the number of Networks.
  4539. //
  4540. // @param newNetwork is the network to be matched against NetworkRequests.
  4541. // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
  4542. // performed to tear down unvalidated networks that have no chance (i.e. even if
  4543. // validated) of becoming the highest scoring network.
  4544. private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
  4545. ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
  4546. if (!newNetwork.everConnected) return;
  4547. boolean keep = newNetwork.isVPN();
  4548. boolean isNewDefault = false;
  4549. NetworkAgentInfo oldDefaultNetwork = null;
  4550. final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
  4551. final int score = newNetwork.getCurrentScore();
  4552. if (VDBG) log("rematching " + newNetwork.name());
  4553. // Find and migrate to this Network any NetworkRequests for
  4554. // which this network is now the best.
  4555. ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
  4556. ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
  4557. NetworkCapabilities nc = newNetwork.networkCapabilities;
  4558. if (VDBG) log(" network has: " + nc);
  4559. for (NetworkRequestInfo nri : mNetworkRequests.values()) {
  4560. // Process requests in the first pass and listens in the second pass. This allows us to
  4561. // change a network's capabilities depending on which requests it has. This is only
  4562. // correct if the change in capabilities doesn't affect whether the network satisfies
  4563. // requests or not, and doesn't affect the network's score.
  4564. if (nri.request.isListen()) continue;
  4565. final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
  4566. final boolean satisfies = newNetwork.satisfies(nri.request);
  4567. if (newNetwork == currentNetwork && satisfies) {
  4568. if (VDBG) {
  4569. log("Network " + newNetwork.name() + " was already satisfying" +
  4570. " request " + nri.request.requestId + ". No change.");
  4571. }
  4572. keep = true;
  4573. continue;
  4574. }
  4575. // check if it satisfies the NetworkCapabilities
  4576. if (VDBG) log(" checking if request is satisfied: " + nri.request);
  4577. if (satisfies) {
  4578. // next check if it's better than any current network we're using for
  4579. // this request
  4580. if (VDBG) {
  4581. log("currentScore = " +
  4582. (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
  4583. ", newScore = " + score);
  4584. }
  4585. if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
  4586. if (VDBG) log("rematch for " + newNetwork.name());
  4587. if (currentNetwork != null) {
  4588. if (VDBG) log(" accepting network in place of " + currentNetwork.name());
  4589. currentNetwork.removeRequest(nri.request.requestId);
  4590. currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
  4591. affectedNetworks.add(currentNetwork);
  4592. } else {
  4593. if (VDBG) log(" accepting network in place of null");
  4594. }
  4595. newNetwork.unlingerRequest(nri.request);
  4596. setNetworkForRequest(nri.request.requestId, newNetwork);
  4597. if (!newNetwork.addRequest(nri.request)) {
  4598. Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
  4599. }
  4600. addedRequests.add(nri);
  4601. keep = true;
  4602. // Tell NetworkFactories about the new score, so they can stop
  4603. // trying to connect if they know they cannot match it.
  4604. // TODO - this could get expensive if we have alot of requests for this
  4605. // network. Think about if there is a way to reduce this. Push
  4606. // netid->request mapping to each factory?
  4607. sendUpdatedScoreToFactories(nri.request, score);
  4608. if (isDefaultRequest(nri)) {
  4609. isNewDefault = true;
  4610. oldDefaultNetwork = currentNetwork;
  4611. if (currentNetwork != null) {
  4612. mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
  4613. }
  4614. }
  4615. }
  4616. } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
  4617. // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
  4618. // mark it as no longer satisfying "nri". Because networks are processed by
  4619. // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
  4620. // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
  4621. // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
  4622. // This means this code doesn't have to handle the case where "currentNetwork" no
  4623. // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
  4624. if (DBG) {
  4625. log("Network " + newNetwork.name() + " stopped satisfying" +
  4626. " request " + nri.request.requestId);
  4627. }
  4628. newNetwork.removeRequest(nri.request.requestId);
  4629. if (currentNetwork == newNetwork) {
  4630. clearNetworkForRequest(nri.request.requestId);
  4631. sendUpdatedScoreToFactories(nri.request, 0);
  4632. } else {
  4633. Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
  4634. newNetwork.name() +
  4635. " without updating mNetworkForRequestId or factories!");
  4636. }
  4637. // TODO: Technically, sending CALLBACK_LOST here is
  4638. // incorrect if there is a replacement network currently
  4639. // connected that can satisfy nri, which is a request
  4640. // (not a listen). However, the only capability that can both
  4641. // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
  4642. // so this code is only incorrect for a network that loses
  4643. // the TRUSTED capability, which is a rare case.
  4644. callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
  4645. }
  4646. }
  4647. if (isNewDefault) {
  4648. // Notify system services that this network is up.
  4649. makeDefault(newNetwork);
  4650. // Log 0 -> X and Y -> X default network transitions, where X is the new default.
  4651. metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
  4652. now, newNetwork, oldDefaultNetwork);
  4653. // Have a new default network, release the transition wakelock in
  4654. scheduleReleaseNetworkTransitionWakelock();
  4655. }
  4656. if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
  4657. Slog.wtf(TAG, String.format(
  4658. "BUG: %s changed requestable capabilities during rematch: %s -> %s",
  4659. newNetwork.name(), nc, newNetwork.networkCapabilities));
  4660. }
  4661. if (newNetwork.getCurrentScore() != score) {
  4662. Slog.wtf(TAG, String.format(
  4663. "BUG: %s changed score during rematch: %d -> %d",
  4664. newNetwork.name(), score, newNetwork.getCurrentScore()));
  4665. }
  4666. // Second pass: process all listens.
  4667. if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
  4668. // If the network went from background to foreground or vice versa, we need to update
  4669. // its foreground state. It is safe to do this after rematching the requests because
  4670. // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
  4671. // capability and does not affect the network's score (see the Slog.wtf call above).
  4672. updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
  4673. } else {
  4674. processListenRequests(newNetwork, false);
  4675. }
  4676. // do this after the default net is switched, but
  4677. // before LegacyTypeTracker sends legacy broadcasts
  4678. for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
  4679. // Linger any networks that are no longer needed. This should be done after sending the
  4680. // available callback for newNetwork.
  4681. for (NetworkAgentInfo nai : affectedNetworks) {
  4682. updateLingerState(nai, now);
  4683. }
  4684. // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
  4685. // does not need to be done in any particular order.
  4686. updateLingerState(newNetwork, now);
  4687. if (isNewDefault) {
  4688. // Maintain the illusion: since the legacy API only
  4689. // understands one network at a time, we must pretend
  4690. // that the current default network disconnected before
  4691. // the new one connected.
  4692. if (oldDefaultNetwork != null) {
  4693. mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
  4694. oldDefaultNetwork, true);
  4695. }
  4696. mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
  4697. mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
  4698. notifyLockdownVpn(newNetwork);
  4699. }
  4700. if (keep) {
  4701. // Notify battery stats service about this network, both the normal
  4702. // interface and any stacked links.
  4703. // TODO: Avoid redoing this; this must only be done once when a network comes online.
  4704. try {
  4705. final IBatteryStats bs = BatteryStatsService.getService();
  4706. final int type = newNetwork.networkInfo.getType();
  4707. final String baseIface = newNetwork.linkProperties.getInterfaceName();
  4708. bs.noteNetworkInterfaceType(baseIface, type);
  4709. for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
  4710. final String stackedIface = stacked.getInterfaceName();
  4711. bs.noteNetworkInterfaceType(stackedIface, type);
  4712. NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
  4713. }
  4714. } catch (RemoteException ignored) {
  4715. }
  4716. // This has to happen after the notifyNetworkCallbacks as that tickles each
  4717. // ConnectivityManager instance so that legacy requests correctly bind dns
  4718. // requests to this network. The legacy users are listening for this bcast
  4719. // and will generally do a dns request so they can ensureRouteToHost and if
  4720. // they do that before the callbacks happen they'll use the default network.
  4721. //
  4722. // TODO: Is there still a race here? We send the broadcast
  4723. // after sending the callback, but if the app can receive the
  4724. // broadcast before the callback, it might still break.
  4725. //
  4726. // This *does* introduce a race where if the user uses the new api
  4727. // (notification callbacks) and then uses the old api (getNetworkInfo(type))
  4728. // they may get old info. Reverse this after the old startUsing api is removed.
  4729. // This is on top of the multiple intent sequencing referenced in the todo above.
  4730. for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
  4731. NetworkRequest nr = newNetwork.requestAt(i);
  4732. if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
  4733. // legacy type tracker filters out repeat adds
  4734. mLegacyTypeTracker.add(nr.legacyType, newNetwork);
  4735. }
  4736. }
  4737. // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
  4738. // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
  4739. // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
  4740. // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
  4741. if (newNetwork.isVPN()) {
  4742. mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
  4743. }
  4744. }
  4745. if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
  4746. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  4747. if (unneeded(nai, UnneededFor.TEARDOWN)) {
  4748. if (nai.getLingerExpiry() > 0) {
  4749. // This network has active linger timers and no requests, but is not
  4750. // lingering. Linger it.
  4751. //
  4752. // One way (the only way?) this can happen if this network is unvalidated
  4753. // and became unneeded due to another network improving its score to the
  4754. // point where this network will no longer be able to satisfy any requests
  4755. // even if it validates.
  4756. updateLingerState(nai, now);
  4757. } else {
  4758. if (DBG) log("Reaping " + nai.name());
  4759. teardownUnneededNetwork(nai);
  4760. }
  4761. }
  4762. }
  4763. }
  4764. }
  4765. /**
  4766. * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
  4767. * being disconnected.
  4768. * @param changed If only one Network's score or capabilities have been modified since the last
  4769. * time this function was called, pass this Network in this argument, otherwise pass
  4770. * null.
  4771. * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
  4772. * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
  4773. * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
  4774. * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
  4775. * network's score.
  4776. */
  4777. private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
  4778. // TODO: This may get slow. The "changed" parameter is provided for future optimization
  4779. // to avoid the slowness. It is not simply enough to process just "changed", for
  4780. // example in the case where "changed"'s score decreases and another network should begin
  4781. // satifying a NetworkRequest that "changed" currently satisfies.
  4782. // Optimization: Only reprocess "changed" if its score improved. This is safe because it
  4783. // can only add more NetworkRequests satisfied by "changed", and this is exactly what
  4784. // rematchNetworkAndRequests() handles.
  4785. final long now = SystemClock.elapsedRealtime();
  4786. if (changed != null && oldScore < changed.getCurrentScore()) {
  4787. rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
  4788. } else {
  4789. final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
  4790. new NetworkAgentInfo[mNetworkAgentInfos.size()]);
  4791. // Rematch higher scoring networks first to prevent requests first matching a lower
  4792. // scoring network and then a higher scoring network, which could produce multiple
  4793. // callbacks and inadvertently unlinger networks.
  4794. Arrays.sort(nais);
  4795. for (NetworkAgentInfo nai : nais) {
  4796. rematchNetworkAndRequests(nai,
  4797. // Only reap the last time through the loop. Reaping before all rematching
  4798. // is complete could incorrectly teardown a network that hasn't yet been
  4799. // rematched.
  4800. (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
  4801. : ReapUnvalidatedNetworks.REAP,
  4802. now);
  4803. }
  4804. }
  4805. }
  4806. private void updateInetCondition(NetworkAgentInfo nai) {
  4807. // Don't bother updating until we've graduated to validated at least once.
  4808. if (!nai.everValidated) return;
  4809. // For now only update icons for default connection.
  4810. // TODO: Update WiFi and cellular icons separately. b/17237507
  4811. if (!isDefaultNetwork(nai)) return;
  4812. int newInetCondition = nai.lastValidated ? 100 : 0;
  4813. // Don't repeat publish.
  4814. if (newInetCondition == mDefaultInetConditionPublished) return;
  4815. mDefaultInetConditionPublished = newInetCondition;
  4816. sendInetConditionBroadcast(nai.networkInfo);
  4817. }
  4818. private void notifyLockdownVpn(NetworkAgentInfo nai) {
  4819. synchronized (mVpns) {
  4820. if (mLockdownTracker != null) {
  4821. if (nai != null && nai.isVPN()) {
  4822. mLockdownTracker.onVpnStateChanged(nai.networkInfo);
  4823. } else {
  4824. mLockdownTracker.onNetworkInfoChanged();
  4825. }
  4826. }
  4827. }
  4828. }
  4829. private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
  4830. final NetworkInfo.State state = newInfo.getState();
  4831. NetworkInfo oldInfo = null;
  4832. final int oldScore = networkAgent.getCurrentScore();
  4833. synchronized (networkAgent) {
  4834. oldInfo = networkAgent.networkInfo;
  4835. networkAgent.networkInfo = newInfo;
  4836. }
  4837. notifyLockdownVpn(networkAgent);
  4838. if (DBG) {
  4839. log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
  4840. (oldInfo == null ? "null" : oldInfo.getState()) +
  4841. " to " + state);
  4842. }
  4843. if (!networkAgent.created
  4844. && (state == NetworkInfo.State.CONNECTED
  4845. || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
  4846. // A network that has just connected has zero requests and is thus a foreground network.
  4847. networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
  4848. try {
  4849. // This should never fail. Specifying an already in use NetID will cause failure.
  4850. if (networkAgent.isVPN()) {
  4851. mNetd.createVirtualNetwork(networkAgent.network.netId,
  4852. !networkAgent.linkProperties.getDnsServers().isEmpty(),
  4853. (networkAgent.networkMisc == null ||
  4854. !networkAgent.networkMisc.allowBypass));
  4855. } else {
  4856. mNetd.createPhysicalNetwork(networkAgent.network.netId,
  4857. getNetworkPermission(networkAgent.networkCapabilities));
  4858. }
  4859. } catch (Exception e) {
  4860. loge("Error creating network " + networkAgent.network.netId + ": "
  4861. + e.getMessage());
  4862. return;
  4863. }
  4864. networkAgent.created = true;
  4865. }
  4866. if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
  4867. networkAgent.everConnected = true;
  4868. updateLinkProperties(networkAgent, null);
  4869. notifyIfacesChangedForNetworkStats();
  4870. networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
  4871. scheduleUnvalidatedPrompt(networkAgent);
  4872. if (networkAgent.isVPN()) {
  4873. // Temporarily disable the default proxy (not global).
  4874. synchronized (mProxyLock) {
  4875. if (!mDefaultProxyDisabled) {
  4876. mDefaultProxyDisabled = true;
  4877. if (mGlobalProxy == null && mDefaultProxy != null) {
  4878. sendProxyBroadcast(null);
  4879. }
  4880. }
  4881. }
  4882. // TODO: support proxy per network.
  4883. }
  4884. // Whether a particular NetworkRequest listen should cause signal strength thresholds to
  4885. // be communicated to a particular NetworkAgent depends only on the network's immutable,
  4886. // capabilities, so it only needs to be done once on initial connect, not every time the
  4887. // network's capabilities change. Note that we do this before rematching the network,
  4888. // so we could decide to tear it down immediately afterwards. That's fine though - on
  4889. // disconnection NetworkAgents should stop any signal strength monitoring they have been
  4890. // doing.
  4891. updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
  4892. // Consider network even though it is not yet validated.
  4893. final long now = SystemClock.elapsedRealtime();
  4894. rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
  4895. // This has to happen after matching the requests, because callbacks are just requests.
  4896. notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
  4897. } else if (state == NetworkInfo.State.DISCONNECTED) {
  4898. networkAgent.asyncChannel.disconnect();
  4899. if (networkAgent.isVPN()) {
  4900. synchronized (mProxyLock) {
  4901. if (mDefaultProxyDisabled) {
  4902. mDefaultProxyDisabled = false;
  4903. if (mGlobalProxy == null && mDefaultProxy != null) {
  4904. sendProxyBroadcast(mDefaultProxy);
  4905. }
  4906. }
  4907. }
  4908. updateUids(networkAgent, networkAgent.networkCapabilities, null);
  4909. }
  4910. } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
  4911. state == NetworkInfo.State.SUSPENDED) {
  4912. // going into or coming out of SUSPEND: rescore and notify
  4913. if (networkAgent.getCurrentScore() != oldScore) {
  4914. rematchAllNetworksAndRequests(networkAgent, oldScore);
  4915. }
  4916. updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
  4917. networkAgent.networkCapabilities);
  4918. // TODO (b/73132094) : remove this call once the few users of onSuspended and
  4919. // onResumed have been removed.
  4920. notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
  4921. ConnectivityManager.CALLBACK_SUSPENDED :
  4922. ConnectivityManager.CALLBACK_RESUMED));
  4923. mLegacyTypeTracker.update(networkAgent);
  4924. }
  4925. }
  4926. private void updateNetworkScore(NetworkAgentInfo nai, int score) {
  4927. if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
  4928. if (score < 0) {
  4929. loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
  4930. "). Bumping score to min of 0");
  4931. score = 0;
  4932. }
  4933. final int oldScore = nai.getCurrentScore();
  4934. nai.setCurrentScore(score);
  4935. rematchAllNetworksAndRequests(nai, oldScore);
  4936. sendUpdatedScoreToFactories(nai);
  4937. }
  4938. // Notify only this one new request of the current state. Transfer all the
  4939. // current state by calling NetworkCapabilities and LinkProperties callbacks
  4940. // so that callers can be guaranteed to have as close to atomicity in state
  4941. // transfer as can be supported by this current API.
  4942. protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
  4943. mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
  4944. if (nri.mPendingIntent != null) {
  4945. sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
  4946. // Attempt no subsequent state pushes where intents are involved.
  4947. return;
  4948. }
  4949. callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
  4950. }
  4951. private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
  4952. // The NetworkInfo we actually send out has no bearing on the real
  4953. // state of affairs. For example, if the default connection is mobile,
  4954. // and a request for HIPRI has just gone away, we need to pretend that
  4955. // HIPRI has just disconnected. So we need to set the type to HIPRI and
  4956. // the state to DISCONNECTED, even though the network is of type MOBILE
  4957. // and is still connected.
  4958. NetworkInfo info = new NetworkInfo(nai.networkInfo);
  4959. info.setType(type);
  4960. if (state != DetailedState.DISCONNECTED) {
  4961. info.setDetailedState(state, null, info.getExtraInfo());
  4962. sendConnectedBroadcast(info);
  4963. } else {
  4964. info.setDetailedState(state, info.getReason(), info.getExtraInfo());
  4965. Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
  4966. intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
  4967. intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
  4968. if (info.isFailover()) {
  4969. intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
  4970. nai.networkInfo.setFailover(false);
  4971. }
  4972. if (info.getReason() != null) {
  4973. intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
  4974. }
  4975. if (info.getExtraInfo() != null) {
  4976. intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
  4977. }
  4978. NetworkAgentInfo newDefaultAgent = null;
  4979. if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
  4980. newDefaultAgent = getDefaultNetwork();
  4981. if (newDefaultAgent != null) {
  4982. intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
  4983. newDefaultAgent.networkInfo);
  4984. } else {
  4985. intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
  4986. }
  4987. }
  4988. intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
  4989. mDefaultInetConditionPublished);
  4990. sendStickyBroadcast(intent);
  4991. if (newDefaultAgent != null) {
  4992. sendConnectedBroadcast(newDefaultAgent.networkInfo);
  4993. }
  4994. }
  4995. }
  4996. protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
  4997. if (VDBG) {
  4998. String notification = ConnectivityManager.getCallbackName(notifyType);
  4999. log("notifyType " + notification + " for " + networkAgent.name());
  5000. }
  5001. for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
  5002. NetworkRequest nr = networkAgent.requestAt(i);
  5003. NetworkRequestInfo nri = mNetworkRequests.get(nr);
  5004. if (VDBG) log(" sending notification for " + nr);
  5005. // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
  5006. // a network that no longer satisfies the listen?
  5007. if (nri.mPendingIntent == null) {
  5008. callCallbackForRequest(nri, networkAgent, notifyType, arg1);
  5009. } else {
  5010. sendPendingIntentForRequest(nri, networkAgent, notifyType);
  5011. }
  5012. }
  5013. }
  5014. protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
  5015. notifyNetworkCallbacks(networkAgent, notifyType, 0);
  5016. }
  5017. /**
  5018. * Returns the list of all interfaces that could be used by network traffic that does not
  5019. * explicitly specify a network. This includes the default network, but also all VPNs that are
  5020. * currently connected.
  5021. *
  5022. * Must be called on the handler thread.
  5023. */
  5024. private Network[] getDefaultNetworks() {
  5025. ArrayList<Network> defaultNetworks = new ArrayList<>();
  5026. NetworkAgentInfo defaultNetwork = getDefaultNetwork();
  5027. for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
  5028. if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
  5029. defaultNetworks.add(nai.network);
  5030. }
  5031. }
  5032. return defaultNetworks.toArray(new Network[0]);
  5033. }
  5034. /**
  5035. * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
  5036. * properties tracked by NetworkStatsService on an active iface has changed.
  5037. */
  5038. private void notifyIfacesChangedForNetworkStats() {
  5039. try {
  5040. mStatsService.forceUpdateIfaces(getDefaultNetworks());
  5041. } catch (Exception ignored) {
  5042. }
  5043. }
  5044. @Override
  5045. public boolean addVpnAddress(String address, int prefixLength) {
  5046. int user = UserHandle.getUserId(Binder.getCallingUid());
  5047. synchronized (mVpns) {
  5048. throwIfLockdownEnabled();
  5049. return mVpns.get(user).addAddress(address, prefixLength);
  5050. }
  5051. }
  5052. @Override
  5053. public boolean removeVpnAddress(String address, int prefixLength) {
  5054. int user = UserHandle.getUserId(Binder.getCallingUid());
  5055. synchronized (mVpns) {
  5056. throwIfLockdownEnabled();
  5057. return mVpns.get(user).removeAddress(address, prefixLength);
  5058. }
  5059. }
  5060. @Override
  5061. public boolean setUnderlyingNetworksForVpn(Network[] networks) {
  5062. int user = UserHandle.getUserId(Binder.getCallingUid());
  5063. final boolean success;
  5064. synchronized (mVpns) {
  5065. throwIfLockdownEnabled();
  5066. success = mVpns.get(user).setUnderlyingNetworks(networks);
  5067. }
  5068. if (success) {
  5069. mHandler.post(() -> notifyIfacesChangedForNetworkStats());
  5070. }
  5071. return success;
  5072. }
  5073. @Override
  5074. public String getCaptivePortalServerUrl() {
  5075. enforceConnectivityInternalPermission();
  5076. return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
  5077. }
  5078. @Override
  5079. public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
  5080. IBinder binder, String srcAddr, int srcPort, String dstAddr) {
  5081. enforceKeepalivePermission();
  5082. mKeepaliveTracker.startNattKeepalive(
  5083. getNetworkAgentInfoForNetwork(network),
  5084. intervalSeconds, messenger, binder,
  5085. srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
  5086. }
  5087. @Override
  5088. public void stopKeepalive(Network network, int slot) {
  5089. mHandler.sendMessage(mHandler.obtainMessage(
  5090. NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
  5091. }
  5092. @Override
  5093. public void factoryReset() {
  5094. enforceConnectivityInternalPermission();
  5095. if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
  5096. return;
  5097. }
  5098. final int userId = UserHandle.getCallingUserId();
  5099. // Turn airplane mode off
  5100. setAirplaneMode(false);
  5101. if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
  5102. // Untether
  5103. String pkgName = mContext.getOpPackageName();
  5104. for (String tether : getTetheredIfaces()) {
  5105. untether(tether, pkgName);
  5106. }
  5107. }
  5108. if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
  5109. // Remove always-on package
  5110. synchronized (mVpns) {
  5111. final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
  5112. if (alwaysOnPackage != null) {
  5113. setAlwaysOnVpnPackage(userId, null, false);
  5114. setVpnPackageAuthorization(alwaysOnPackage, userId, false);
  5115. }
  5116. // Turn Always-on VPN off
  5117. if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
  5118. final long ident = Binder.clearCallingIdentity();
  5119. try {
  5120. mKeyStore.delete(Credentials.LOCKDOWN_VPN);
  5121. mLockdownEnabled = false;
  5122. setLockdownTracker(null);
  5123. } finally {
  5124. Binder.restoreCallingIdentity(ident);
  5125. }
  5126. }
  5127. // Turn VPN off
  5128. VpnConfig vpnConfig = getVpnConfig(userId);
  5129. if (vpnConfig != null) {
  5130. if (vpnConfig.legacy) {
  5131. prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
  5132. } else {
  5133. // Prevent this app (packagename = vpnConfig.user) from initiating
  5134. // VPN connections in the future without user intervention.
  5135. setVpnPackageAuthorization(vpnConfig.user, userId, false);
  5136. prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
  5137. }
  5138. }
  5139. }
  5140. }
  5141. Settings.Global.putString(mContext.getContentResolver(),
  5142. Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
  5143. }
  5144. @VisibleForTesting
  5145. public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
  5146. NetworkAgentInfo nai, NetworkRequest defaultRequest) {
  5147. return new NetworkMonitor(context, handler, nai, defaultRequest);
  5148. }
  5149. @VisibleForTesting
  5150. MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
  5151. return new MultinetworkPolicyTracker(c, h, r);
  5152. }
  5153. @VisibleForTesting
  5154. public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
  5155. return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
  5156. }
  5157. @VisibleForTesting
  5158. public boolean hasService(String name) {
  5159. return ServiceManager.checkService(name) != null;
  5160. }
  5161. @VisibleForTesting
  5162. protected IpConnectivityMetrics.Logger metricsLogger() {
  5163. return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
  5164. "no IpConnectivityMetrics service");
  5165. }
  5166. private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
  5167. int[] transports = nai.networkCapabilities.getTransportTypes();
  5168. mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
  5169. }
  5170. private static boolean toBool(int encodedBoolean) {
  5171. return encodedBoolean != 0; // Only 0 means false.
  5172. }
  5173. private static int encodeBool(boolean b) {
  5174. return b ? 1 : 0;
  5175. }
  5176. }