1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.net; 18 19 import android.annotation.IntDef; 20 import android.annotation.IntRange; 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.annotation.SuppressLint; 24 import android.annotation.SystemApi; 25 import android.annotation.TestApi; 26 import android.compat.annotation.UnsupportedAppUsage; 27 import android.content.Context; 28 import android.os.Build; 29 import android.os.Bundle; 30 import android.os.ConditionVariable; 31 import android.os.Handler; 32 import android.os.Looper; 33 import android.os.Message; 34 import android.os.RemoteException; 35 import android.telephony.data.EpsBearerQosSessionAttributes; 36 import android.telephony.data.NrQosSessionAttributes; 37 import android.util.Log; 38 39 import com.android.internal.annotations.VisibleForTesting; 40 41 import java.lang.annotation.Retention; 42 import java.lang.annotation.RetentionPolicy; 43 import java.time.Duration; 44 import java.util.ArrayList; 45 import java.util.List; 46 import java.util.Objects; 47 import java.util.concurrent.atomic.AtomicBoolean; 48 49 /** 50 * A utility class for handling for communicating between bearer-specific 51 * code and ConnectivityService. 52 * 53 * An agent manages the life cycle of a network. A network starts its 54 * life cycle when {@link register} is called on NetworkAgent. The network 55 * is then connecting. When full L3 connectivity has been established, 56 * the agent should call {@link markConnected} to inform the system that 57 * this network is ready to use. When the network disconnects its life 58 * ends and the agent should call {@link unregister}, at which point the 59 * system will clean up and free resources. 60 * Any reconnection becomes a new logical network, so after a network 61 * is disconnected the agent cannot be used any more. Network providers 62 * should create a new NetworkAgent instance to handle new connections. 63 * 64 * A bearer may have more than one NetworkAgent if it can simultaneously 65 * support separate networks (IMS / Internet / MMS Apns on cellular, or 66 * perhaps connections with different SSID or P2P for Wi-Fi). 67 * 68 * This class supports methods to start and stop sending keepalive packets. 69 * Keepalive packets are typically sent at periodic intervals over a network 70 * with NAT when there is no other traffic to avoid the network forcefully 71 * closing the connection. NetworkAgents that manage technologies that 72 * have hardware support for keepalive should implement the related 73 * methods to save battery life. NetworkAgent that cannot get support 74 * without waking up the CPU should not, as this would be prohibitive in 75 * terms of battery - these agents should simply not override the related 76 * methods, which results in the implementation returning 77 * {@link SocketKeepalive.ERROR_UNSUPPORTED} as appropriate. 78 * 79 * Keepalive packets need to be sent at relatively frequent intervals 80 * (a few seconds to a few minutes). As the contents of keepalive packets 81 * depend on the current network status, hardware needs to be configured 82 * to send them and has a limited amount of memory to do so. The HAL 83 * formalizes this as slots that an implementation can configure to send 84 * the correct packets. Devices typically have a small number of slots 85 * per radio technology, and the specific number of slots for each 86 * technology is specified in configuration files. 87 * See {@link SocketKeepalive} for details. 88 * 89 * @hide 90 */ 91 @SystemApi 92 public abstract class NetworkAgent { 93 /** 94 * The {@link Network} corresponding to this object. 95 */ 96 @Nullable 97 private volatile Network mNetwork; 98 99 @Nullable 100 private volatile INetworkAgentRegistry mRegistry; 101 102 private interface RegistryAction { execute(@onNull INetworkAgentRegistry registry)103 void execute(@NonNull INetworkAgentRegistry registry) throws RemoteException; 104 } 105 106 private final Handler mHandler; 107 private final String LOG_TAG; 108 private static final boolean DBG = true; 109 private static final boolean VDBG = false; 110 /** @hide */ 111 @TestApi 112 public static final int MIN_LINGER_TIMER_MS = 2000; 113 private final ArrayList<RegistryAction> mPreConnectedQueue = new ArrayList<>(); 114 private volatile long mLastBwRefreshTime = 0; 115 private static final long BW_REFRESH_MIN_WIN_MS = 500; 116 private boolean mBandwidthUpdateScheduled = false; 117 private AtomicBoolean mBandwidthUpdatePending = new AtomicBoolean(false); 118 @NonNull 119 private NetworkInfo mNetworkInfo; 120 @NonNull 121 private final Object mRegisterLock = new Object(); 122 123 /** 124 * The ID of the {@link NetworkProvider} that created this object, or 125 * {@link NetworkProvider#ID_NONE} if unknown. 126 * @hide 127 */ 128 public final int providerId; 129 130 // ConnectivityService parses message constants from itself and NetworkAgent with MessageUtils 131 // for debugging purposes, and crashes if some messages have the same values. 132 // TODO: have ConnectivityService store message names in different maps and remove this base 133 private static final int BASE = 200; 134 135 /** 136 * Sent by ConnectivityService to the NetworkAgent to inform it of 137 * suspected connectivity problems on its network. The NetworkAgent 138 * should take steps to verify and correct connectivity. 139 * @hide 140 */ 141 public static final int CMD_SUSPECT_BAD = BASE; 142 143 /** 144 * Sent by the NetworkAgent (note the EVENT vs CMD prefix) to 145 * ConnectivityService to pass the current NetworkInfo (connection state). 146 * Sent when the NetworkInfo changes, mainly due to change of state. 147 * obj = NetworkInfo 148 * @hide 149 */ 150 public static final int EVENT_NETWORK_INFO_CHANGED = BASE + 1; 151 152 /** 153 * Sent by the NetworkAgent to ConnectivityService to pass the current 154 * NetworkCapabilties. 155 * obj = NetworkCapabilities 156 * @hide 157 */ 158 public static final int EVENT_NETWORK_CAPABILITIES_CHANGED = BASE + 2; 159 160 /** 161 * Sent by the NetworkAgent to ConnectivityService to pass the current 162 * NetworkProperties. 163 * obj = NetworkProperties 164 * @hide 165 */ 166 public static final int EVENT_NETWORK_PROPERTIES_CHANGED = BASE + 3; 167 168 /** 169 * Centralize the place where base network score, and network score scaling, will be 170 * stored, so as we can consistently compare apple and oranges, or wifi, ethernet and LTE 171 * @hide 172 */ 173 public static final int WIFI_BASE_SCORE = 60; 174 175 /** 176 * Sent by the NetworkAgent to ConnectivityService to pass the current 177 * network score. 178 * arg1 = network score int 179 * @hide 180 */ 181 public static final int EVENT_NETWORK_SCORE_CHANGED = BASE + 4; 182 183 /** 184 * Sent by the NetworkAgent to ConnectivityService to pass the current 185 * list of underlying networks. 186 * obj = array of Network objects 187 * @hide 188 */ 189 public static final int EVENT_UNDERLYING_NETWORKS_CHANGED = BASE + 5; 190 191 /** 192 * Sent by the NetworkAgent to ConnectivityService to pass the current value of the teardown 193 * delay. 194 * arg1 = teardown delay in milliseconds 195 * @hide 196 */ 197 public static final int EVENT_TEARDOWN_DELAY_CHANGED = BASE + 6; 198 199 /** 200 * The maximum value for the teardown delay, in milliseconds. 201 * @hide 202 */ 203 public static final int MAX_TEARDOWN_DELAY_MS = 5000; 204 205 /** 206 * Sent by ConnectivityService to the NetworkAgent to inform the agent of the 207 * networks status - whether we could use the network or could not, due to 208 * either a bad network configuration (no internet link) or captive portal. 209 * 210 * arg1 = either {@code VALID_NETWORK} or {@code INVALID_NETWORK} 211 * obj = Bundle containing map from {@code REDIRECT_URL_KEY} to {@code String} 212 * representing URL that Internet probe was redirect to, if it was redirected, 213 * or mapping to {@code null} otherwise. 214 * @hide 215 */ 216 public static final int CMD_REPORT_NETWORK_STATUS = BASE + 7; 217 218 /** 219 * Network validation suceeded. 220 * Corresponds to {@link NetworkCapabilities.NET_CAPABILITY_VALIDATED}. 221 */ 222 public static final int VALIDATION_STATUS_VALID = 1; 223 224 /** 225 * Network validation was attempted and failed. This may be received more than once as 226 * subsequent validation attempts are made. 227 */ 228 public static final int VALIDATION_STATUS_NOT_VALID = 2; 229 230 /** @hide */ 231 @Retention(RetentionPolicy.SOURCE) 232 @IntDef(prefix = { "VALIDATION_STATUS_" }, value = { 233 VALIDATION_STATUS_VALID, 234 VALIDATION_STATUS_NOT_VALID 235 }) 236 public @interface ValidationStatus {} 237 238 // TODO: remove. 239 /** @hide */ 240 public static final int VALID_NETWORK = 1; 241 /** @hide */ 242 public static final int INVALID_NETWORK = 2; 243 244 /** 245 * The key for the redirect URL in the Bundle argument of {@code CMD_REPORT_NETWORK_STATUS}. 246 * @hide 247 */ 248 public static final String REDIRECT_URL_KEY = "redirect URL"; 249 250 /** 251 * Sent by the NetworkAgent to ConnectivityService to indicate this network was 252 * explicitly selected. This should be sent before the NetworkInfo is marked 253 * CONNECTED so it can be given special treatment at that time. 254 * 255 * obj = boolean indicating whether to use this network even if unvalidated 256 * @hide 257 */ 258 public static final int EVENT_SET_EXPLICITLY_SELECTED = BASE + 8; 259 260 /** 261 * Sent by ConnectivityService to the NetworkAgent to inform the agent of 262 * whether the network should in the future be used even if not validated. 263 * This decision is made by the user, but it is the network transport's 264 * responsibility to remember it. 265 * 266 * arg1 = 1 if true, 0 if false 267 * @hide 268 */ 269 public static final int CMD_SAVE_ACCEPT_UNVALIDATED = BASE + 9; 270 271 /** 272 * Sent by ConnectivityService to the NetworkAgent to inform the agent to pull 273 * the underlying network connection for updated bandwidth information. 274 * @hide 275 */ 276 public static final int CMD_REQUEST_BANDWIDTH_UPDATE = BASE + 10; 277 278 /** 279 * Sent by ConnectivityService to the NetworkAgent to request that the specified packet be sent 280 * periodically on the given interval. 281 * 282 * arg1 = the hardware slot number of the keepalive to start 283 * arg2 = interval in seconds 284 * obj = KeepalivePacketData object describing the data to be sent 285 * 286 * @hide 287 */ 288 public static final int CMD_START_SOCKET_KEEPALIVE = BASE + 11; 289 290 /** 291 * Requests that the specified keepalive packet be stopped. 292 * 293 * arg1 = unused 294 * arg2 = error code (SUCCESS) 295 * obj = callback to identify the keepalive 296 * 297 * Also used internally by ConnectivityService / KeepaliveTracker, with different semantics. 298 * @hide 299 */ 300 public static final int CMD_STOP_SOCKET_KEEPALIVE = BASE + 12; 301 302 /** 303 * Sent by the NetworkAgent to ConnectivityService to provide status on a socket keepalive 304 * request. This may either be the reply to a CMD_START_SOCKET_KEEPALIVE, or an asynchronous 305 * error notification. 306 * 307 * This is also sent by KeepaliveTracker to the app's {@link SocketKeepalive}, 308 * so that the app's {@link SocketKeepalive.Callback} methods can be called. 309 * 310 * arg1 = hardware slot number of the keepalive 311 * arg2 = error code 312 * @hide 313 */ 314 public static final int EVENT_SOCKET_KEEPALIVE = BASE + 13; 315 316 /** 317 * Sent by ConnectivityService to inform this network transport of signal strength thresholds 318 * that when crossed should trigger a system wakeup and a NetworkCapabilities update. 319 * 320 * obj = int[] describing signal strength thresholds. 321 * @hide 322 */ 323 public static final int CMD_SET_SIGNAL_STRENGTH_THRESHOLDS = BASE + 14; 324 325 /** 326 * Sent by ConnectivityService to the NeworkAgent to inform the agent to avoid 327 * automatically reconnecting to this network (e.g. via autojoin). Happens 328 * when user selects "No" option on the "Stay connected?" dialog box. 329 * @hide 330 */ 331 public static final int CMD_PREVENT_AUTOMATIC_RECONNECT = BASE + 15; 332 333 /** 334 * Sent by the KeepaliveTracker to NetworkAgent to add a packet filter. 335 * 336 * For TCP keepalive offloads, keepalive packets are sent by the firmware. However, because the 337 * remote site will send ACK packets in response to the keepalive packets, the firmware also 338 * needs to be configured to properly filter the ACKs to prevent the system from waking up. 339 * This does not happen with UDP, so this message is TCP-specific. 340 * arg1 = hardware slot number of the keepalive to filter for. 341 * obj = the keepalive packet to send repeatedly. 342 * @hide 343 */ 344 public static final int CMD_ADD_KEEPALIVE_PACKET_FILTER = BASE + 16; 345 346 /** 347 * Sent by the KeepaliveTracker to NetworkAgent to remove a packet filter. See 348 * {@link #CMD_ADD_KEEPALIVE_PACKET_FILTER}. 349 * arg1 = hardware slot number of the keepalive packet filter to remove. 350 * @hide 351 */ 352 public static final int CMD_REMOVE_KEEPALIVE_PACKET_FILTER = BASE + 17; 353 354 /** 355 * Sent by ConnectivityService to the NetworkAgent to complete the bidirectional connection. 356 * obj = INetworkAgentRegistry 357 */ 358 private static final int EVENT_AGENT_CONNECTED = BASE + 18; 359 360 /** 361 * Sent by ConnectivityService to the NetworkAgent to inform the agent that it was disconnected. 362 */ 363 private static final int EVENT_AGENT_DISCONNECTED = BASE + 19; 364 365 /** 366 * Sent by QosCallbackTracker to {@link NetworkAgent} to register a new filter with 367 * callback. 368 * 369 * arg1 = QoS agent callback ID 370 * obj = {@link QosFilter} 371 * @hide 372 */ 373 public static final int CMD_REGISTER_QOS_CALLBACK = BASE + 20; 374 375 /** 376 * Sent by QosCallbackTracker to {@link NetworkAgent} to unregister a callback. 377 * 378 * arg1 = QoS agent callback ID 379 * @hide 380 */ 381 public static final int CMD_UNREGISTER_QOS_CALLBACK = BASE + 21; 382 383 /** 384 * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent that its native 385 * network was created and the Network object is now valid. 386 * 387 * @hide 388 */ 389 public static final int CMD_NETWORK_CREATED = BASE + 22; 390 391 /** 392 * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent that its native 393 * network was destroyed. 394 * 395 * @hide 396 */ 397 public static final int CMD_NETWORK_DESTROYED = BASE + 23; 398 399 /** 400 * Sent by the NetworkAgent to ConnectivityService to set the linger duration for this network 401 * agent. 402 * arg1 = the linger duration, represents by {@link Duration}. 403 * 404 * @hide 405 */ 406 public static final int EVENT_LINGER_DURATION_CHANGED = BASE + 24; 407 408 /** 409 * Sent by the NetworkAgent to ConnectivityService to set add a DSCP policy. 410 * 411 * @hide 412 */ 413 public static final int EVENT_ADD_DSCP_POLICY = BASE + 25; 414 415 /** 416 * Sent by the NetworkAgent to ConnectivityService to set remove a DSCP policy. 417 * 418 * @hide 419 */ 420 public static final int EVENT_REMOVE_DSCP_POLICY = BASE + 26; 421 422 /** 423 * Sent by the NetworkAgent to ConnectivityService to remove all DSCP policies. 424 * 425 * @hide 426 */ 427 public static final int EVENT_REMOVE_ALL_DSCP_POLICIES = BASE + 27; 428 429 /** 430 * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent of an updated 431 * status for a DSCP policy. 432 * 433 * @hide 434 */ 435 public static final int CMD_DSCP_POLICY_STATUS = BASE + 28; 436 437 /** 438 * Sent by the NetworkAgent to ConnectivityService to notify that this network is expected to be 439 * replaced within the specified time by a similar network. 440 * arg1 = timeout in milliseconds 441 * @hide 442 */ 443 public static final int EVENT_UNREGISTER_AFTER_REPLACEMENT = BASE + 29; 444 445 /** 446 * DSCP policy was successfully added. 447 */ 448 public static final int DSCP_POLICY_STATUS_SUCCESS = 0; 449 450 /** 451 * DSCP policy was rejected for any reason besides invalid classifier or insufficient resources. 452 */ 453 public static final int DSCP_POLICY_STATUS_REQUEST_DECLINED = 1; 454 455 /** 456 * Requested DSCP policy contained a classifier which is not supported. 457 */ 458 public static final int DSCP_POLICY_STATUS_REQUESTED_CLASSIFIER_NOT_SUPPORTED = 2; 459 460 /** 461 * Requested DSCP policy was not added due to insufficient processing resources. 462 */ 463 // TODO: should this error case be supported? 464 public static final int DSCP_POLICY_STATUS_INSUFFICIENT_PROCESSING_RESOURCES = 3; 465 466 /** 467 * DSCP policy was deleted. 468 */ 469 public static final int DSCP_POLICY_STATUS_DELETED = 4; 470 471 /** 472 * DSCP policy was not found during deletion. 473 */ 474 public static final int DSCP_POLICY_STATUS_POLICY_NOT_FOUND = 5; 475 476 /** @hide */ 477 @IntDef(prefix = "DSCP_POLICY_STATUS_", value = { 478 DSCP_POLICY_STATUS_SUCCESS, 479 DSCP_POLICY_STATUS_REQUEST_DECLINED, 480 DSCP_POLICY_STATUS_REQUESTED_CLASSIFIER_NOT_SUPPORTED, 481 DSCP_POLICY_STATUS_INSUFFICIENT_PROCESSING_RESOURCES, 482 DSCP_POLICY_STATUS_DELETED 483 }) 484 @Retention(RetentionPolicy.SOURCE) 485 public @interface DscpPolicyStatus {} 486 getLegacyNetworkInfo(final NetworkAgentConfig config)487 private static NetworkInfo getLegacyNetworkInfo(final NetworkAgentConfig config) { 488 final NetworkInfo ni = new NetworkInfo(config.legacyType, config.legacySubType, 489 config.legacyTypeName, config.legacySubTypeName); 490 ni.setIsAvailable(true); 491 ni.setDetailedState(NetworkInfo.DetailedState.CONNECTING, null /* reason */, 492 config.getLegacyExtraInfo()); 493 return ni; 494 } 495 496 // Temporary backward compatibility constructor NetworkAgent(@onNull Context context, @NonNull Looper looper, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, int score, @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider)497 public NetworkAgent(@NonNull Context context, @NonNull Looper looper, @NonNull String logTag, 498 @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, int score, 499 @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider) { 500 this(context, looper, logTag, nc, lp, 501 new NetworkScore.Builder().setLegacyInt(score).build(), config, provider); 502 } 503 504 /** 505 * Create a new network agent. 506 * @param context a {@link Context} to get system services from. 507 * @param looper the {@link Looper} on which to invoke the callbacks. 508 * @param logTag the tag for logs 509 * @param nc the initial {@link NetworkCapabilities} of this network. Update with 510 * sendNetworkCapabilities. 511 * @param lp the initial {@link LinkProperties} of this network. Update with sendLinkProperties. 512 * @param score the initial score of this network. Update with sendNetworkScore. 513 * @param config an immutable {@link NetworkAgentConfig} for this agent. 514 * @param provider the {@link NetworkProvider} managing this agent. 515 */ NetworkAgent(@onNull Context context, @NonNull Looper looper, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider)516 public NetworkAgent(@NonNull Context context, @NonNull Looper looper, @NonNull String logTag, 517 @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, 518 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, 519 @Nullable NetworkProvider provider) { 520 this(looper, context, logTag, nc, lp, score, config, 521 provider == null ? NetworkProvider.ID_NONE : provider.getProviderId(), 522 getLegacyNetworkInfo(config)); 523 } 524 525 private static class InitialConfiguration { 526 public final Context context; 527 public final NetworkCapabilities capabilities; 528 public final LinkProperties properties; 529 public final NetworkScore score; 530 public final NetworkAgentConfig config; 531 public final NetworkInfo info; InitialConfiguration(@onNull Context context, @NonNull NetworkCapabilities capabilities, @NonNull LinkProperties properties, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, @NonNull NetworkInfo info)532 InitialConfiguration(@NonNull Context context, @NonNull NetworkCapabilities capabilities, 533 @NonNull LinkProperties properties, @NonNull NetworkScore score, 534 @NonNull NetworkAgentConfig config, @NonNull NetworkInfo info) { 535 this.context = context; 536 this.capabilities = capabilities; 537 this.properties = properties; 538 this.score = score; 539 this.config = config; 540 this.info = info; 541 } 542 } 543 private volatile InitialConfiguration mInitialConfiguration; 544 NetworkAgent(@onNull Looper looper, @NonNull Context context, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId, @NonNull NetworkInfo ni)545 private NetworkAgent(@NonNull Looper looper, @NonNull Context context, @NonNull String logTag, 546 @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, 547 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId, 548 @NonNull NetworkInfo ni) { 549 mHandler = new NetworkAgentHandler(looper); 550 LOG_TAG = logTag; 551 mNetworkInfo = new NetworkInfo(ni); 552 this.providerId = providerId; 553 if (ni == null || nc == null || lp == null) { 554 throw new IllegalArgumentException(); 555 } 556 557 mInitialConfiguration = new InitialConfiguration(context, 558 new NetworkCapabilities(nc, NetworkCapabilities.REDACT_NONE), 559 new LinkProperties(lp), score, config, ni); 560 } 561 562 private class NetworkAgentHandler extends Handler { NetworkAgentHandler(Looper looper)563 NetworkAgentHandler(Looper looper) { 564 super(looper); 565 } 566 567 @Override handleMessage(Message msg)568 public void handleMessage(Message msg) { 569 switch (msg.what) { 570 case EVENT_AGENT_CONNECTED: { 571 if (mRegistry != null) { 572 log("Received new connection while already connected!"); 573 } else { 574 if (VDBG) log("NetworkAgent fully connected"); 575 synchronized (mPreConnectedQueue) { 576 final INetworkAgentRegistry registry = (INetworkAgentRegistry) msg.obj; 577 mRegistry = registry; 578 for (RegistryAction a : mPreConnectedQueue) { 579 try { 580 a.execute(registry); 581 } catch (RemoteException e) { 582 Log.wtf(LOG_TAG, "Communication error with registry", e); 583 // Fall through 584 } 585 } 586 mPreConnectedQueue.clear(); 587 } 588 } 589 break; 590 } 591 case EVENT_AGENT_DISCONNECTED: { 592 if (DBG) log("NetworkAgent channel lost"); 593 // let the client know CS is done with us. 594 onNetworkUnwanted(); 595 synchronized (mPreConnectedQueue) { 596 mRegistry = null; 597 } 598 break; 599 } 600 case CMD_SUSPECT_BAD: { 601 log("Unhandled Message " + msg); 602 break; 603 } 604 case CMD_REQUEST_BANDWIDTH_UPDATE: { 605 long currentTimeMs = System.currentTimeMillis(); 606 if (VDBG) { 607 log("CMD_REQUEST_BANDWIDTH_UPDATE request received."); 608 } 609 if (currentTimeMs >= (mLastBwRefreshTime + BW_REFRESH_MIN_WIN_MS)) { 610 mBandwidthUpdateScheduled = false; 611 if (!mBandwidthUpdatePending.getAndSet(true)) { 612 onBandwidthUpdateRequested(); 613 } 614 } else { 615 // deliver the request at a later time rather than discard it completely. 616 if (!mBandwidthUpdateScheduled) { 617 long waitTime = mLastBwRefreshTime + BW_REFRESH_MIN_WIN_MS 618 - currentTimeMs + 1; 619 mBandwidthUpdateScheduled = sendEmptyMessageDelayed( 620 CMD_REQUEST_BANDWIDTH_UPDATE, waitTime); 621 } 622 } 623 break; 624 } 625 case CMD_REPORT_NETWORK_STATUS: { 626 String redirectUrl = ((Bundle) msg.obj).getString(REDIRECT_URL_KEY); 627 if (VDBG) { 628 log("CMD_REPORT_NETWORK_STATUS(" 629 + (msg.arg1 == VALID_NETWORK ? "VALID, " : "INVALID, ") 630 + redirectUrl); 631 } 632 Uri uri = null; 633 try { 634 if (null != redirectUrl) { 635 uri = Uri.parse(redirectUrl); 636 } 637 } catch (Exception e) { 638 Log.wtf(LOG_TAG, "Surprising URI : " + redirectUrl, e); 639 } 640 onValidationStatus(msg.arg1 /* status */, uri); 641 break; 642 } 643 case CMD_SAVE_ACCEPT_UNVALIDATED: { 644 onSaveAcceptUnvalidated(msg.arg1 != 0); 645 break; 646 } 647 case CMD_START_SOCKET_KEEPALIVE: { 648 onStartSocketKeepalive(msg.arg1 /* slot */, 649 Duration.ofSeconds(msg.arg2) /* interval */, 650 (KeepalivePacketData) msg.obj /* packet */); 651 break; 652 } 653 case CMD_STOP_SOCKET_KEEPALIVE: { 654 onStopSocketKeepalive(msg.arg1 /* slot */); 655 break; 656 } 657 658 case CMD_SET_SIGNAL_STRENGTH_THRESHOLDS: { 659 onSignalStrengthThresholdsUpdated((int[]) msg.obj); 660 break; 661 } 662 case CMD_PREVENT_AUTOMATIC_RECONNECT: { 663 onAutomaticReconnectDisabled(); 664 break; 665 } 666 case CMD_ADD_KEEPALIVE_PACKET_FILTER: { 667 onAddKeepalivePacketFilter(msg.arg1 /* slot */, 668 (KeepalivePacketData) msg.obj /* packet */); 669 break; 670 } 671 case CMD_REMOVE_KEEPALIVE_PACKET_FILTER: { 672 onRemoveKeepalivePacketFilter(msg.arg1 /* slot */); 673 break; 674 } 675 case CMD_REGISTER_QOS_CALLBACK: { 676 onQosCallbackRegistered( 677 msg.arg1 /* QoS callback id */, 678 (QosFilter) msg.obj /* QoS filter */); 679 break; 680 } 681 case CMD_UNREGISTER_QOS_CALLBACK: { 682 onQosCallbackUnregistered( 683 msg.arg1 /* QoS callback id */); 684 break; 685 } 686 case CMD_NETWORK_CREATED: { 687 onNetworkCreated(); 688 break; 689 } 690 case CMD_NETWORK_DESTROYED: { 691 onNetworkDestroyed(); 692 break; 693 } 694 case CMD_DSCP_POLICY_STATUS: { 695 onDscpPolicyStatusUpdated( 696 msg.arg1 /* Policy ID */, 697 msg.arg2 /* DSCP Policy Status */); 698 break; 699 } 700 } 701 } 702 } 703 704 /** 705 * Register this network agent with ConnectivityService. 706 * 707 * This method can only be called once per network agent. 708 * 709 * @return the Network associated with this network agent (which can also be obtained later 710 * by calling getNetwork() on this agent). 711 * @throws IllegalStateException thrown by the system server if this network agent is 712 * already registered. 713 */ 714 @NonNull register()715 public Network register() { 716 if (VDBG) log("Registering NetworkAgent"); 717 synchronized (mRegisterLock) { 718 if (mNetwork != null) { 719 throw new IllegalStateException("Agent already registered"); 720 } 721 final ConnectivityManager cm = (ConnectivityManager) mInitialConfiguration.context 722 .getSystemService(Context.CONNECTIVITY_SERVICE); 723 mNetwork = cm.registerNetworkAgent(new NetworkAgentBinder(mHandler), 724 new NetworkInfo(mInitialConfiguration.info), 725 mInitialConfiguration.properties, mInitialConfiguration.capabilities, 726 mInitialConfiguration.score, mInitialConfiguration.config, providerId); 727 mInitialConfiguration = null; // All this memory can now be GC'd 728 } 729 return mNetwork; 730 } 731 732 private static class NetworkAgentBinder extends INetworkAgent.Stub { 733 private static final String LOG_TAG = NetworkAgentBinder.class.getSimpleName(); 734 735 private final Handler mHandler; 736 NetworkAgentBinder(Handler handler)737 private NetworkAgentBinder(Handler handler) { 738 mHandler = handler; 739 } 740 741 @Override onRegistered(@onNull INetworkAgentRegistry registry)742 public void onRegistered(@NonNull INetworkAgentRegistry registry) { 743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_CONNECTED, registry)); 744 } 745 746 @Override onDisconnected()747 public void onDisconnected() { 748 mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_DISCONNECTED)); 749 } 750 751 @Override onBandwidthUpdateRequested()752 public void onBandwidthUpdateRequested() { 753 mHandler.sendMessage(mHandler.obtainMessage(CMD_REQUEST_BANDWIDTH_UPDATE)); 754 } 755 756 @Override onValidationStatusChanged( int validationStatus, @Nullable String captivePortalUrl)757 public void onValidationStatusChanged( 758 int validationStatus, @Nullable String captivePortalUrl) { 759 // TODO: consider using a parcelable as argument when the interface is structured 760 Bundle redirectUrlBundle = new Bundle(); 761 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, captivePortalUrl); 762 mHandler.sendMessage(mHandler.obtainMessage(CMD_REPORT_NETWORK_STATUS, 763 validationStatus, 0, redirectUrlBundle)); 764 } 765 766 @Override onSaveAcceptUnvalidated(boolean acceptUnvalidated)767 public void onSaveAcceptUnvalidated(boolean acceptUnvalidated) { 768 mHandler.sendMessage(mHandler.obtainMessage(CMD_SAVE_ACCEPT_UNVALIDATED, 769 acceptUnvalidated ? 1 : 0, 0)); 770 } 771 772 @Override onStartNattSocketKeepalive(int slot, int intervalDurationMs, @NonNull NattKeepalivePacketData packetData)773 public void onStartNattSocketKeepalive(int slot, int intervalDurationMs, 774 @NonNull NattKeepalivePacketData packetData) { 775 mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE, 776 slot, intervalDurationMs, packetData)); 777 } 778 779 @Override onStartTcpSocketKeepalive(int slot, int intervalDurationMs, @NonNull TcpKeepalivePacketData packetData)780 public void onStartTcpSocketKeepalive(int slot, int intervalDurationMs, 781 @NonNull TcpKeepalivePacketData packetData) { 782 mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE, 783 slot, intervalDurationMs, packetData)); 784 } 785 786 @Override onStopSocketKeepalive(int slot)787 public void onStopSocketKeepalive(int slot) { 788 mHandler.sendMessage(mHandler.obtainMessage(CMD_STOP_SOCKET_KEEPALIVE, slot, 0)); 789 } 790 791 @Override onSignalStrengthThresholdsUpdated(@onNull int[] thresholds)792 public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) { 793 mHandler.sendMessage(mHandler.obtainMessage( 794 CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, thresholds)); 795 } 796 797 @Override onPreventAutomaticReconnect()798 public void onPreventAutomaticReconnect() { 799 mHandler.sendMessage(mHandler.obtainMessage(CMD_PREVENT_AUTOMATIC_RECONNECT)); 800 } 801 802 @Override onAddNattKeepalivePacketFilter(int slot, @NonNull NattKeepalivePacketData packetData)803 public void onAddNattKeepalivePacketFilter(int slot, 804 @NonNull NattKeepalivePacketData packetData) { 805 mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, 806 slot, 0, packetData)); 807 } 808 809 @Override onAddTcpKeepalivePacketFilter(int slot, @NonNull TcpKeepalivePacketData packetData)810 public void onAddTcpKeepalivePacketFilter(int slot, 811 @NonNull TcpKeepalivePacketData packetData) { 812 mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, 813 slot, 0, packetData)); 814 } 815 816 @Override onRemoveKeepalivePacketFilter(int slot)817 public void onRemoveKeepalivePacketFilter(int slot) { 818 mHandler.sendMessage(mHandler.obtainMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER, 819 slot, 0)); 820 } 821 822 @Override onQosFilterCallbackRegistered(final int qosCallbackId, final QosFilterParcelable qosFilterParcelable)823 public void onQosFilterCallbackRegistered(final int qosCallbackId, 824 final QosFilterParcelable qosFilterParcelable) { 825 if (qosFilterParcelable.getQosFilter() != null) { 826 mHandler.sendMessage( 827 mHandler.obtainMessage(CMD_REGISTER_QOS_CALLBACK, qosCallbackId, 0, 828 qosFilterParcelable.getQosFilter())); 829 return; 830 } 831 832 Log.wtf(LOG_TAG, "onQosFilterCallbackRegistered: qos filter is null."); 833 } 834 835 @Override onQosCallbackUnregistered(final int qosCallbackId)836 public void onQosCallbackUnregistered(final int qosCallbackId) { 837 mHandler.sendMessage(mHandler.obtainMessage( 838 CMD_UNREGISTER_QOS_CALLBACK, qosCallbackId, 0, null)); 839 } 840 841 @Override onNetworkCreated()842 public void onNetworkCreated() { 843 mHandler.sendMessage(mHandler.obtainMessage(CMD_NETWORK_CREATED)); 844 } 845 846 @Override onNetworkDestroyed()847 public void onNetworkDestroyed() { 848 mHandler.sendMessage(mHandler.obtainMessage(CMD_NETWORK_DESTROYED)); 849 } 850 851 @Override onDscpPolicyStatusUpdated(final int policyId, @DscpPolicyStatus final int status)852 public void onDscpPolicyStatusUpdated(final int policyId, 853 @DscpPolicyStatus final int status) { 854 mHandler.sendMessage(mHandler.obtainMessage( 855 CMD_DSCP_POLICY_STATUS, policyId, status)); 856 } 857 } 858 859 /** 860 * Register this network agent with a testing harness. 861 * 862 * The returned Messenger sends messages to the Handler. This allows a test to send 863 * this object {@code CMD_*} messages as if they came from ConnectivityService, which 864 * is useful for testing the behavior. 865 * 866 * @hide 867 */ registerForTest(final Network network)868 public INetworkAgent registerForTest(final Network network) { 869 log("Registering NetworkAgent for test"); 870 synchronized (mRegisterLock) { 871 mNetwork = network; 872 mInitialConfiguration = null; 873 } 874 return new NetworkAgentBinder(mHandler); 875 } 876 877 /** 878 * Waits for the handler to be idle. 879 * This is useful for testing, and has smaller scope than an accessor to mHandler. 880 * TODO : move the implementation in common library with the tests 881 * @hide 882 */ 883 @VisibleForTesting waitForIdle(final long timeoutMs)884 public boolean waitForIdle(final long timeoutMs) { 885 final ConditionVariable cv = new ConditionVariable(false); 886 mHandler.post(cv::open); 887 return cv.block(timeoutMs); 888 } 889 890 /** 891 * @return The Network associated with this agent, or null if it's not registered yet. 892 */ 893 @Nullable getNetwork()894 public Network getNetwork() { 895 return mNetwork; 896 } 897 queueOrSendMessage(@onNull RegistryAction action)898 private void queueOrSendMessage(@NonNull RegistryAction action) { 899 synchronized (mPreConnectedQueue) { 900 if (mRegistry != null) { 901 try { 902 action.execute(mRegistry); 903 } catch (RemoteException e) { 904 Log.wtf(LOG_TAG, "Error executing registry action", e); 905 // Fall through: the channel is asynchronous and does not report errors back 906 } 907 } else { 908 mPreConnectedQueue.add(action); 909 } 910 } 911 } 912 913 /** 914 * Must be called by the agent when the network's {@link LinkProperties} change. 915 * @param linkProperties the new LinkProperties. 916 */ sendLinkProperties(@onNull LinkProperties linkProperties)917 public void sendLinkProperties(@NonNull LinkProperties linkProperties) { 918 Objects.requireNonNull(linkProperties); 919 final LinkProperties lp = new LinkProperties(linkProperties); 920 queueOrSendMessage(reg -> reg.sendLinkProperties(lp)); 921 } 922 923 /** 924 * Must be called by the agent when the network's underlying networks change. 925 * 926 * <p>{@code networks} is one of the following: 927 * <ul> 928 * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in 929 * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular) 930 * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear 931 * first in the array.</li> 932 * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no 933 * underlying network connection, and thus, app traffic will not be sent or received.</li> 934 * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's 935 * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket} 936 * APIs mentioned above to send traffic over specific channels.</li> 937 * </ul> 938 * 939 * @param underlyingNetworks the new list of underlying networks. 940 * @see {@link VpnService.Builder#setUnderlyingNetworks(Network[])} 941 */ setUnderlyingNetworks( @uppressLint"NullableCollection") @ullable List<Network> underlyingNetworks)942 public void setUnderlyingNetworks( 943 @SuppressLint("NullableCollection") @Nullable List<Network> underlyingNetworks) { 944 final ArrayList<Network> underlyingArray = (underlyingNetworks != null) 945 ? new ArrayList<>(underlyingNetworks) : null; 946 queueOrSendMessage(reg -> reg.sendUnderlyingNetworks(underlyingArray)); 947 } 948 949 /** 950 * Inform ConnectivityService that this agent has now connected. 951 * Call {@link #unregister} to disconnect. 952 */ markConnected()953 public void markConnected() { 954 mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null /* reason */, 955 mNetworkInfo.getExtraInfo()); 956 queueOrSendNetworkInfo(mNetworkInfo); 957 } 958 959 /** 960 * Unregister this network agent. 961 * 962 * This signals the network has disconnected and ends its lifecycle. After this is called, 963 * the network is torn down and this agent can no longer be used. 964 */ unregister()965 public void unregister() { 966 // When unregistering an agent nobody should use the extrainfo (or reason) any more. 967 mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null /* reason */, 968 null /* extraInfo */); 969 queueOrSendNetworkInfo(mNetworkInfo); 970 } 971 972 /** 973 * Sets the value of the teardown delay. 974 * 975 * The teardown delay is the time between when the network disconnects and when the native 976 * network corresponding to this {@code NetworkAgent} is destroyed. By default, the native 977 * network is destroyed immediately. If {@code teardownDelayMs} is non-zero, then when this 978 * network disconnects, the system will instead immediately mark the network as restricted 979 * and unavailable to unprivileged apps, but will defer destroying the native network until the 980 * teardown delay timer expires. 981 * 982 * The interfaces in use by this network will remain in use until the native network is 983 * destroyed and cannot be reused until {@link #onNetworkDestroyed()} is called. 984 * 985 * This method may be called at any time while the network is connected. It has no effect if 986 * the network is already disconnected and the teardown delay timer is running. 987 * 988 * @param teardownDelayMillis the teardown delay to set, or 0 to disable teardown delay. 989 */ setTeardownDelayMillis( @ntRangefrom = 0, to = MAX_TEARDOWN_DELAY_MS) int teardownDelayMillis)990 public void setTeardownDelayMillis( 991 @IntRange(from = 0, to = MAX_TEARDOWN_DELAY_MS) int teardownDelayMillis) { 992 queueOrSendMessage(reg -> reg.sendTeardownDelayMs(teardownDelayMillis)); 993 } 994 995 /** 996 * Indicates that this agent will likely soon be replaced by another agent for a very similar 997 * network (e.g., same Wi-Fi SSID). 998 * 999 * If the network is not currently satisfying any {@link NetworkRequest}s, it will be torn down. 1000 * If it is satisfying requests, then the native network corresponding to the agent will be 1001 * destroyed immediately, but the agent will remain registered and will continue to satisfy 1002 * requests until {@link #unregister} is called, the network is replaced by an equivalent or 1003 * better network, or the specified timeout expires. During this time: 1004 * 1005 * <ul> 1006 * <li>The agent may not send any further updates, for example by calling methods 1007 * such as {@link #sendNetworkCapabilities}, {@link #sendLinkProperties}, 1008 * {@link #sendNetworkScore(NetworkScore)} and so on. Any such updates will be ignored. 1009 * <li>The network will remain connected and continue to satisfy any requests that it would 1010 * otherwise satisfy (including, possibly, the default request). 1011 * <li>The validation state of the network will not change, and calls to 1012 * {@link ConnectivityManager#reportNetworkConnectivity(Network, boolean)} will be ignored. 1013 * </ul> 1014 * 1015 * Once this method is called, it is not possible to restore the agent to a functioning state. 1016 * If a replacement network becomes available, then a new agent must be registered. When that 1017 * replacement network is fully capable of replacing this network (including, possibly, being 1018 * validated), this agent will no longer be needed and will be torn down. Otherwise, this agent 1019 * can be disconnected by calling {@link #unregister}. If {@link #unregister} is not called, 1020 * this agent will automatically be unregistered when the specified timeout expires. Any 1021 * teardown delay previously set using{@link #setTeardownDelayMillis} is ignored. 1022 * 1023 * <p>This method has no effect if {@link #markConnected} has not yet been called. 1024 * <p>This method may only be called once. 1025 * 1026 * @param timeoutMillis the timeout after which this network will be unregistered even if 1027 * {@link #unregister} was not called. 1028 */ unregisterAfterReplacement( @ntRangefrom = 0, to = MAX_TEARDOWN_DELAY_MS) int timeoutMillis)1029 public void unregisterAfterReplacement( 1030 @IntRange(from = 0, to = MAX_TEARDOWN_DELAY_MS) int timeoutMillis) { 1031 queueOrSendMessage(reg -> reg.sendUnregisterAfterReplacement(timeoutMillis)); 1032 } 1033 1034 /** 1035 * Change the legacy subtype of this network agent. 1036 * 1037 * This is only for backward compatibility and should not be used by non-legacy network agents, 1038 * or agents that did not use to set a subtype. As such, only TYPE_MOBILE type agents can use 1039 * this and others will be thrown an exception if they try. 1040 * 1041 * @deprecated this is for backward compatibility only. 1042 * @param legacySubtype the legacy subtype. 1043 * @hide 1044 */ 1045 @Deprecated 1046 @SystemApi setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName)1047 public void setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName) { 1048 mNetworkInfo.setSubtype(legacySubtype, legacySubtypeName); 1049 queueOrSendNetworkInfo(mNetworkInfo); 1050 } 1051 1052 /** 1053 * Set the ExtraInfo of this network agent. 1054 * 1055 * This sets the ExtraInfo field inside the NetworkInfo returned by legacy public API and the 1056 * broadcasts about the corresponding Network. 1057 * This is only for backward compatibility and should not be used by non-legacy network agents, 1058 * who will be thrown an exception if they try. The extra info should only be : 1059 * <ul> 1060 * <li>For cellular agents, the APN name.</li> 1061 * <li>For ethernet agents, the interface name.</li> 1062 * </ul> 1063 * 1064 * @deprecated this is for backward compatibility only. 1065 * @param extraInfo the ExtraInfo. 1066 * @hide 1067 */ 1068 @Deprecated setLegacyExtraInfo(@ullable final String extraInfo)1069 public void setLegacyExtraInfo(@Nullable final String extraInfo) { 1070 mNetworkInfo.setExtraInfo(extraInfo); 1071 queueOrSendNetworkInfo(mNetworkInfo); 1072 } 1073 1074 /** 1075 * Must be called by the agent when it has a new NetworkInfo object. 1076 * @hide TODO: expose something better. 1077 */ 1078 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) sendNetworkInfo(NetworkInfo networkInfo)1079 public final void sendNetworkInfo(NetworkInfo networkInfo) { 1080 queueOrSendNetworkInfo(networkInfo); 1081 } 1082 queueOrSendNetworkInfo(NetworkInfo networkInfo)1083 private void queueOrSendNetworkInfo(NetworkInfo networkInfo) { 1084 final NetworkInfo ni = new NetworkInfo(networkInfo); 1085 queueOrSendMessage(reg -> reg.sendNetworkInfo(ni)); 1086 } 1087 1088 /** 1089 * Must be called by the agent when the network's {@link NetworkCapabilities} change. 1090 * @param networkCapabilities the new NetworkCapabilities. 1091 */ sendNetworkCapabilities(@onNull NetworkCapabilities networkCapabilities)1092 public void sendNetworkCapabilities(@NonNull NetworkCapabilities networkCapabilities) { 1093 Objects.requireNonNull(networkCapabilities); 1094 mBandwidthUpdatePending.set(false); 1095 mLastBwRefreshTime = System.currentTimeMillis(); 1096 final NetworkCapabilities nc = 1097 new NetworkCapabilities(networkCapabilities, NetworkCapabilities.REDACT_NONE); 1098 queueOrSendMessage(reg -> reg.sendNetworkCapabilities(nc)); 1099 } 1100 1101 /** 1102 * Must be called by the agent to update the score of this network. 1103 * 1104 * @param score the new score. 1105 */ sendNetworkScore(@onNull NetworkScore score)1106 public void sendNetworkScore(@NonNull NetworkScore score) { 1107 Objects.requireNonNull(score); 1108 queueOrSendMessage(reg -> reg.sendScore(score)); 1109 } 1110 1111 /** 1112 * Must be called by the agent to update the score of this network. 1113 * 1114 * @param score the new score, between 0 and 99. 1115 * deprecated use sendNetworkScore(NetworkScore) TODO : remove in S. 1116 */ sendNetworkScore(@ntRangefrom = 0, to = 99) int score)1117 public void sendNetworkScore(@IntRange(from = 0, to = 99) int score) { 1118 sendNetworkScore(new NetworkScore.Builder().setLegacyInt(score).build()); 1119 } 1120 1121 /** 1122 * Must be called by the agent to indicate this network was manually selected by the user. 1123 * This should be called before the NetworkInfo is marked CONNECTED so that this 1124 * Network can be given special treatment at that time. If {@code acceptUnvalidated} is 1125 * {@code true}, then the system will switch to this network. If it is {@code false} and the 1126 * network cannot be validated, the system will ask the user whether to switch to this network. 1127 * If the user confirms and selects "don't ask again", then the system will call 1128 * {@link #saveAcceptUnvalidated} to persist the user's choice. Thus, if the transport ever 1129 * calls this method with {@code acceptUnvalidated} set to {@code false}, it must also implement 1130 * {@link #saveAcceptUnvalidated} to respect the user's choice. 1131 * @hide should move to NetworkAgentConfig. 1132 */ explicitlySelected(boolean acceptUnvalidated)1133 public void explicitlySelected(boolean acceptUnvalidated) { 1134 explicitlySelected(true /* explicitlySelected */, acceptUnvalidated); 1135 } 1136 1137 /** 1138 * Must be called by the agent to indicate whether the network was manually selected by the 1139 * user. This should be called before the network becomes connected, so it can be given 1140 * special treatment when it does. 1141 * 1142 * If {@code explicitlySelected} is {@code true}, and {@code acceptUnvalidated} is {@code true}, 1143 * then the system will switch to this network. If {@code explicitlySelected} is {@code true} 1144 * and {@code acceptUnvalidated} is {@code false}, and the network cannot be validated, the 1145 * system will ask the user whether to switch to this network. If the user confirms and selects 1146 * "don't ask again", then the system will call {@link #saveAcceptUnvalidated} to persist the 1147 * user's choice. Thus, if the transport ever calls this method with {@code explicitlySelected} 1148 * set to {@code true} and {@code acceptUnvalidated} set to {@code false}, it must also 1149 * implement {@link #saveAcceptUnvalidated} to respect the user's choice. 1150 * 1151 * If {@code explicitlySelected} is {@code false} and {@code acceptUnvalidated} is 1152 * {@code true}, the system will interpret this as the user having accepted partial connectivity 1153 * on this network. Thus, the system will switch to the network and consider it validated even 1154 * if it only provides partial connectivity, but the network is not otherwise treated specially. 1155 * @hide should move to NetworkAgentConfig. 1156 */ explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated)1157 public void explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated) { 1158 queueOrSendMessage(reg -> reg.sendExplicitlySelected( 1159 explicitlySelected, acceptUnvalidated)); 1160 } 1161 1162 /** 1163 * Called when ConnectivityService has indicated they no longer want this network. 1164 * The parent factory should (previously) have received indication of the change 1165 * as well, either canceling NetworkRequests or altering their score such that this 1166 * network won't be immediately requested again. 1167 */ onNetworkUnwanted()1168 public void onNetworkUnwanted() { 1169 unwanted(); 1170 } 1171 /** @hide TODO delete once subclasses have moved to onNetworkUnwanted. */ unwanted()1172 protected void unwanted() { 1173 } 1174 1175 /** 1176 * Called when ConnectivityService request a bandwidth update. The parent factory 1177 * shall try to overwrite this method and produce a bandwidth update if capable. 1178 * @hide 1179 */ 1180 @SystemApi onBandwidthUpdateRequested()1181 public void onBandwidthUpdateRequested() { 1182 pollLceData(); 1183 } 1184 /** @hide TODO delete once subclasses have moved to onBandwidthUpdateRequested. */ pollLceData()1185 protected void pollLceData() { 1186 } 1187 1188 /** 1189 * Called when the system determines the usefulness of this network. 1190 * 1191 * The system attempts to validate Internet connectivity on networks that provide the 1192 * {@link NetworkCapabilities#NET_CAPABILITY_INTERNET} capability. 1193 * 1194 * Currently there are two possible values: 1195 * {@code VALIDATION_STATUS_VALID} if Internet connectivity was validated, 1196 * {@code VALIDATION_STATUS_NOT_VALID} if Internet connectivity was not validated. 1197 * 1198 * This is guaranteed to be called again when the network status changes, but the system 1199 * may also call this multiple times even if the status does not change. 1200 * 1201 * @param status one of {@code VALIDATION_STATUS_VALID} or {@code VALIDATION_STATUS_NOT_VALID}. 1202 * @param redirectUri If Internet connectivity is being redirected (e.g., on a captive portal), 1203 * this is the destination the probes are being redirected to, otherwise {@code null}. 1204 */ onValidationStatus(@alidationStatus int status, @Nullable Uri redirectUri)1205 public void onValidationStatus(@ValidationStatus int status, @Nullable Uri redirectUri) { 1206 networkStatus(status, null == redirectUri ? "" : redirectUri.toString()); 1207 } 1208 /** @hide TODO delete once subclasses have moved to onValidationStatus */ networkStatus(int status, String redirectUrl)1209 protected void networkStatus(int status, String redirectUrl) { 1210 } 1211 1212 1213 /** 1214 * Called when the user asks to remember the choice to use this network even if unvalidated. 1215 * The transport is responsible for remembering the choice, and the next time the user connects 1216 * to the network, should explicitlySelected with {@code acceptUnvalidated} set to {@code true}. 1217 * This method will only be called if {@link #explicitlySelected} was called with 1218 * {@code acceptUnvalidated} set to {@code false}. 1219 * @param accept whether the user wants to use the network even if unvalidated. 1220 */ onSaveAcceptUnvalidated(boolean accept)1221 public void onSaveAcceptUnvalidated(boolean accept) { 1222 saveAcceptUnvalidated(accept); 1223 } 1224 /** @hide TODO delete once subclasses have moved to onSaveAcceptUnvalidated */ saveAcceptUnvalidated(boolean accept)1225 protected void saveAcceptUnvalidated(boolean accept) { 1226 } 1227 1228 /** 1229 * Called when ConnectivityService has successfully created this NetworkAgent's native network. 1230 */ onNetworkCreated()1231 public void onNetworkCreated() {} 1232 1233 1234 /** 1235 * Called when ConnectivityService has successfully destroy this NetworkAgent's native network. 1236 */ onNetworkDestroyed()1237 public void onNetworkDestroyed() {} 1238 1239 /** 1240 * Called when when the DSCP Policy status has changed. 1241 */ onDscpPolicyStatusUpdated(int policyId, @DscpPolicyStatus int status)1242 public void onDscpPolicyStatusUpdated(int policyId, @DscpPolicyStatus int status) {} 1243 1244 /** 1245 * Requests that the network hardware send the specified packet at the specified interval. 1246 * 1247 * @param slot the hardware slot on which to start the keepalive. 1248 * @param interval the interval between packets, between 10 and 3600. Note that this API 1249 * does not support sub-second precision and will round off the request. 1250 * @param packet the packet to send. 1251 */ 1252 // seconds is from SocketKeepalive.MIN_INTERVAL_SEC to MAX_INTERVAL_SEC, but these should 1253 // not be exposed as constants because they may change in the future (API guideline 4.8) 1254 // and should have getters if exposed at all. Getters can't be used in the annotation, 1255 // so the values unfortunately need to be copied. onStartSocketKeepalive(int slot, @NonNull Duration interval, @NonNull KeepalivePacketData packet)1256 public void onStartSocketKeepalive(int slot, @NonNull Duration interval, 1257 @NonNull KeepalivePacketData packet) { 1258 final long intervalSeconds = interval.getSeconds(); 1259 if (intervalSeconds < SocketKeepalive.MIN_INTERVAL_SEC 1260 || intervalSeconds > SocketKeepalive.MAX_INTERVAL_SEC) { 1261 throw new IllegalArgumentException("Interval needs to be comprised between " 1262 + SocketKeepalive.MIN_INTERVAL_SEC + " and " + SocketKeepalive.MAX_INTERVAL_SEC 1263 + " but was " + intervalSeconds); 1264 } 1265 final Message msg = mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE, slot, 1266 (int) intervalSeconds, packet); 1267 startSocketKeepalive(msg); 1268 msg.recycle(); 1269 } 1270 /** @hide TODO delete once subclasses have moved to onStartSocketKeepalive */ startSocketKeepalive(Message msg)1271 protected void startSocketKeepalive(Message msg) { 1272 onSocketKeepaliveEvent(msg.arg1, SocketKeepalive.ERROR_UNSUPPORTED); 1273 } 1274 1275 /** 1276 * Requests that the network hardware stop a previously-started keepalive. 1277 * 1278 * @param slot the hardware slot on which to stop the keepalive. 1279 */ onStopSocketKeepalive(int slot)1280 public void onStopSocketKeepalive(int slot) { 1281 Message msg = mHandler.obtainMessage(CMD_STOP_SOCKET_KEEPALIVE, slot, 0, null); 1282 stopSocketKeepalive(msg); 1283 msg.recycle(); 1284 } 1285 /** @hide TODO delete once subclasses have moved to onStopSocketKeepalive */ stopSocketKeepalive(Message msg)1286 protected void stopSocketKeepalive(Message msg) { 1287 onSocketKeepaliveEvent(msg.arg1, SocketKeepalive.ERROR_UNSUPPORTED); 1288 } 1289 1290 /** 1291 * Must be called by the agent when a socket keepalive event occurs. 1292 * 1293 * @param slot the hardware slot on which the event occurred. 1294 * @param event the event that occurred, as one of the SocketKeepalive.ERROR_* 1295 * or SocketKeepalive.SUCCESS constants. 1296 */ sendSocketKeepaliveEvent(int slot, @SocketKeepalive.KeepaliveEvent int event)1297 public final void sendSocketKeepaliveEvent(int slot, 1298 @SocketKeepalive.KeepaliveEvent int event) { 1299 queueOrSendMessage(reg -> reg.sendSocketKeepaliveEvent(slot, event)); 1300 } 1301 /** @hide TODO delete once callers have moved to sendSocketKeepaliveEvent */ onSocketKeepaliveEvent(int slot, int reason)1302 public void onSocketKeepaliveEvent(int slot, int reason) { 1303 sendSocketKeepaliveEvent(slot, reason); 1304 } 1305 1306 /** 1307 * Called by ConnectivityService to add specific packet filter to network hardware to block 1308 * replies (e.g., TCP ACKs) matching the sent keepalive packets. Implementations that support 1309 * this feature must override this method. 1310 * 1311 * @param slot the hardware slot on which the keepalive should be sent. 1312 * @param packet the packet that is being sent. 1313 */ onAddKeepalivePacketFilter(int slot, @NonNull KeepalivePacketData packet)1314 public void onAddKeepalivePacketFilter(int slot, @NonNull KeepalivePacketData packet) { 1315 Message msg = mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0, packet); 1316 addKeepalivePacketFilter(msg); 1317 msg.recycle(); 1318 } 1319 /** @hide TODO delete once subclasses have moved to onAddKeepalivePacketFilter */ addKeepalivePacketFilter(Message msg)1320 protected void addKeepalivePacketFilter(Message msg) { 1321 } 1322 1323 /** 1324 * Called by ConnectivityService to remove a packet filter installed with 1325 * {@link #addKeepalivePacketFilter(Message)}. Implementations that support this feature 1326 * must override this method. 1327 * 1328 * @param slot the hardware slot on which the keepalive is being sent. 1329 */ onRemoveKeepalivePacketFilter(int slot)1330 public void onRemoveKeepalivePacketFilter(int slot) { 1331 Message msg = mHandler.obtainMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER, slot, 0, null); 1332 removeKeepalivePacketFilter(msg); 1333 msg.recycle(); 1334 } 1335 /** @hide TODO delete once subclasses have moved to onRemoveKeepalivePacketFilter */ removeKeepalivePacketFilter(Message msg)1336 protected void removeKeepalivePacketFilter(Message msg) { 1337 } 1338 1339 /** 1340 * Called by ConnectivityService to inform this network agent of signal strength thresholds 1341 * that when crossed should trigger a system wakeup and a NetworkCapabilities update. 1342 * 1343 * When the system updates the list of thresholds that should wake up the CPU for a 1344 * given agent it will call this method on the agent. The agent that implement this 1345 * should implement it in hardware so as to ensure the CPU will be woken up on breach. 1346 * Agents are expected to react to a breach by sending an updated NetworkCapabilities 1347 * object with the appropriate signal strength to sendNetworkCapabilities. 1348 * 1349 * The specific units are bearer-dependent. See details on the units and requests in 1350 * {@link NetworkCapabilities.Builder#setSignalStrength}. 1351 * 1352 * @param thresholds the array of thresholds that should trigger wakeups. 1353 */ onSignalStrengthThresholdsUpdated(@onNull int[] thresholds)1354 public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) { 1355 setSignalStrengthThresholds(thresholds); 1356 } 1357 /** @hide TODO delete once subclasses have moved to onSetSignalStrengthThresholds */ setSignalStrengthThresholds(int[] thresholds)1358 protected void setSignalStrengthThresholds(int[] thresholds) { 1359 } 1360 1361 /** 1362 * Called when the user asks to not stay connected to this network because it was found to not 1363 * provide Internet access. Usually followed by call to {@code unwanted}. The transport is 1364 * responsible for making sure the device does not automatically reconnect to the same network 1365 * after the {@code unwanted} call. 1366 */ onAutomaticReconnectDisabled()1367 public void onAutomaticReconnectDisabled() { 1368 preventAutomaticReconnect(); 1369 } 1370 /** @hide TODO delete once subclasses have moved to onAutomaticReconnectDisabled */ preventAutomaticReconnect()1371 protected void preventAutomaticReconnect() { 1372 } 1373 1374 /** 1375 * Called when a qos callback is registered with a filter. 1376 * @param qosCallbackId the id for the callback registered 1377 * @param filter the filter being registered 1378 */ onQosCallbackRegistered(final int qosCallbackId, final @NonNull QosFilter filter)1379 public void onQosCallbackRegistered(final int qosCallbackId, final @NonNull QosFilter filter) { 1380 } 1381 1382 /** 1383 * Called when a qos callback is registered with a filter. 1384 * <p/> 1385 * Any QoS events that are sent with the same callback id after this method is called 1386 * are a no-op. 1387 * 1388 * @param qosCallbackId the id for the callback being unregistered 1389 */ onQosCallbackUnregistered(final int qosCallbackId)1390 public void onQosCallbackUnregistered(final int qosCallbackId) { 1391 } 1392 1393 1394 /** 1395 * Sends the attributes of Qos Session back to the Application 1396 * 1397 * @param qosCallbackId the callback id that the session belongs to 1398 * @param sessionId the unique session id across all Qos Sessions 1399 * @param attributes the attributes of the Qos Session 1400 */ sendQosSessionAvailable(final int qosCallbackId, final int sessionId, @NonNull final QosSessionAttributes attributes)1401 public final void sendQosSessionAvailable(final int qosCallbackId, final int sessionId, 1402 @NonNull final QosSessionAttributes attributes) { 1403 Objects.requireNonNull(attributes, "The attributes must be non-null"); 1404 if (attributes instanceof EpsBearerQosSessionAttributes) { 1405 queueOrSendMessage(ra -> ra.sendEpsQosSessionAvailable(qosCallbackId, 1406 new QosSession(sessionId, QosSession.TYPE_EPS_BEARER), 1407 (EpsBearerQosSessionAttributes)attributes)); 1408 } else if (attributes instanceof NrQosSessionAttributes) { 1409 queueOrSendMessage(ra -> ra.sendNrQosSessionAvailable(qosCallbackId, 1410 new QosSession(sessionId, QosSession.TYPE_NR_BEARER), 1411 (NrQosSessionAttributes)attributes)); 1412 } 1413 } 1414 1415 /** 1416 * Sends event that the Qos Session was lost. 1417 * 1418 * @param qosCallbackId the callback id that the session belongs to 1419 * @param sessionId the unique session id across all Qos Sessions 1420 * @param qosSessionType the session type {@code QosSesson#QosSessionType} 1421 */ sendQosSessionLost(final int qosCallbackId, final int sessionId, final int qosSessionType)1422 public final void sendQosSessionLost(final int qosCallbackId, 1423 final int sessionId, final int qosSessionType) { 1424 queueOrSendMessage(ra -> ra.sendQosSessionLost(qosCallbackId, 1425 new QosSession(sessionId, qosSessionType))); 1426 } 1427 1428 /** 1429 * Sends the exception type back to the application. 1430 * 1431 * The NetworkAgent should not send anymore messages with this id. 1432 * 1433 * @param qosCallbackId the callback id this exception belongs to 1434 * @param exceptionType the type of exception 1435 */ sendQosCallbackError(final int qosCallbackId, @QosCallbackException.ExceptionType final int exceptionType)1436 public final void sendQosCallbackError(final int qosCallbackId, 1437 @QosCallbackException.ExceptionType final int exceptionType) { 1438 queueOrSendMessage(ra -> ra.sendQosCallbackError(qosCallbackId, exceptionType)); 1439 } 1440 1441 /** 1442 * Set the linger duration for this network agent. 1443 * @param duration the delay between the moment the network becomes unneeded and the 1444 * moment the network is disconnected or moved into the background. 1445 * Note that If this duration has greater than millisecond precision, then 1446 * the internal implementation will drop any excess precision. 1447 */ setLingerDuration(@onNull final Duration duration)1448 public void setLingerDuration(@NonNull final Duration duration) { 1449 Objects.requireNonNull(duration); 1450 final long durationMs = duration.toMillis(); 1451 if (durationMs < MIN_LINGER_TIMER_MS || durationMs > Integer.MAX_VALUE) { 1452 throw new IllegalArgumentException("Duration must be within [" 1453 + MIN_LINGER_TIMER_MS + "," + Integer.MAX_VALUE + "]ms"); 1454 } 1455 queueOrSendMessage(ra -> ra.sendLingerDuration((int) durationMs)); 1456 } 1457 1458 /** 1459 * Add a DSCP Policy. 1460 * @param policy the DSCP policy to be added. 1461 */ sendAddDscpPolicy(@onNull final DscpPolicy policy)1462 public void sendAddDscpPolicy(@NonNull final DscpPolicy policy) { 1463 Objects.requireNonNull(policy); 1464 queueOrSendMessage(ra -> ra.sendAddDscpPolicy(policy)); 1465 } 1466 1467 /** 1468 * Remove the specified DSCP policy. 1469 * @param policyId the ID corresponding to a specific DSCP Policy. 1470 */ sendRemoveDscpPolicy(final int policyId)1471 public void sendRemoveDscpPolicy(final int policyId) { 1472 queueOrSendMessage(ra -> ra.sendRemoveDscpPolicy(policyId)); 1473 } 1474 1475 /** 1476 * Remove all the DSCP policies on this network. 1477 */ sendRemoveAllDscpPolicies()1478 public void sendRemoveAllDscpPolicies() { 1479 queueOrSendMessage(ra -> ra.sendRemoveAllDscpPolicies()); 1480 } 1481 1482 /** @hide */ log(final String s)1483 protected void log(final String s) { 1484 Log.d(LOG_TAG, "NetworkAgent: " + s); 1485 } 1486 } 1487