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