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 static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL; 20 import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN; 21 import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND; 22 import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; 23 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED; 24 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED; 25 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; 26 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; 27 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING; 28 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED; 29 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED; 30 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN; 31 import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY; 32 import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED; 33 import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED; 34 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; 35 import static android.net.NetworkCapabilities.RES_ID_UNSET; 36 import static android.net.NetworkCapabilities.TRANSPORT_TEST; 37 38 import android.annotation.FlaggedApi; 39 import android.annotation.NonNull; 40 import android.annotation.Nullable; 41 import android.annotation.RequiresPermission; 42 import android.annotation.SuppressLint; 43 import android.annotation.SystemApi; 44 import android.compat.annotation.UnsupportedAppUsage; 45 import android.net.NetworkCapabilities.NetCapability; 46 import android.net.NetworkCapabilities.Transport; 47 import android.os.Build; 48 import android.os.Parcel; 49 import android.os.Parcelable; 50 import android.os.Process; 51 import android.text.TextUtils; 52 import android.util.Range; 53 54 import com.android.net.flags.Flags; 55 56 import java.util.Arrays; 57 import java.util.List; 58 import java.util.Objects; 59 import java.util.Set; 60 61 /** 62 * An object describing a network that the application is interested in. 63 * 64 * <p>@see <a href="https://developer.android.com/training/basics/network-ops/reading-network-state> 65 * this general guide</a> on how to use NetworkCapabilities and related classes. 66 * 67 * NetworkRequest defines a request for a network, made through 68 * {@link NetworkRequest.Builder} and used to request a network via 69 * {@link ConnectivityManager#requestNetwork} or to listen for changes 70 * via the {@link ConnectivityManager#registerNetworkCallback} family of 71 * functions. 72 * 73 * <p>{@link ConnectivityManager#requestNetwork} will try to find a connected 74 * network matching the NetworkRequest, and return it if there is one. 75 * As long as the request is outstanding, the system will try to find the best 76 * possible network that matches the request. The request will keep up the 77 * currently best connected network, and if a better one is found (e.g. cheaper 78 * or faster) the system will bring up that better network to better serve the 79 * request. A request filed with {@link ConnectivityManager#requestNetwork} will 80 * only match one network at a time (the one the system thinks is best), even if 81 * other networks can match the request that are being kept up by other requests. 82 * 83 * For example, an application needing a network with 84 * {@link NetworkCapabilities#NET_CAPABILITY_INTERNET} should use 85 * {@link ConnectivityManager#requestNetwork} to request the system keeps one up. 86 * A general cellular network can satisfy this request, but if the system finds 87 * a free Wi-Fi network which is expected to be faster, it will try and connect 88 * to that Wi-Fi network and switch the request over to it once it is connected. 89 * The cell network may stay connected if there are outstanding requests (from 90 * the same app or from other apps on the system) that match the cell network 91 * but not the Wi-Fi network, such as a request with {@link NetworkCapabilities#NET_CAPABILITY_MMS}. 92 * 93 * When a network is no longer needed to serve any request, the system can 94 * tear it down at any time and usually does so immediately, so make sure to 95 * keep up requests for the networks your app needs. 96 * 97 * <p>By contrast, requests filed with {@link ConnectivityManager#registerNetworkCallback} 98 * will receive callbacks for all matching networks, and will not cause the system to 99 * keep up the networks they match. Use this to listen to networks that the device is 100 * connected to, but that you don't want the system to keep up for your use case. 101 * 102 * <p>Applications build a NetworkRequest and pass it to one of the 103 * {@link ConnectivityManager} methods above together with a 104 * {@link ConnectivityManager.NetworkCallback} object. The callback 105 * will then start receiving method calls about networks that match 106 * the request. 107 * 108 * <p>Networks are brought up and/or matched according to the capabilities 109 * set in the builder. For example, a request with 110 * {@link NetworkCapabilities#NET_CAPABILITY_MMS} lets the system match 111 * and/or bring up a network that is capable to send MMS. A request with 112 * {@link NetworkCapabilities#NET_CAPABILITY_NOT_METERED} matches a network 113 * that doesn't charge the user for usage. See 114 * {@link NetworkCapabilities} for a list of capabilities and their 115 * description. 116 * 117 * <p>While all capabilities can be matched with the 118 * {@link ConnectivityManager#registerNetworkCallback} family of methods, 119 * not all capabilities can be used to request that the system brings 120 * up a network with {@link ConnectivityManager#requestNetwork}. For example, 121 * an application cannot use {@link ConnectivityManager#requestNetwork} to 122 * ask the system to bring up a network with 123 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}, because the 124 * system won't know if a network has a captive portal before it connects 125 * to that network. Similarly, some capabilities may require a specific 126 * permission or privilege to be requested. 127 * 128 * Look up the specific capability and the {@link ConnectivityManager#requestNetwork} 129 * method for limitations applicable to each capability. 130 * 131 * <p>Also, starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, some capabilities 132 * require the application to self-certify by explicitly adding the 133 * {@link android.content.pm.PackageManager#PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES} 134 * property in the AndroidManifest.xml, which points to an XML resource file. In the 135 * XML resource file, the application declares what kind of network capabilities the application 136 * wants to have. 137 * 138 * Here is an example self-certification XML resource file : 139 * <pre> 140 * {@code 141 * <network-capabilities-declaration xmlns:android="http://schemas.android.com/apk/res/android"> 142 * <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_LATENCY"/> 143 * <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_BANDWIDTH"/> 144 * </network-capabilities-declaration> 145 * } 146 * </pre> 147 * Look up the specific capability to learn whether its usage requires this self-certification. 148 */ 149 public class NetworkRequest implements Parcelable { 150 /** 151 * The first requestId value that will be allocated. 152 * @hide only used by ConnectivityService. 153 */ 154 public static final int FIRST_REQUEST_ID = 1; 155 156 /** 157 * The requestId value that represents the absence of a request. 158 * @hide only used by ConnectivityService. 159 */ 160 public static final int REQUEST_ID_NONE = -1; 161 162 /** 163 * The {@link NetworkCapabilities} that define this request. 164 * @hide 165 */ 166 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 167 public final @NonNull NetworkCapabilities networkCapabilities; 168 169 /** 170 * Identifies the request. NetworkRequests should only be constructed by 171 * the Framework and given out to applications as tokens to be used to identify 172 * the request. 173 * @hide 174 */ 175 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 176 public final int requestId; 177 178 /** 179 * Set for legacy requests and the default. Set to TYPE_NONE for none. 180 * Causes CONNECTIVITY_ACTION broadcasts to be sent. 181 * @hide 182 */ 183 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 184 public final int legacyType; 185 186 /** 187 * A NetworkRequest as used by the system can be one of the following types: 188 * 189 * - LISTEN, for which the framework will issue callbacks about any 190 * and all networks that match the specified NetworkCapabilities, 191 * 192 * - REQUEST, capable of causing a specific network to be created 193 * first (e.g. a telephony DUN request), the framework will issue 194 * callbacks about the single, highest scoring current network 195 * (if any) that matches the specified NetworkCapabilities, or 196 * 197 * - RESERVATION requests behave identically to those of type REQUEST. 198 * For example, unlike LISTEN, they cause networks to remain 199 * connected, and they match exactly one network (the best one). 200 * A RESERVATION generates a unique reservationId in its 201 * NetworkCapabilities by copying the requestId which affects 202 * matching. A NetworkProvider can register a "blanket" NetworkOffer 203 * with reservationId = MATCH_ALL_RESERVATIONS to indicate that it 204 * is capable of generating NetworkOffers in response to RESERVATION 205 * requests. 206 * 207 * - TRACK_DEFAULT, which causes the framework to issue callbacks for 208 * the single, highest scoring current network (if any) that will 209 * be chosen for an app, but which cannot cause the framework to 210 * either create or retain the existence of any specific network. 211 * 212 * - TRACK_SYSTEM_DEFAULT, which causes the framework to send callbacks 213 * for the network (if any) that satisfies the default Internet 214 * request. 215 * 216 * - TRACK_BEST, which causes the framework to send callbacks about 217 * the single, highest scoring current network (if any) that matches 218 * the specified NetworkCapabilities. 219 * 220 * - BACKGROUND_REQUEST, like REQUEST but does not cause any networks 221 * to retain the NET_CAPABILITY_FOREGROUND capability. A network with 222 * no foreground requests is in the background. A network that has 223 * one or more background requests and loses its last foreground 224 * request to a higher-scoring network will not go into the 225 * background immediately, but will linger and go into the background 226 * after the linger timeout. 227 * 228 * - The value NONE is used only by applications. When an application 229 * creates a NetworkRequest, it does not have a type; the type is set 230 * by the system depending on the method used to file the request 231 * (requestNetwork, registerNetworkCallback, etc.). 232 * 233 * @hide 234 */ 235 public static enum Type { 236 NONE, 237 LISTEN, 238 TRACK_DEFAULT, 239 REQUEST, 240 BACKGROUND_REQUEST, 241 TRACK_SYSTEM_DEFAULT, 242 LISTEN_FOR_BEST, 243 RESERVATION, 244 }; 245 246 /** 247 * The type of the request. This is only used by the system and is always NONE elsewhere. 248 * 249 * @hide 250 */ 251 public final Type type; 252 253 /** 254 * @hide 255 */ NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type)256 public NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type) { 257 if (nc == null) { 258 throw new NullPointerException(); 259 } 260 if (nc.getReservationId() != RES_ID_UNSET) { 261 throw new IllegalArgumentException("ReservationId must only be set by the system"); 262 } 263 requestId = rId; 264 networkCapabilities = nc; 265 if (type == Type.RESERVATION) { 266 // Conceptually, the reservationId is not related to the requestId; however, the 267 // requestId fulfills the same uniqueness requirements that are needed for the 268 // reservationId, so it can be reused for this purpose. 269 networkCapabilities.setReservationId(rId); 270 } 271 this.legacyType = legacyType; 272 this.type = type; 273 } 274 275 /** 276 * @hide 277 */ NetworkRequest(NetworkRequest that)278 public NetworkRequest(NetworkRequest that) { 279 networkCapabilities = new NetworkCapabilities(that.networkCapabilities); 280 requestId = that.requestId; 281 this.legacyType = that.legacyType; 282 this.type = that.type; 283 } 284 NetworkRequest(Parcel in)285 private NetworkRequest(Parcel in) { 286 networkCapabilities = NetworkCapabilities.CREATOR.createFromParcel(in); 287 legacyType = in.readInt(); 288 requestId = in.readInt(); 289 type = Type.valueOf(in.readString()); // IllegalArgumentException if invalid. 290 } 291 292 /** 293 * Builder used to create {@link NetworkRequest} objects. Specify the Network features 294 * needed in terms of {@link NetworkCapabilities} features 295 */ 296 public static class Builder { 297 /** 298 * Capabilities that are currently compatible with VCN networks. 299 */ 300 private static final List<Integer> VCN_SUPPORTED_CAPABILITIES = Arrays.asList( 301 NET_CAPABILITY_CAPTIVE_PORTAL, 302 NET_CAPABILITY_DUN, 303 NET_CAPABILITY_FOREGROUND, 304 NET_CAPABILITY_INTERNET, 305 NET_CAPABILITY_NOT_CONGESTED, 306 NET_CAPABILITY_NOT_METERED, 307 NET_CAPABILITY_NOT_RESTRICTED, 308 NET_CAPABILITY_NOT_ROAMING, 309 NET_CAPABILITY_NOT_SUSPENDED, 310 NET_CAPABILITY_NOT_VPN, 311 NET_CAPABILITY_PARTIAL_CONNECTIVITY, 312 NET_CAPABILITY_TEMPORARILY_NOT_METERED, 313 NET_CAPABILITY_TRUSTED, 314 NET_CAPABILITY_VALIDATED, 315 NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED); 316 317 private final NetworkCapabilities mNetworkCapabilities; 318 319 // A boolean that represents whether the NOT_VCN_MANAGED capability should be deduced when 320 // the NetworkRequest object is built. 321 private boolean mShouldDeduceNotVcnManaged = true; 322 323 /** 324 * Default constructor for Builder. 325 */ Builder()326 public Builder() { 327 // By default, restrict this request to networks available to this app. 328 // Apps can rescind this restriction, but ConnectivityService will enforce 329 // it for apps that do not have the NETWORK_SETTINGS permission. 330 mNetworkCapabilities = new NetworkCapabilities(); 331 mNetworkCapabilities.setSingleUid(Process.myUid()); 332 } 333 334 /** 335 * Creates a new Builder of NetworkRequest from an existing instance. 336 */ Builder(@onNull final NetworkRequest request)337 public Builder(@NonNull final NetworkRequest request) { 338 Objects.requireNonNull(request); 339 mNetworkCapabilities = request.networkCapabilities; 340 // If the caller constructed the builder from a request, it means the user 341 // might explicitly want the capabilities from the request. Thus, the NOT_VCN_MANAGED 342 // capabilities should not be touched later. 343 mShouldDeduceNotVcnManaged = false; 344 } 345 346 /** 347 * Build {@link NetworkRequest} give the current set of capabilities. 348 */ build()349 public NetworkRequest build() { 350 // Make a copy of mNetworkCapabilities so we don't inadvertently remove NOT_RESTRICTED 351 // when later an unrestricted capability could be added to mNetworkCapabilities, in 352 // which case NOT_RESTRICTED should be returned to mNetworkCapabilities, which 353 // maybeMarkCapabilitiesRestricted() doesn't add back. 354 final NetworkCapabilities nc = new NetworkCapabilities(mNetworkCapabilities); 355 nc.maybeMarkCapabilitiesRestricted(); 356 deduceNotVcnManagedCapability(nc); 357 return new NetworkRequest(nc, ConnectivityManager.TYPE_NONE, 358 ConnectivityManager.REQUEST_ID_UNSET, Type.NONE); 359 } 360 361 /** 362 * Add the given capability requirement to this builder. These represent 363 * the requested network's required capabilities. Note that when searching 364 * for a network to satisfy a request, all capabilities requested must be 365 * satisfied. 366 * 367 * @param capability The capability to add. 368 * @return The builder to facilitate chaining 369 * {@code builder.addCapability(...).addCapability();}. 370 */ addCapability(@etworkCapabilities.NetCapability int capability)371 public Builder addCapability(@NetworkCapabilities.NetCapability int capability) { 372 mNetworkCapabilities.addCapability(capability); 373 if (capability == NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED) { 374 mShouldDeduceNotVcnManaged = false; 375 } 376 return this; 377 } 378 379 /** 380 * Removes (if found) the given capability from this builder instance. 381 * 382 * @param capability The capability to remove. 383 * @return The builder to facilitate chaining. 384 */ removeCapability(@etworkCapabilities.NetCapability int capability)385 public Builder removeCapability(@NetworkCapabilities.NetCapability int capability) { 386 mNetworkCapabilities.removeCapability(capability); 387 if (capability == NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED) { 388 mShouldDeduceNotVcnManaged = false; 389 } 390 return this; 391 } 392 393 /** 394 * Set the {@code NetworkCapabilities} for this builder instance, 395 * overriding any capabilities that had been previously set. 396 * 397 * @param nc The superseding {@code NetworkCapabilities} instance. 398 * @return The builder to facilitate chaining. 399 * @hide 400 */ setCapabilities(NetworkCapabilities nc)401 public Builder setCapabilities(NetworkCapabilities nc) { 402 mNetworkCapabilities.set(nc); 403 return this; 404 } 405 406 /** 407 * Sets this request to match only networks that apply to the specified UIDs. 408 * 409 * By default, the set of UIDs is the UID of the calling app, and this request will match 410 * any network that applies to the app. Setting it to {@code null} will observe any 411 * network on the system, even if it does not apply to this app. In this case, any 412 * {@link NetworkSpecifier} set on this request will be redacted or removed to prevent the 413 * application deducing restricted information such as location. 414 * 415 * @param uids The UIDs as a set of {@code Range<Integer>}, or null for everything. 416 * @return The builder to facilitate chaining. 417 * @hide 418 */ 419 @NonNull 420 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 421 @SuppressLint("MissingGetterMatchingBuilder") setUids(@ullable Set<Range<Integer>> uids)422 public Builder setUids(@Nullable Set<Range<Integer>> uids) { 423 mNetworkCapabilities.setUids(uids); 424 return this; 425 } 426 427 /** 428 * Add a capability that must not exist in the requested network. 429 * <p> 430 * If the capability was previously added to the list of required capabilities (for 431 * example, it was there by default or added using {@link #addCapability(int)} method), then 432 * it will be removed from the list of required capabilities as well. 433 * 434 * @see #addCapability(int) 435 * 436 * @param capability The capability to add to forbidden capability list. 437 * @return The builder to facilitate chaining. 438 * 439 * @hide 440 */ 441 @NonNull 442 @SuppressLint("MissingGetterMatchingBuilder") 443 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 444 // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public addForbiddenCapability(@etworkCapabilities.NetCapability int capability)445 public Builder addForbiddenCapability(@NetworkCapabilities.NetCapability int capability) { 446 mNetworkCapabilities.addForbiddenCapability(capability); 447 return this; 448 } 449 450 /** 451 * Removes (if found) the given forbidden capability from this builder instance. 452 * 453 * @param capability The forbidden capability to remove. 454 * @return The builder to facilitate chaining. 455 * 456 * @hide 457 */ 458 @NonNull 459 @SuppressLint("BuilderSetStyle") 460 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 461 // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public removeForbiddenCapability( @etworkCapabilities.NetCapability int capability)462 public Builder removeForbiddenCapability( 463 @NetworkCapabilities.NetCapability int capability) { 464 mNetworkCapabilities.removeForbiddenCapability(capability); 465 return this; 466 } 467 468 /** 469 * Completely clears all the {@code NetworkCapabilities} from this builder instance, 470 * removing even the capabilities that are set by default when the object is constructed. 471 * Also removes any set forbidden capabilities. 472 * 473 * @return The builder to facilitate chaining. 474 */ 475 @NonNull clearCapabilities()476 public Builder clearCapabilities() { 477 mNetworkCapabilities.clearAll(); 478 // If the caller explicitly clear all capabilities, the NOT_VCN_MANAGED capabilities 479 // should not be add back later. 480 mShouldDeduceNotVcnManaged = false; 481 return this; 482 } 483 484 /** 485 * Adds the given transport requirement to this builder. These represent 486 * the set of allowed transports for the request. Only networks using one 487 * of these transports will satisfy the request. If no particular transports 488 * are required, none should be specified here. 489 * 490 * @param transportType The transport type to add. 491 * @return The builder to facilitate chaining. 492 */ addTransportType(@etworkCapabilities.Transport int transportType)493 public Builder addTransportType(@NetworkCapabilities.Transport int transportType) { 494 mNetworkCapabilities.addTransportType(transportType); 495 return this; 496 } 497 498 /** 499 * Removes (if found) the given transport from this builder instance. 500 * 501 * @param transportType The transport type to remove. 502 * @return The builder to facilitate chaining. 503 */ removeTransportType(@etworkCapabilities.Transport int transportType)504 public Builder removeTransportType(@NetworkCapabilities.Transport int transportType) { 505 mNetworkCapabilities.removeTransportType(transportType); 506 return this; 507 } 508 509 /** 510 * @hide 511 */ setLinkUpstreamBandwidthKbps(int upKbps)512 public Builder setLinkUpstreamBandwidthKbps(int upKbps) { 513 mNetworkCapabilities.setLinkUpstreamBandwidthKbps(upKbps); 514 return this; 515 } 516 /** 517 * @hide 518 */ setLinkDownstreamBandwidthKbps(int downKbps)519 public Builder setLinkDownstreamBandwidthKbps(int downKbps) { 520 mNetworkCapabilities.setLinkDownstreamBandwidthKbps(downKbps); 521 return this; 522 } 523 524 /** 525 * Sets the optional bearer specific network specifier. 526 * This has no meaning if a single transport is also not specified, so calling 527 * this without a single transport set will generate an exception, as will 528 * subsequently adding or removing transports after this is set. 529 * </p> 530 * If the {@code networkSpecifier} is provided, it shall be interpreted as follows: 531 * <ul> 532 * <li>If the specifier can be parsed as an integer, it will be treated as a 533 * {@link android.net TelephonyNetworkSpecifier}, and the provided integer will be 534 * interpreted as a SubscriptionId. 535 * <li>If the value is an ethernet interface name, it will be treated as such. 536 * <li>For all other cases, the behavior is undefined. 537 * </ul> 538 * 539 * @param networkSpecifier A {@code String} of either a SubscriptionId in cellular 540 * network request or an ethernet interface name in ethernet 541 * network request. 542 * 543 * @deprecated Use {@link #setNetworkSpecifier(NetworkSpecifier)} instead. 544 */ 545 @Deprecated setNetworkSpecifier(String networkSpecifier)546 public Builder setNetworkSpecifier(String networkSpecifier) { 547 try { 548 int subId = Integer.parseInt(networkSpecifier); 549 return setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder() 550 .setSubscriptionId(subId).build()); 551 } catch (NumberFormatException nfe) { 552 // An EthernetNetworkSpecifier or TestNetworkSpecifier does not accept null or empty 553 // ("") strings. When network specifiers were strings a null string and an empty 554 // string were considered equivalent. Hence no meaning is attached to a null or 555 // empty ("") string. 556 if (TextUtils.isEmpty(networkSpecifier)) { 557 return setNetworkSpecifier((NetworkSpecifier) null); 558 } else if (mNetworkCapabilities.hasTransport(TRANSPORT_TEST)) { 559 return setNetworkSpecifier(new TestNetworkSpecifier(networkSpecifier)); 560 } else { 561 return setNetworkSpecifier(new EthernetNetworkSpecifier(networkSpecifier)); 562 } 563 } 564 } 565 566 /** 567 * Sets the optional bearer specific network specifier. 568 * This has no meaning if a single transport is also not specified, so calling 569 * this without a single transport set will generate an exception, as will 570 * subsequently adding or removing transports after this is set. 571 * </p> 572 * 573 * @param networkSpecifier A concrete, parcelable framework class that extends 574 * NetworkSpecifier. 575 */ setNetworkSpecifier(NetworkSpecifier networkSpecifier)576 public Builder setNetworkSpecifier(NetworkSpecifier networkSpecifier) { 577 if (networkSpecifier instanceof MatchAllNetworkSpecifier) { 578 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted"); 579 } 580 mNetworkCapabilities.setNetworkSpecifier(networkSpecifier); 581 // Do not touch NOT_VCN_MANAGED if the caller needs to access to a very specific 582 // Network. 583 mShouldDeduceNotVcnManaged = false; 584 return this; 585 } 586 587 /** 588 * Sets the signal strength. This is a signed integer, with higher values indicating a 589 * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same 590 * RSSI units reported by WifiManager. 591 * <p> 592 * Note that when used to register a network callback, this specifies the minimum acceptable 593 * signal strength. When received as the state of an existing network it specifies the 594 * current value. A value of {@code SIGNAL_STRENGTH_UNSPECIFIED} means no value when 595 * received and has no effect when requesting a callback. 596 * 597 * <p>This method requires the caller to hold the 598 * {@link android.Manifest.permission#NETWORK_SIGNAL_STRENGTH_WAKEUP} permission 599 * 600 * @param signalStrength the bearer-specific signal strength. 601 * @hide 602 */ 603 @SystemApi 604 @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP) setSignalStrength(int signalStrength)605 public @NonNull Builder setSignalStrength(int signalStrength) { 606 mNetworkCapabilities.setSignalStrength(signalStrength); 607 return this; 608 } 609 610 /** 611 * Deduce the NET_CAPABILITY_NOT_VCN_MANAGED capability from other capabilities 612 * and user intention, which includes: 613 * 1. For the requests that don't have anything besides 614 * {@link #VCN_SUPPORTED_CAPABILITIES}, add the NET_CAPABILITY_NOT_VCN_MANAGED to 615 * allow the callers automatically utilize VCN networks if available. 616 * 2. For the requests that explicitly add or remove NET_CAPABILITY_NOT_VCN_MANAGED, 617 * or has clear intention of tracking specific network, 618 * do not alter them to allow user fire request that suits their need. 619 * 620 * @hide 621 */ deduceNotVcnManagedCapability(final NetworkCapabilities nc)622 private void deduceNotVcnManagedCapability(final NetworkCapabilities nc) { 623 if (!mShouldDeduceNotVcnManaged) return; 624 for (final int cap : nc.getCapabilities()) { 625 if (!VCN_SUPPORTED_CAPABILITIES.contains(cap)) return; 626 } 627 nc.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED); 628 } 629 630 /** 631 * Sets the optional subscription ID set. 632 * <p> 633 * This specify the subscription IDs requirement. 634 * A network will satisfy this request only if it matches one of the subIds in this set. 635 * An empty set matches all networks, including those without a subId. 636 * 637 * <p>Registering a NetworkRequest with a non-empty set of subIds requires the 638 * NETWORK_FACTORY permission. 639 * 640 * @param subIds A {@code Set} that represents subscription IDs. 641 */ 642 @NonNull 643 @FlaggedApi(Flags.FLAG_REQUEST_RESTRICTED_WIFI) setSubscriptionIds(@onNull Set<Integer> subIds)644 public Builder setSubscriptionIds(@NonNull Set<Integer> subIds) { 645 mNetworkCapabilities.setSubscriptionIds(subIds); 646 return this; 647 } 648 649 /** 650 * Specifies whether the built request should also match networks that do not apply to the 651 * calling UID. 652 * 653 * By default, the built request will only match networks that apply to the calling UID. 654 * If this method is called with {@code true}, the built request will match any network on 655 * the system that matches the other parameters of the request. In this case, any 656 * information in the built request that is subject to redaction for security or privacy 657 * purposes, such as a {@link NetworkSpecifier}, will be redacted or removed to prevent the 658 * application deducing sensitive information. 659 * 660 * @param include Whether to match networks that do not apply to the calling UID. 661 * @return The builder to facilitate chaining. 662 */ 663 @NonNull setIncludeOtherUidNetworks(boolean include)664 public Builder setIncludeOtherUidNetworks(boolean include) { 665 if (include) { 666 mNetworkCapabilities.setUids(null); 667 } else { 668 mNetworkCapabilities.setSingleUid(Process.myUid()); 669 } 670 return this; 671 } 672 } 673 674 // implement the Parcelable interface describeContents()675 public int describeContents() { 676 return 0; 677 } writeToParcel(Parcel dest, int flags)678 public void writeToParcel(Parcel dest, int flags) { 679 networkCapabilities.writeToParcel(dest, flags); 680 dest.writeInt(legacyType); 681 dest.writeInt(requestId); 682 dest.writeString(type.name()); 683 } 684 685 public static final @android.annotation.NonNull Creator<NetworkRequest> CREATOR = 686 new Creator<NetworkRequest>() { 687 public NetworkRequest createFromParcel(Parcel in) { 688 return new NetworkRequest(in); 689 } 690 public NetworkRequest[] newArray(int size) { 691 return new NetworkRequest[size]; 692 } 693 }; 694 695 /** 696 * Returns true iff. this NetworkRequest is of type LISTEN. 697 * 698 * @hide 699 */ isListen()700 public boolean isListen() { 701 return type == Type.LISTEN; 702 } 703 704 /** 705 * Returns true iff. this NetworkRequest is of type LISTEN_FOR_BEST. 706 * 707 * @hide 708 */ isListenForBest()709 public boolean isListenForBest() { 710 return type == Type.LISTEN_FOR_BEST; 711 } 712 713 /** 714 * Returns true iff. the contained NetworkRequest is one that: 715 * 716 * - should be associated with at most one satisfying network 717 * at a time; 718 * 719 * - should cause a network to be kept up, but not necessarily in 720 * the foreground, if it is the best network which can satisfy the 721 * NetworkRequest. 722 * 723 * For full detail of how isRequest() is used for pairing Networks with 724 * NetworkRequests read rematchNetworkAndRequests(). 725 * 726 * @hide 727 */ isRequest()728 public boolean isRequest() { 729 return type == Type.REQUEST || type == Type.BACKGROUND_REQUEST || type == Type.RESERVATION; 730 } 731 732 /** 733 * Returns true iff. this NetworkRequest is of type BACKGROUND_REQUEST. 734 * 735 * @hide 736 */ isBackgroundRequest()737 public boolean isBackgroundRequest() { 738 return type == Type.BACKGROUND_REQUEST; 739 } 740 741 /** 742 * @see Builder#addCapability(int) 743 */ hasCapability(@etCapability int capability)744 public boolean hasCapability(@NetCapability int capability) { 745 return networkCapabilities.hasCapability(capability); 746 } 747 748 /** 749 * @see Builder#addForbiddenCapability(int) 750 * 751 * @hide 752 */ 753 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 754 // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public instead of @SystemApi hasForbiddenCapability(@etCapability int capability)755 public boolean hasForbiddenCapability(@NetCapability int capability) { 756 return networkCapabilities.hasForbiddenCapability(capability); 757 } 758 759 /** 760 * Returns true if and only if the capabilities requested in this NetworkRequest are satisfied 761 * by the provided {@link NetworkCapabilities}. 762 * 763 * @param nc Capabilities that should satisfy this NetworkRequest. null capabilities do not 764 * satisfy any request. 765 */ canBeSatisfiedBy(@ullable NetworkCapabilities nc)766 public boolean canBeSatisfiedBy(@Nullable NetworkCapabilities nc) { 767 return networkCapabilities.satisfiedByNetworkCapabilities(nc); 768 } 769 770 /** 771 * @see Builder#addTransportType(int) 772 */ hasTransport(@ransport int transportType)773 public boolean hasTransport(@Transport int transportType) { 774 return networkCapabilities.hasTransport(transportType); 775 } 776 777 /** 778 * @see Builder#setNetworkSpecifier(NetworkSpecifier) 779 */ 780 @Nullable getNetworkSpecifier()781 public NetworkSpecifier getNetworkSpecifier() { 782 return networkCapabilities.getNetworkSpecifier(); 783 } 784 785 /** 786 * @return the uid of the app making the request. 787 * 788 * Note: This could return {@link Process#INVALID_UID} if the {@link NetworkRequest} object was 789 * not obtained from {@link ConnectivityManager}. 790 * @hide 791 */ 792 @SystemApi getRequestorUid()793 public int getRequestorUid() { 794 return networkCapabilities.getRequestorUid(); 795 } 796 797 /** 798 * @return the package name of the app making the request. 799 * 800 * Note: This could return {@code null} if the {@link NetworkRequest} object was not obtained 801 * from {@link ConnectivityManager}. 802 * @hide 803 */ 804 @SystemApi 805 @Nullable getRequestorPackageName()806 public String getRequestorPackageName() { 807 return networkCapabilities.getRequestorPackageName(); 808 } 809 toString()810 public String toString() { 811 return "NetworkRequest [ " + type + " id=" + requestId + 812 (legacyType != ConnectivityManager.TYPE_NONE ? ", legacyType=" + legacyType : "") + 813 ", " + networkCapabilities.toString() + " ]"; 814 } 815 equals(@ullable Object obj)816 public boolean equals(@Nullable Object obj) { 817 if (obj instanceof NetworkRequest == false) return false; 818 NetworkRequest that = (NetworkRequest)obj; 819 return (that.legacyType == this.legacyType && 820 that.requestId == this.requestId && 821 that.type == this.type && 822 Objects.equals(that.networkCapabilities, this.networkCapabilities)); 823 } 824 hashCode()825 public int hashCode() { 826 return Objects.hash(requestId, legacyType, networkCapabilities, type); 827 } 828 829 /** 830 * Gets all the capabilities set on this {@code NetworkRequest} instance. 831 * 832 * @return an array of capability values for this instance. 833 */ 834 @NonNull getCapabilities()835 public @NetCapability int[] getCapabilities() { 836 // No need to make a defensive copy here as NC#getCapabilities() already returns 837 // a new array. 838 return networkCapabilities.getCapabilities(); 839 } 840 841 /** 842 * Get the enteprise identifiers. 843 * 844 * Get all the enterprise identifiers set on this {@code NetworkCapability} 845 * @return array of all the enterprise identifiers. 846 * @hide 847 */ 848 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) getEnterpriseIds()849 public @NonNull @NetworkCapabilities.EnterpriseId int[] getEnterpriseIds() { 850 // No need to make a defensive copy here as NC#getCapabilities() already returns 851 // a new array. 852 return networkCapabilities.getEnterpriseIds(); 853 } 854 855 /** 856 * Tests for the presence of an enterprise identifier on this instance. 857 * 858 * @param enterpriseId the enterprise capability identifier to be tested for. 859 * @return {@code true} if set on this instance. 860 * @hide 861 */ 862 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)863 public boolean hasEnterpriseId( 864 @NetworkCapabilities.EnterpriseId int enterpriseId) { 865 return networkCapabilities.hasEnterpriseId(enterpriseId); 866 } 867 868 /** 869 * Gets all the forbidden capabilities set on this {@code NetworkRequest} instance. 870 * 871 * @return an array of forbidden capability values for this instance. 872 * 873 * @hide 874 */ 875 @NonNull 876 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 877 // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public instead of @SystemApi getForbiddenCapabilities()878 public @NetCapability int[] getForbiddenCapabilities() { 879 // No need to make a defensive copy here as NC#getForbiddenCapabilities() already returns 880 // a new array. 881 return networkCapabilities.getForbiddenCapabilities(); 882 } 883 884 /** 885 * Gets all the transports set on this {@code NetworkRequest} instance. 886 * 887 * @return an array of transport type values for this instance. 888 */ 889 @NonNull getTransportTypes()890 public @Transport int[] getTransportTypes() { 891 // No need to make a defensive copy here as NC#getTransportTypes() already returns 892 // a new array. 893 return networkCapabilities.getTransportTypes(); 894 } 895 896 /** 897 * Gets all the subscription ids set on this {@code NetworkRequest} instance. 898 * 899 * @return Set of Integer values for this instance. 900 */ 901 @NonNull 902 @FlaggedApi(Flags.FLAG_REQUEST_RESTRICTED_WIFI) getSubscriptionIds()903 public Set<Integer> getSubscriptionIds() { 904 // No need to make a defensive copy here as NC#getSubscriptionIds() already returns 905 // a new set. 906 return networkCapabilities.getSubscriptionIds(); 907 } 908 } 909