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 com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE; 20 import static com.android.net.module.util.BitUtils.appendStringRepresentationOfBitMaskToStringBuilder; 21 import static com.android.net.module.util.BitUtils.describeDifferences; 22 23 import android.annotation.IntDef; 24 import android.annotation.LongDef; 25 import android.annotation.NonNull; 26 import android.annotation.Nullable; 27 import android.annotation.RequiresPermission; 28 import android.annotation.SuppressLint; 29 import android.annotation.SystemApi; 30 import android.compat.annotation.UnsupportedAppUsage; 31 import android.net.ConnectivityManager.NetworkCallback; 32 import android.os.Build; 33 import android.os.Parcel; 34 import android.os.Parcelable; 35 import android.os.Process; 36 import android.text.TextUtils; 37 import android.util.ArraySet; 38 import android.util.Range; 39 40 import com.android.internal.annotations.VisibleForTesting; 41 import com.android.net.module.util.BitUtils; 42 import com.android.net.module.util.CollectionUtils; 43 import com.android.net.module.util.NetworkCapabilitiesUtils; 44 45 import java.lang.annotation.Retention; 46 import java.lang.annotation.RetentionPolicy; 47 import java.util.ArrayList; 48 import java.util.Arrays; 49 import java.util.Collections; 50 import java.util.List; 51 import java.util.Objects; 52 import java.util.Set; 53 import java.util.StringJoiner; 54 55 /** 56 * Representation of the capabilities of an active network. 57 * 58 * <p>@see <a href="https://developer.android.com/training/basics/network-ops/reading-network-state> 59 * this general guide</a> on how to use NetworkCapabilities and related classes. 60 * 61 * <p>NetworkCapabilities represent what a network can do and what its 62 * characteristics are like. The principal attribute of NetworkCapabilities 63 * is in the capabilities bits, which are checked with 64 * {@link #hasCapability(int)}. See the list of capabilities and each 65 * capability for a description of what it means. 66 * 67 * <p>Some prime examples include {@code NET_CAPABILITY_MMS}, which means that the 68 * network is capable of sending MMS. A network without this capability 69 * is not capable of sending MMS. 70 * <p>The {@code NET_CAPABILITY_INTERNET} capability means that the network is 71 * configured to reach the general Internet. It may or may not actually 72 * provide connectivity ; the {@code NET_CAPABILITY_VALIDATED} bit indicates that 73 * the system found actual connectivity to the general Internet the last 74 * time it checked. Apps interested in actual connectivity should usually 75 * look at both these capabilities. 76 * <p>The {@code NET_CAPABILITY_NOT_METERED} capability is set for networks that 77 * do not bill the user for consumption of bytes. Applications are 78 * encouraged to consult this to determine appropriate usage, and to 79 * limit usage of metered network where possible, including deferring 80 * big downloads until such a time that an unmetered network is connected. 81 * Also see {@link android.app.job.JobScheduler} to help with scheduling such 82 * downloads, in particular 83 * {@link android.app.job.JobInfo.Builder#setRequiredNetwork(NetworkRequest)}. 84 * <p>NetworkCapabilities contain a number of other capabilities that 85 * represent what modern networks can and can't do. Look up the individual 86 * capabilities in this class to learn about each of them. 87 * 88 * <p>NetworkCapabilities typically represent attributes that can apply to 89 * any network. The attributes that apply only to specific transports like 90 * cellular or Wi-Fi can be found in the specifier (for requestable attributes) 91 * or in the transport info (for non-requestable ones). See 92 * {@link #getNetworkSpecifier} and {@link #getTransportInfo}. An app would 93 * downcast these to the specific class for the transport they need if they 94 * are interested in transport-specific attributes. Also see 95 * {@link android.net.wifi.WifiNetworkSpecifier} or 96 * {@link android.net.wifi.WifiInfo} for some examples of each of these. 97 * 98 * <p>NetworkCapabilities also contains other attributes like the estimated 99 * upstream and downstream bandwidth and the specific transport of that 100 * network (e.g. {@link #TRANSPORT_CELLULAR}). Generally, apps should normally 101 * have little reason to check for the type of transport ; for example, to 102 * query whether a network costs money to the user, do not look at the 103 * transport, but instead look at the absence or presence of 104 * {@link #NET_CAPABILITY_NOT_METERED} which will correctly account for 105 * metered Wi-Fis and free of charge cell connections. 106 * 107 * <p>The system communicates with apps about connected networks and uses 108 * NetworkCapabilities to express these capabilities about these networks. 109 * Apps should register callbacks with the {@link ConnectivityManager#requestNetwork} 110 * or {@link ConnectivityManager#registerNetworkCallback} family of methods 111 * to learn about the capabilities of a network on a continuous basis 112 * and be able to react to changes to capabilities. For quick debugging Android also 113 * provides {@link ConnectivityManager#getNetworkCapabilities(Network)}, 114 * but the dynamic nature of networking makes this ill-suited to production 115 * code since capabilities obtained in this way can go stale immediately. 116 * 117 * <p>Also see {@link NetworkRequest} which uses the same capabilities 118 * together with {@link ConnectivityManager#requestNetwork} for how to 119 * request the system brings up the kind of network your application needs. 120 */ 121 public final class NetworkCapabilities implements Parcelable { 122 private static final String TAG = "NetworkCapabilities"; 123 124 /** 125 * Mechanism to support redaction of fields in NetworkCapabilities that are guarded by specific 126 * app permissions. 127 **/ 128 /** 129 * Don't redact any fields since the receiving app holds all the necessary permissions. 130 * 131 * @hide 132 */ 133 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 134 public static final long REDACT_NONE = 0; 135 136 /** 137 * Redact any fields that need {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 138 * permission since the receiving app does not hold this permission or the location toggle 139 * is off. 140 * 141 * @see android.Manifest.permission#ACCESS_FINE_LOCATION 142 * @hide 143 */ 144 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 145 public static final long REDACT_FOR_ACCESS_FINE_LOCATION = 1 << 0; 146 147 /** 148 * Redact any fields that need {@link android.Manifest.permission#LOCAL_MAC_ADDRESS} 149 * permission since the receiving app does not hold this permission. 150 * 151 * @see android.Manifest.permission#LOCAL_MAC_ADDRESS 152 * @hide 153 */ 154 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 155 public static final long REDACT_FOR_LOCAL_MAC_ADDRESS = 1 << 1; 156 157 /** 158 * 159 * Redact any fields that need {@link android.Manifest.permission#NETWORK_SETTINGS} 160 * permission since the receiving app does not hold this permission. 161 * 162 * @see android.Manifest.permission#NETWORK_SETTINGS 163 * @hide 164 */ 165 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 166 public static final long REDACT_FOR_NETWORK_SETTINGS = 1 << 2; 167 168 /** 169 * Redact all fields in this object that require any relevant permission. 170 * @hide 171 */ 172 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 173 public static final long REDACT_ALL = -1L; 174 175 /** @hide */ 176 @LongDef(flag = true, prefix = { "REDACT_" }, value = { 177 REDACT_NONE, 178 REDACT_FOR_ACCESS_FINE_LOCATION, 179 REDACT_FOR_LOCAL_MAC_ADDRESS, 180 REDACT_FOR_NETWORK_SETTINGS, 181 REDACT_ALL 182 }) 183 @Retention(RetentionPolicy.SOURCE) 184 public @interface RedactionType {} 185 186 // Set to true when private DNS is broken. 187 private boolean mPrivateDnsBroken; 188 189 // Underlying networks, if any. VPNs and VCNs typically have underlying networks. 190 // This is an unmodifiable list and it will be returned as is in the getter. 191 @Nullable 192 private List<Network> mUnderlyingNetworks; 193 194 /** 195 * Uid of the app making the request. 196 */ 197 private int mRequestorUid; 198 199 /** 200 * Package name of the app making the request. 201 */ 202 private String mRequestorPackageName; 203 204 /** 205 * Enterprise capability identifier 1. It will be used to uniquely identify specific 206 * enterprise network. 207 */ 208 public static final int NET_ENTERPRISE_ID_1 = 1; 209 210 /** 211 * Enterprise capability identifier 2. It will be used to uniquely identify specific 212 * enterprise network. 213 */ 214 public static final int NET_ENTERPRISE_ID_2 = 2; 215 216 /** 217 * Enterprise capability identifier 3. It will be used to uniquely identify specific 218 * enterprise network. 219 */ 220 public static final int NET_ENTERPRISE_ID_3 = 3; 221 222 /** 223 * Enterprise capability identifier 4. It will be used to uniquely identify specific 224 * enterprise network. 225 */ 226 public static final int NET_ENTERPRISE_ID_4 = 4; 227 228 /** 229 * Enterprise capability identifier 5. It will be used to uniquely identify specific 230 * enterprise network. 231 */ 232 public static final int NET_ENTERPRISE_ID_5 = 5; 233 234 /** @hide */ 235 @Retention(RetentionPolicy.SOURCE) 236 @IntDef(prefix = { "NET_CAPABILITY_ENTERPRISE_SUB_LEVEL" }, value = { 237 NET_ENTERPRISE_ID_1, 238 NET_ENTERPRISE_ID_2, 239 NET_ENTERPRISE_ID_3, 240 NET_ENTERPRISE_ID_4, 241 NET_ENTERPRISE_ID_5, 242 }) 243 public @interface EnterpriseId { 244 } 245 246 private static final int ALL_VALID_ENTERPRISE_IDS; 247 static { 248 int enterpriseIds = 0; 249 for (int i = NET_ENTERPRISE_ID_1; i <= NET_ENTERPRISE_ID_5; ++i) { 250 enterpriseIds |= 1 << i; 251 } 252 ALL_VALID_ENTERPRISE_IDS = enterpriseIds; 253 } 254 255 /** 256 * Bitfield representing the network's enterprise capability identifier. If any are specified 257 * they will be satisfied by any Network that matches all of them. 258 * See {@link #addEnterpriseId(int)} for details on how masks are added 259 */ 260 private int mEnterpriseId; 261 262 /** 263 * Get enteprise identifiers set. 264 * 265 * Get all the enterprise capabilities identifier set on this {@code NetworkCapability} 266 * If NET_CAPABILITY_ENTERPRISE is set and no enterprise ID is set, it is 267 * considered to have NET_CAPABILITY_ENTERPRISE by default. 268 * @return all the enterprise capabilities identifier set. 269 * 270 */ getEnterpriseIds()271 public @NonNull @EnterpriseId int[] getEnterpriseIds() { 272 if (hasCapability(NET_CAPABILITY_ENTERPRISE) && mEnterpriseId == 0) { 273 return new int[]{NET_ENTERPRISE_ID_1}; 274 } 275 return BitUtils.unpackBits(mEnterpriseId); 276 } 277 278 /** 279 * Tests for the presence of an enterprise capability identifier on this instance. 280 * 281 * If NET_CAPABILITY_ENTERPRISE is set and no enterprise ID is set, it is 282 * considered to have NET_CAPABILITY_ENTERPRISE by default. 283 * @param enterpriseId the enterprise capability identifier to be tested for. 284 * @return {@code true} if set on this instance. 285 */ hasEnterpriseId( @nterpriseId int enterpriseId)286 public boolean hasEnterpriseId( 287 @EnterpriseId int enterpriseId) { 288 if (enterpriseId == NET_ENTERPRISE_ID_1) { 289 if (hasCapability(NET_CAPABILITY_ENTERPRISE) && mEnterpriseId == 0) { 290 return true; 291 } 292 } 293 return isValidEnterpriseId(enterpriseId) 294 && ((mEnterpriseId & (1L << enterpriseId)) != 0); 295 } 296 NetworkCapabilities()297 public NetworkCapabilities() { 298 clearAll(); 299 mNetworkCapabilities = DEFAULT_CAPABILITIES; 300 } 301 NetworkCapabilities(NetworkCapabilities nc)302 public NetworkCapabilities(NetworkCapabilities nc) { 303 this(nc, REDACT_NONE); 304 } 305 306 /** 307 * Make a copy of NetworkCapabilities. 308 * 309 * @param nc Original NetworkCapabilities 310 * @param redactions bitmask of redactions that needs to be performed on this new instance of 311 * {@link NetworkCapabilities}. 312 * @hide 313 */ NetworkCapabilities(@ullable NetworkCapabilities nc, @RedactionType long redactions)314 public NetworkCapabilities(@Nullable NetworkCapabilities nc, @RedactionType long redactions) { 315 if (nc != null) { 316 set(nc); 317 } 318 if (mTransportInfo != null) { 319 mTransportInfo = nc.mTransportInfo.makeCopy(redactions); 320 } 321 } 322 323 /** 324 * Completely clears the contents of this object, removing even the capabilities that are set 325 * by default when the object is constructed. 326 * @hide 327 */ clearAll()328 public void clearAll() { 329 mNetworkCapabilities = mTransportTypes = mForbiddenNetworkCapabilities = 0; 330 mLinkUpBandwidthKbps = mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 331 mNetworkSpecifier = null; 332 mTransportInfo = null; 333 mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED; 334 mUids = null; 335 mAllowedUids.clear(); 336 mAdministratorUids = new int[0]; 337 mOwnerUid = Process.INVALID_UID; 338 mSSID = null; 339 mPrivateDnsBroken = false; 340 mRequestorUid = Process.INVALID_UID; 341 mRequestorPackageName = null; 342 mSubIds = new ArraySet<>(); 343 mUnderlyingNetworks = null; 344 mEnterpriseId = 0; 345 } 346 347 /** 348 * Set all contents of this object to the contents of a NetworkCapabilities. 349 * 350 * @param nc Original NetworkCapabilities 351 * @hide 352 */ set(@onNull NetworkCapabilities nc)353 public void set(@NonNull NetworkCapabilities nc) { 354 mNetworkCapabilities = nc.mNetworkCapabilities; 355 mTransportTypes = nc.mTransportTypes; 356 mLinkUpBandwidthKbps = nc.mLinkUpBandwidthKbps; 357 mLinkDownBandwidthKbps = nc.mLinkDownBandwidthKbps; 358 mNetworkSpecifier = nc.mNetworkSpecifier; 359 if (nc.getTransportInfo() != null) { 360 setTransportInfo(nc.getTransportInfo()); 361 } else { 362 setTransportInfo(null); 363 } 364 mSignalStrength = nc.mSignalStrength; 365 mUids = (nc.mUids == null) ? null : new ArraySet<>(nc.mUids); 366 setAllowedUids(nc.mAllowedUids); 367 setAdministratorUids(nc.getAdministratorUids()); 368 mOwnerUid = nc.mOwnerUid; 369 mForbiddenNetworkCapabilities = nc.mForbiddenNetworkCapabilities; 370 mSSID = nc.mSSID; 371 mPrivateDnsBroken = nc.mPrivateDnsBroken; 372 mRequestorUid = nc.mRequestorUid; 373 mRequestorPackageName = nc.mRequestorPackageName; 374 mSubIds = new ArraySet<>(nc.mSubIds); 375 // mUnderlyingNetworks is an unmodifiable list if non-null, so a defensive copy is not 376 // necessary. 377 mUnderlyingNetworks = nc.mUnderlyingNetworks; 378 mEnterpriseId = nc.mEnterpriseId; 379 } 380 381 /** 382 * Represents the network's capabilities. If any are specified they will be satisfied 383 * by any Network that matches all of them. 384 */ 385 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 386 private long mNetworkCapabilities; 387 388 /** 389 * If any capabilities specified here they must not exist in the matching Network. 390 */ 391 private long mForbiddenNetworkCapabilities; 392 393 /** @hide */ 394 @Retention(RetentionPolicy.SOURCE) 395 @IntDef(prefix = { "NET_CAPABILITY_" }, value = { 396 NET_CAPABILITY_MMS, 397 NET_CAPABILITY_SUPL, 398 NET_CAPABILITY_DUN, 399 NET_CAPABILITY_FOTA, 400 NET_CAPABILITY_IMS, 401 NET_CAPABILITY_CBS, 402 NET_CAPABILITY_WIFI_P2P, 403 NET_CAPABILITY_IA, 404 NET_CAPABILITY_RCS, 405 NET_CAPABILITY_XCAP, 406 NET_CAPABILITY_EIMS, 407 NET_CAPABILITY_NOT_METERED, 408 NET_CAPABILITY_INTERNET, 409 NET_CAPABILITY_NOT_RESTRICTED, 410 NET_CAPABILITY_TRUSTED, 411 NET_CAPABILITY_NOT_VPN, 412 NET_CAPABILITY_VALIDATED, 413 NET_CAPABILITY_CAPTIVE_PORTAL, 414 NET_CAPABILITY_NOT_ROAMING, 415 NET_CAPABILITY_FOREGROUND, 416 NET_CAPABILITY_NOT_CONGESTED, 417 NET_CAPABILITY_NOT_SUSPENDED, 418 NET_CAPABILITY_OEM_PAID, 419 NET_CAPABILITY_MCX, 420 NET_CAPABILITY_PARTIAL_CONNECTIVITY, 421 NET_CAPABILITY_TEMPORARILY_NOT_METERED, 422 NET_CAPABILITY_OEM_PRIVATE, 423 NET_CAPABILITY_VEHICLE_INTERNAL, 424 NET_CAPABILITY_NOT_VCN_MANAGED, 425 NET_CAPABILITY_ENTERPRISE, 426 NET_CAPABILITY_VSIM, 427 NET_CAPABILITY_BIP, 428 NET_CAPABILITY_HEAD_UNIT, 429 NET_CAPABILITY_MMTEL, 430 NET_CAPABILITY_PRIORITIZE_LATENCY, 431 NET_CAPABILITY_PRIORITIZE_BANDWIDTH, 432 }) 433 public @interface NetCapability { } 434 435 /** 436 * Indicates this is a network that has the ability to reach the 437 * carrier's MMSC for sending and receiving MMS messages. 438 */ 439 public static final int NET_CAPABILITY_MMS = 0; 440 441 /** 442 * Indicates this is a network that has the ability to reach the carrier's 443 * SUPL server, used to retrieve GPS information. 444 */ 445 public static final int NET_CAPABILITY_SUPL = 1; 446 447 /** 448 * Indicates this is a network that has the ability to reach the carrier's 449 * DUN or tethering gateway. 450 */ 451 public static final int NET_CAPABILITY_DUN = 2; 452 453 /** 454 * Indicates this is a network that has the ability to reach the carrier's 455 * FOTA portal, used for over the air updates. 456 */ 457 public static final int NET_CAPABILITY_FOTA = 3; 458 459 /** 460 * Indicates this is a network that has the ability to reach the carrier's 461 * IMS servers, used for network registration and signaling. 462 */ 463 public static final int NET_CAPABILITY_IMS = 4; 464 465 /** 466 * Indicates this is a network that has the ability to reach the carrier's 467 * CBS servers, used for carrier specific services. 468 */ 469 public static final int NET_CAPABILITY_CBS = 5; 470 471 /** 472 * Indicates this is a network that has the ability to reach a Wi-Fi direct 473 * peer. 474 */ 475 public static final int NET_CAPABILITY_WIFI_P2P = 6; 476 477 /** 478 * Indicates this is a network that has the ability to reach a carrier's 479 * Initial Attach servers. 480 */ 481 public static final int NET_CAPABILITY_IA = 7; 482 483 /** 484 * Indicates this is a network that has the ability to reach a carrier's 485 * RCS servers, used for Rich Communication Services. 486 */ 487 public static final int NET_CAPABILITY_RCS = 8; 488 489 /** 490 * Indicates this is a network that has the ability to reach a carrier's 491 * XCAP servers, used for configuration and control. 492 */ 493 public static final int NET_CAPABILITY_XCAP = 9; 494 495 /** 496 * Indicates this is a network that has the ability to reach a carrier's 497 * Emergency IMS servers or other services, used for network signaling 498 * during emergency calls. 499 */ 500 public static final int NET_CAPABILITY_EIMS = 10; 501 502 /** 503 * Indicates that this network is unmetered. 504 */ 505 public static final int NET_CAPABILITY_NOT_METERED = 11; 506 507 /** 508 * Indicates that this network should be able to reach the internet. 509 */ 510 public static final int NET_CAPABILITY_INTERNET = 12; 511 512 /** 513 * Indicates that this network is available for general use. If this is not set 514 * applications should not attempt to communicate on this network. Note that this 515 * is simply informative and not enforcement - enforcement is handled via other means. 516 * Set by default. 517 */ 518 public static final int NET_CAPABILITY_NOT_RESTRICTED = 13; 519 520 /** 521 * Indicates that the user has indicated implicit trust of this network. This 522 * generally means it's a sim-selected carrier, a plugged in ethernet, a paired 523 * BT device or a wifi the user asked to connect to. Untrusted networks 524 * are probably limited to unknown wifi AP. Set by default. 525 */ 526 public static final int NET_CAPABILITY_TRUSTED = 14; 527 528 /** 529 * Indicates that this network is not a VPN. This capability is set by default and should be 530 * explicitly cleared for VPN networks. 531 */ 532 public static final int NET_CAPABILITY_NOT_VPN = 15; 533 534 /** 535 * Indicates that connectivity on this network was successfully validated. For example, for a 536 * network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully 537 * detected. 538 */ 539 public static final int NET_CAPABILITY_VALIDATED = 16; 540 541 /** 542 * Indicates that this network was found to have a captive portal in place last time it was 543 * probed. 544 */ 545 public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17; 546 547 /** 548 * Indicates that this network is not roaming. 549 */ 550 public static final int NET_CAPABILITY_NOT_ROAMING = 18; 551 552 /** 553 * Indicates that this network is available for use by apps, and not a network that is being 554 * kept up in the background to facilitate fast network switching. 555 */ 556 public static final int NET_CAPABILITY_FOREGROUND = 19; 557 558 /** 559 * Indicates that this network is not congested. 560 * <p> 561 * When a network is congested, applications should defer network traffic 562 * that can be done at a later time, such as uploading analytics. 563 */ 564 public static final int NET_CAPABILITY_NOT_CONGESTED = 20; 565 566 /** 567 * Indicates that this network is not currently suspended. 568 * <p> 569 * When a network is suspended, the network's IP addresses and any connections 570 * established on the network remain valid, but the network is temporarily unable 571 * to transfer data. This can happen, for example, if a cellular network experiences 572 * a temporary loss of signal, such as when driving through a tunnel, etc. 573 * A network with this capability is not suspended, so is expected to be able to 574 * transfer data. 575 */ 576 public static final int NET_CAPABILITY_NOT_SUSPENDED = 21; 577 578 /** 579 * Indicates that traffic that goes through this network is paid by oem. For example, 580 * this network can be used by system apps to upload telemetry data. 581 * @hide 582 */ 583 @SystemApi 584 public static final int NET_CAPABILITY_OEM_PAID = 22; 585 586 /** 587 * Indicates this is a network that has the ability to reach a carrier's Mission Critical 588 * servers. 589 */ 590 public static final int NET_CAPABILITY_MCX = 23; 591 592 /** 593 * Indicates that this network was tested to only provide partial connectivity. 594 * @hide 595 */ 596 @SystemApi 597 public static final int NET_CAPABILITY_PARTIAL_CONNECTIVITY = 24; 598 599 /** 600 * Indicates that this network is temporarily unmetered. 601 * <p> 602 * This capability will be set for networks that are generally metered, but are currently 603 * unmetered, e.g., because the user is in a particular area. This capability can be changed at 604 * any time. When it is removed, applications are responsible for stopping any data transfer 605 * that should not occur on a metered network. 606 * Note that most apps should use {@link #NET_CAPABILITY_NOT_METERED} instead. For more 607 * information, see https://developer.android.com/about/versions/11/features/5g#meteredness. 608 */ 609 public static final int NET_CAPABILITY_TEMPORARILY_NOT_METERED = 25; 610 611 /** 612 * Indicates that this network is private to the OEM and meant only for OEM use. 613 * @hide 614 */ 615 @SystemApi 616 public static final int NET_CAPABILITY_OEM_PRIVATE = 26; 617 618 /** 619 * Indicates this is an internal vehicle network, meant to communicate with other 620 * automotive systems. 621 * 622 * @hide 623 */ 624 @SystemApi 625 public static final int NET_CAPABILITY_VEHICLE_INTERNAL = 27; 626 627 /** 628 * Indicates that this network is not subsumed by a Virtual Carrier Network (VCN). 629 * <p> 630 * To provide an experience on a VCN similar to a single traditional carrier network, in 631 * some cases the system sets this bit is set by default in application's network requests, 632 * and may choose to remove it at its own discretion when matching the request to a network. 633 * <p> 634 * Applications that want to know about a Virtual Carrier Network's underlying networks, 635 * for example to use them for multipath purposes, should remove this bit from their network 636 * requests ; the system will not add it back once removed. 637 * @hide 638 */ 639 @SystemApi 640 public static final int NET_CAPABILITY_NOT_VCN_MANAGED = 28; 641 642 /** 643 * Indicates that this network is intended for enterprise use. 644 * <p> 645 * 5G URSP rules may indicate that all data should use a connection dedicated for enterprise 646 * use. If the enterprise capability is requested, all enterprise traffic will be routed over 647 * the connection with this capability. 648 */ 649 public static final int NET_CAPABILITY_ENTERPRISE = 29; 650 651 /** 652 * Indicates that this network has ability to access the carrier's Virtual Sim service. 653 * @hide 654 */ 655 @SystemApi 656 public static final int NET_CAPABILITY_VSIM = 30; 657 658 /** 659 * Indicates that this network has ability to support Bearer Independent Protol. 660 * @hide 661 */ 662 @SystemApi 663 public static final int NET_CAPABILITY_BIP = 31; 664 665 /** 666 * Indicates that this network is connected to an automotive head unit. 667 */ 668 public static final int NET_CAPABILITY_HEAD_UNIT = 32; 669 670 /** 671 * Indicates that this network has ability to support MMTEL (Multimedia Telephony service). 672 */ 673 public static final int NET_CAPABILITY_MMTEL = 33; 674 675 /** 676 * Indicates that this network should be able to prioritize latency for the internet. 677 * 678 * Starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, requesting this capability with 679 * {@link ConnectivityManager#requestNetwork} requires declaration in the self-certified 680 * network capabilities. See {@link NetworkRequest} for the self-certification documentation. 681 */ 682 public static final int NET_CAPABILITY_PRIORITIZE_LATENCY = 34; 683 684 /** 685 * Indicates that this network should be able to prioritize bandwidth for the internet. 686 * 687 * Starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, requesting this capability with 688 * {@link ConnectivityManager#requestNetwork} requires declaration in the self-certified 689 * network capabilities. See {@link NetworkRequest} for the self-certification documentation. 690 */ 691 public static final int NET_CAPABILITY_PRIORITIZE_BANDWIDTH = 35; 692 693 private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS; 694 private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_PRIORITIZE_BANDWIDTH; 695 696 private static final int ALL_VALID_CAPABILITIES; 697 static { 698 int caps = 0; 699 for (int i = MIN_NET_CAPABILITY; i <= MAX_NET_CAPABILITY; ++i) { 700 caps |= 1 << i; 701 } 702 ALL_VALID_CAPABILITIES = caps; 703 } 704 705 /** 706 * Network capabilities that are expected to be mutable, i.e., can change while a particular 707 * network is connected. 708 */ 709 private static final long MUTABLE_CAPABILITIES = BitUtils.packBitList( 710 // TRUSTED can change when user explicitly connects to an untrusted network in Settings. 711 // http://b/18206275 712 NET_CAPABILITY_TRUSTED, 713 NET_CAPABILITY_VALIDATED, 714 NET_CAPABILITY_CAPTIVE_PORTAL, 715 NET_CAPABILITY_NOT_ROAMING, 716 NET_CAPABILITY_FOREGROUND, 717 NET_CAPABILITY_NOT_CONGESTED, 718 NET_CAPABILITY_NOT_SUSPENDED, 719 NET_CAPABILITY_PARTIAL_CONNECTIVITY, 720 NET_CAPABILITY_TEMPORARILY_NOT_METERED, 721 NET_CAPABILITY_NOT_VCN_MANAGED, 722 // The value of NET_CAPABILITY_HEAD_UNIT is 32, which cannot use int to do bit shift, 723 // otherwise there will be an overflow. Use long to do bit shift instead. 724 NET_CAPABILITY_HEAD_UNIT); 725 726 /** 727 * Network capabilities that are not allowed in NetworkRequests. This exists because the 728 * NetworkFactory / NetworkAgent model does not deal well with the situation where a 729 * capability's presence cannot be known in advance. If such a capability is requested, then we 730 * can get into a cycle where the NetworkFactory endlessly churns out NetworkAgents that then 731 * get immediately torn down because they do not have the requested capability. 732 */ 733 // Note that as a historical exception, the TRUSTED and NOT_VCN_MANAGED capabilities 734 // are mutable but requestable. Factories are responsible for not getting 735 // in an infinite loop about these. 736 private static final long NON_REQUESTABLE_CAPABILITIES = 737 MUTABLE_CAPABILITIES 738 & ~(1L << NET_CAPABILITY_TRUSTED) 739 & ~(1L << NET_CAPABILITY_NOT_VCN_MANAGED); 740 741 /** 742 * Capabilities that are set by default when the object is constructed. 743 */ 744 private static final long DEFAULT_CAPABILITIES = BitUtils.packBitList( 745 NET_CAPABILITY_NOT_RESTRICTED, 746 NET_CAPABILITY_TRUSTED, 747 NET_CAPABILITY_NOT_VPN); 748 749 /** 750 * Capabilities that are managed by ConnectivityService. 751 */ 752 private static final long CONNECTIVITY_MANAGED_CAPABILITIES = 753 BitUtils.packBitList( 754 NET_CAPABILITY_VALIDATED, 755 NET_CAPABILITY_CAPTIVE_PORTAL, 756 NET_CAPABILITY_FOREGROUND, 757 NET_CAPABILITY_PARTIAL_CONNECTIVITY); 758 759 /** 760 * Capabilities that are allowed for all test networks. This list must be set so that it is safe 761 * for an unprivileged user to create a network with these capabilities via shell. As such, it 762 * must never contain capabilities that are generally useful to the system, such as INTERNET, 763 * IMS, SUPL, etc. 764 */ 765 private static final long TEST_NETWORKS_ALLOWED_CAPABILITIES = 766 BitUtils.packBitList( 767 NET_CAPABILITY_NOT_METERED, 768 NET_CAPABILITY_TEMPORARILY_NOT_METERED, 769 NET_CAPABILITY_NOT_RESTRICTED, 770 NET_CAPABILITY_NOT_VPN, 771 NET_CAPABILITY_NOT_ROAMING, 772 NET_CAPABILITY_NOT_CONGESTED, 773 NET_CAPABILITY_NOT_SUSPENDED, 774 NET_CAPABILITY_NOT_VCN_MANAGED); 775 776 /** 777 * Extra allowed capabilities for test networks that do not have TRANSPORT_CELLULAR. Test 778 * networks with TRANSPORT_CELLULAR must not have those capabilities in order to mitigate 779 * the risk of being used by running apps. 780 */ 781 private static final long TEST_NETWORKS_EXTRA_ALLOWED_CAPABILITIES_ON_NON_CELL = 782 BitUtils.packBitList(NET_CAPABILITY_CBS, NET_CAPABILITY_DUN, NET_CAPABILITY_RCS); 783 784 /** 785 * Adds the given capability to this {@code NetworkCapability} instance. 786 * Note that when searching for a network to satisfy a request, all capabilities 787 * requested must be satisfied. 788 * 789 * @param capability the capability to be added. 790 * @return This NetworkCapabilities instance, to facilitate chaining. 791 * @hide 792 */ addCapability(@etCapability int capability)793 public @NonNull NetworkCapabilities addCapability(@NetCapability int capability) { 794 // If the given capability was previously added to the list of forbidden capabilities 795 // then the capability will also be removed from the list of forbidden capabilities. 796 // TODO: Consider adding forbidden capabilities to the public API and mention this 797 // in the documentation. 798 checkValidCapability(capability); 799 mNetworkCapabilities |= 1L << capability; 800 // remove from forbidden capability list 801 mForbiddenNetworkCapabilities &= ~(1L << capability); 802 return this; 803 } 804 805 /** 806 * Adds the given capability to the list of forbidden capabilities of this 807 * {@code NetworkCapability} instance. Note that when searching for a network to 808 * satisfy a request, the network must not contain any capability from forbidden capability 809 * list. 810 * <p> 811 * If the capability was previously added to the list of required capabilities (for 812 * example, it was there by default or added using {@link #addCapability(int)} method), then 813 * it will be removed from the list of required capabilities as well. 814 * 815 * @see #addCapability(int) 816 * @hide 817 */ addForbiddenCapability(@etCapability int capability)818 public void addForbiddenCapability(@NetCapability int capability) { 819 checkValidCapability(capability); 820 mForbiddenNetworkCapabilities |= 1L << capability; 821 mNetworkCapabilities &= ~(1L << capability); // remove from requested capabilities 822 } 823 824 /** 825 * Removes (if found) the given capability from this {@code NetworkCapability} 826 * instance that were added via addCapability(int) or setCapabilities(int[], int[]). 827 * 828 * @param capability the capability to be removed. 829 * @return This NetworkCapabilities instance, to facilitate chaining. 830 * @hide 831 */ removeCapability(@etCapability int capability)832 public @NonNull NetworkCapabilities removeCapability(@NetCapability int capability) { 833 checkValidCapability(capability); 834 final long mask = ~(1L << capability); 835 mNetworkCapabilities &= mask; 836 return this; 837 } 838 839 /** 840 * Removes (if found) the given forbidden capability from this {@code NetworkCapability} 841 * instance that were added via addForbiddenCapability(int) or setCapabilities(int[], int[]). 842 * 843 * @param capability the capability to be removed. 844 * @return This NetworkCapabilities instance, to facilitate chaining. 845 * @hide 846 */ removeForbiddenCapability(@etCapability int capability)847 public @NonNull NetworkCapabilities removeForbiddenCapability(@NetCapability int capability) { 848 checkValidCapability(capability); 849 mForbiddenNetworkCapabilities &= ~(1L << capability); 850 return this; 851 } 852 853 /** 854 * Sets (or clears) the given capability on this {@link NetworkCapabilities} 855 * instance. 856 * @hide 857 */ setCapability(@etCapability int capability, boolean value)858 public @NonNull NetworkCapabilities setCapability(@NetCapability int capability, 859 boolean value) { 860 if (value) { 861 addCapability(capability); 862 } else { 863 removeCapability(capability); 864 } 865 return this; 866 } 867 868 /** 869 * Gets all the capabilities set on this {@code NetworkCapability} instance. 870 * 871 * @return an array of capability values for this instance. 872 */ getCapabilities()873 public @NonNull @NetCapability int[] getCapabilities() { 874 return BitUtils.unpackBits(mNetworkCapabilities); 875 } 876 877 /** 878 * Gets all the forbidden capabilities set on this {@code NetworkCapability} instance. 879 * 880 * @return an array of forbidden capability values for this instance. 881 * @hide 882 */ getForbiddenCapabilities()883 public @NetCapability int[] getForbiddenCapabilities() { 884 return BitUtils.unpackBits(mForbiddenNetworkCapabilities); 885 } 886 887 888 /** 889 * Sets all the capabilities set on this {@code NetworkCapability} instance. 890 * This overwrites any existing capabilities. 891 * 892 * @hide 893 */ setCapabilities(@etCapability int[] capabilities, @NetCapability int[] forbiddenCapabilities)894 public void setCapabilities(@NetCapability int[] capabilities, 895 @NetCapability int[] forbiddenCapabilities) { 896 mNetworkCapabilities = BitUtils.packBits(capabilities); 897 mForbiddenNetworkCapabilities = BitUtils.packBits(forbiddenCapabilities); 898 } 899 900 /** 901 * @deprecated use {@link #setCapabilities(int[], int[])} 902 * @hide 903 */ 904 @Deprecated setCapabilities(@etCapability int[] capabilities)905 public void setCapabilities(@NetCapability int[] capabilities) { 906 setCapabilities(capabilities, new int[] {}); 907 } 908 909 /** 910 * Adds the given enterprise capability identifier to this {@code NetworkCapability} instance. 911 * Note that when searching for a network to satisfy a request, all capabilities identifier 912 * requested must be satisfied. 913 * 914 * @param enterpriseId the enterprise capability identifier to be added. 915 * @return This NetworkCapabilities instance, to facilitate chaining. 916 * @hide 917 */ addEnterpriseId( @nterpriseId int enterpriseId)918 public @NonNull NetworkCapabilities addEnterpriseId( 919 @EnterpriseId int enterpriseId) { 920 checkValidEnterpriseId(enterpriseId); 921 mEnterpriseId |= 1 << enterpriseId; 922 return this; 923 } 924 925 /** 926 * Removes (if found) the given enterprise capability identifier from this 927 * {@code NetworkCapability} instance that were added via addEnterpriseId(int) 928 * 929 * @param enterpriseId the enterprise capability identifier to be removed. 930 * @return This NetworkCapabilities instance, to facilitate chaining. 931 * @hide 932 */ removeEnterpriseId( @nterpriseId int enterpriseId)933 private @NonNull NetworkCapabilities removeEnterpriseId( 934 @EnterpriseId int enterpriseId) { 935 checkValidEnterpriseId(enterpriseId); 936 final int mask = ~(1 << enterpriseId); 937 mEnterpriseId &= mask; 938 return this; 939 } 940 941 /** 942 * Set the underlying networks of this network. 943 * 944 * @param networks The underlying networks of this network. 945 * 946 * @hide 947 */ setUnderlyingNetworks(@ullable List<Network> networks)948 public void setUnderlyingNetworks(@Nullable List<Network> networks) { 949 mUnderlyingNetworks = 950 (networks == null) ? null : Collections.unmodifiableList(new ArrayList<>(networks)); 951 } 952 953 /** 954 * Get the underlying networks of this network. If the caller doesn't have one of 955 * {@link android.Manifest.permission.NETWORK_FACTORY}, 956 * {@link android.Manifest.permission.NETWORK_SETTINGS} and 957 * {@link NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}, this is always redacted to null and 958 * it will be never useful to the caller. 959 * 960 * @return <li>If the list is null, this network hasn't declared underlying networks.</li> 961 * <li>If the list is empty, this network has declared that it has no underlying 962 * networks or it doesn't run on any of the available networks.</li> 963 * <li>The list can contain multiple underlying networks, e.g. a VPN running over 964 * multiple networks at the same time.</li> 965 * 966 * @hide 967 */ 968 @SuppressLint("NullableCollection") 969 @Nullable 970 @SystemApi getUnderlyingNetworks()971 public List<Network> getUnderlyingNetworks() { 972 return mUnderlyingNetworks; 973 } 974 equalsUnderlyingNetworks(@onNull NetworkCapabilities nc)975 private boolean equalsUnderlyingNetworks(@NonNull NetworkCapabilities nc) { 976 return Objects.equals(getUnderlyingNetworks(), nc.getUnderlyingNetworks()); 977 } 978 979 /** 980 * Tests for the presence of a capability on this instance. 981 * 982 * @param capability the capabilities to be tested for. 983 * @return {@code true} if set on this instance. 984 */ hasCapability(@etCapability int capability)985 public boolean hasCapability(@NetCapability int capability) { 986 return isValidCapability(capability) 987 && ((mNetworkCapabilities & (1L << capability)) != 0); 988 } 989 990 /** @hide */ 991 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) hasForbiddenCapability(@etCapability int capability)992 public boolean hasForbiddenCapability(@NetCapability int capability) { 993 return isValidCapability(capability) 994 && ((mForbiddenNetworkCapabilities & (1L << capability)) != 0); 995 } 996 997 /** 998 * Check if this NetworkCapabilities has system managed capabilities or not. 999 * @hide 1000 */ hasConnectivityManagedCapability()1001 public boolean hasConnectivityManagedCapability() { 1002 return ((mNetworkCapabilities & CONNECTIVITY_MANAGED_CAPABILITIES) != 0); 1003 } 1004 1005 /** 1006 * Get the name of the given capability that carriers use. 1007 * If the capability does not have a carrier-name, returns null. 1008 * 1009 * @param capability The capability to get the carrier-name of. 1010 * @return The carrier-name of the capability, or null if it doesn't exist. 1011 * @hide 1012 */ 1013 @SystemApi getCapabilityCarrierName(@etCapability int capability)1014 public static @Nullable String getCapabilityCarrierName(@NetCapability int capability) { 1015 if (capability == NET_CAPABILITY_ENTERPRISE) { 1016 return capabilityNameOf(capability); 1017 } else { 1018 return null; 1019 } 1020 } 1021 1022 /** 1023 * Convenience function that returns a human-readable description of the first mutable 1024 * capability we find. Used to present an error message to apps that request mutable 1025 * capabilities. 1026 * 1027 * @hide 1028 */ describeFirstNonRequestableCapability()1029 public @Nullable String describeFirstNonRequestableCapability() { 1030 final long nonRequestable = (mNetworkCapabilities | mForbiddenNetworkCapabilities) 1031 & NON_REQUESTABLE_CAPABILITIES; 1032 1033 if (nonRequestable != 0) { 1034 return capabilityNameOf(BitUtils.unpackBits(nonRequestable)[0]); 1035 } 1036 if (mLinkUpBandwidthKbps != 0 || mLinkDownBandwidthKbps != 0) return "link bandwidth"; 1037 if (hasSignalStrength()) return "signalStrength"; 1038 if (isPrivateDnsBroken()) { 1039 return "privateDnsBroken"; 1040 } 1041 return null; 1042 } 1043 equalsEnterpriseCapabilitiesId(@onNull NetworkCapabilities nc)1044 private boolean equalsEnterpriseCapabilitiesId(@NonNull NetworkCapabilities nc) { 1045 return nc.mEnterpriseId == this.mEnterpriseId; 1046 } 1047 satisfiedByEnterpriseCapabilitiesId(@onNull NetworkCapabilities nc)1048 private boolean satisfiedByEnterpriseCapabilitiesId(@NonNull NetworkCapabilities nc) { 1049 final int requestedEnterpriseCapabilitiesId = mEnterpriseId; 1050 final int providedEnterpriseCapabailitiesId = nc.mEnterpriseId; 1051 1052 if ((providedEnterpriseCapabailitiesId & requestedEnterpriseCapabilitiesId) 1053 == requestedEnterpriseCapabilitiesId) { 1054 return true; 1055 } else if (providedEnterpriseCapabailitiesId == 0 1056 && (requestedEnterpriseCapabilitiesId == (1L << NET_ENTERPRISE_ID_1))) { 1057 return true; 1058 } else { 1059 return false; 1060 } 1061 } 1062 satisfiedByNetCapabilities(@onNull NetworkCapabilities nc, boolean onlyImmutable)1063 private boolean satisfiedByNetCapabilities(@NonNull NetworkCapabilities nc, 1064 boolean onlyImmutable) { 1065 long requestedCapabilities = mNetworkCapabilities; 1066 long requestedForbiddenCapabilities = mForbiddenNetworkCapabilities; 1067 long providedCapabilities = nc.mNetworkCapabilities; 1068 1069 if (onlyImmutable) { 1070 requestedCapabilities &= ~MUTABLE_CAPABILITIES; 1071 requestedForbiddenCapabilities &= ~MUTABLE_CAPABILITIES; 1072 } 1073 return ((providedCapabilities & requestedCapabilities) == requestedCapabilities) 1074 && ((requestedForbiddenCapabilities & providedCapabilities) == 0); 1075 } 1076 1077 /** @hide */ equalsNetCapabilities(@onNull NetworkCapabilities nc)1078 public boolean equalsNetCapabilities(@NonNull NetworkCapabilities nc) { 1079 return (nc.mNetworkCapabilities == this.mNetworkCapabilities) 1080 && (nc.mForbiddenNetworkCapabilities == this.mForbiddenNetworkCapabilities); 1081 } 1082 equalsNetCapabilitiesRequestable(@onNull NetworkCapabilities that)1083 private boolean equalsNetCapabilitiesRequestable(@NonNull NetworkCapabilities that) { 1084 return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) 1085 == (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)) 1086 && ((this.mForbiddenNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) 1087 == (that.mForbiddenNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)); 1088 } 1089 1090 /** 1091 * Removes the NET_CAPABILITY_NOT_RESTRICTED capability if inferring the network is restricted. 1092 * 1093 * @hide 1094 */ maybeMarkCapabilitiesRestricted()1095 public void maybeMarkCapabilitiesRestricted() { 1096 if (NetworkCapabilitiesUtils.inferRestrictedCapability(this)) { 1097 removeCapability(NET_CAPABILITY_NOT_RESTRICTED); 1098 } 1099 } 1100 1101 /** 1102 * @see #restrictCapabilitiesForTestNetwork(int) 1103 * @deprecated Use {@link #restrictCapabilitiesForTestNetwork(int)} (without the typo) instead. 1104 * @hide 1105 */ 1106 @Deprecated restrictCapabilitesForTestNetwork(int creatorUid)1107 public void restrictCapabilitesForTestNetwork(int creatorUid) { 1108 // Do not remove without careful consideration: this method has a typo in its name but is 1109 // called by the first S CTS releases, therefore it cannot be removed from the connectivity 1110 // module as long as such CTS releases are valid for testing S devices. 1111 restrictCapabilitiesForTestNetwork(creatorUid); 1112 } 1113 1114 /** 1115 * Test networks have strong restrictions on what capabilities they can have. Enforce these 1116 * restrictions. 1117 * @hide 1118 */ restrictCapabilitiesForTestNetwork(int creatorUid)1119 public void restrictCapabilitiesForTestNetwork(int creatorUid) { 1120 final long originalCapabilities = mNetworkCapabilities; 1121 final long originalTransportTypes = mTransportTypes; 1122 final NetworkSpecifier originalSpecifier = mNetworkSpecifier; 1123 final int originalSignalStrength = mSignalStrength; 1124 final int originalOwnerUid = getOwnerUid(); 1125 final int[] originalAdministratorUids = getAdministratorUids(); 1126 final TransportInfo originalTransportInfo = getTransportInfo(); 1127 final Set<Integer> originalSubIds = getSubscriptionIds(); 1128 final Set<Integer> originalAllowedUids = new ArraySet<>(mAllowedUids); 1129 clearAll(); 1130 if (0 != (originalCapabilities & (1 << NET_CAPABILITY_NOT_RESTRICTED))) { 1131 // If the test network is not restricted, then it is only allowed to declare some 1132 // specific transports. This is to minimize impact on running apps in case an app 1133 // run from the shell creates a test a network. 1134 mTransportTypes = 1135 (originalTransportTypes & UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS) 1136 | (1 << TRANSPORT_TEST); 1137 } else { 1138 // If the test network is restricted, then it may declare any transport. 1139 mTransportTypes = (originalTransportTypes | (1 << TRANSPORT_TEST)); 1140 } 1141 1142 if (hasSingleTransport(TRANSPORT_TEST)) { 1143 // SubIds are only allowed for Test Networks that only declare TRANSPORT_TEST. 1144 setSubscriptionIds(originalSubIds); 1145 } 1146 1147 mNetworkCapabilities = originalCapabilities & TEST_NETWORKS_ALLOWED_CAPABILITIES; 1148 if (!hasTransport(TRANSPORT_CELLULAR)) { 1149 mNetworkCapabilities |= 1150 (originalCapabilities & TEST_NETWORKS_EXTRA_ALLOWED_CAPABILITIES_ON_NON_CELL); 1151 } 1152 1153 mNetworkSpecifier = originalSpecifier; 1154 mSignalStrength = originalSignalStrength; 1155 mTransportInfo = originalTransportInfo; 1156 mAllowedUids.addAll(originalAllowedUids); 1157 1158 // Only retain the owner and administrator UIDs if they match the app registering the remote 1159 // caller that registered the network. 1160 if (originalOwnerUid == creatorUid) { 1161 setOwnerUid(creatorUid); 1162 } 1163 if (CollectionUtils.contains(originalAdministratorUids, creatorUid)) { 1164 setAdministratorUids(new int[] {creatorUid}); 1165 } 1166 // There is no need to clear the UIDs, they have already been cleared by clearAll() above. 1167 } 1168 1169 /** 1170 * Representing the transport type. Apps should generally not care about transport. A 1171 * request for a fast internet connection could be satisfied by a number of different 1172 * transports. If any are specified here it will be satisfied a Network that matches 1173 * any of them. If a caller doesn't care about the transport it should not specify any. 1174 */ 1175 private long mTransportTypes; 1176 1177 /** @hide */ 1178 @Retention(RetentionPolicy.SOURCE) 1179 @IntDef(prefix = { "TRANSPORT_" }, value = { 1180 TRANSPORT_CELLULAR, 1181 TRANSPORT_WIFI, 1182 TRANSPORT_BLUETOOTH, 1183 TRANSPORT_ETHERNET, 1184 TRANSPORT_VPN, 1185 TRANSPORT_WIFI_AWARE, 1186 TRANSPORT_LOWPAN, 1187 TRANSPORT_TEST, 1188 TRANSPORT_USB, 1189 TRANSPORT_THREAD, 1190 }) 1191 public @interface Transport { } 1192 1193 /** 1194 * Indicates this network uses a Cellular transport. 1195 */ 1196 public static final int TRANSPORT_CELLULAR = 0; 1197 1198 /** 1199 * Indicates this network uses a Wi-Fi transport. 1200 */ 1201 public static final int TRANSPORT_WIFI = 1; 1202 1203 /** 1204 * Indicates this network uses a Bluetooth transport. 1205 */ 1206 public static final int TRANSPORT_BLUETOOTH = 2; 1207 1208 /** 1209 * Indicates this network uses an Ethernet transport. 1210 */ 1211 public static final int TRANSPORT_ETHERNET = 3; 1212 1213 /** 1214 * Indicates this network uses a VPN transport. 1215 */ 1216 public static final int TRANSPORT_VPN = 4; 1217 1218 /** 1219 * Indicates this network uses a Wi-Fi Aware transport. 1220 */ 1221 public static final int TRANSPORT_WIFI_AWARE = 5; 1222 1223 /** 1224 * Indicates this network uses a LoWPAN transport. 1225 */ 1226 public static final int TRANSPORT_LOWPAN = 6; 1227 1228 /** 1229 * Indicates this network uses a Test-only virtual interface as a transport. 1230 * 1231 * @hide 1232 */ 1233 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 1234 public static final int TRANSPORT_TEST = 7; 1235 1236 /** 1237 * Indicates this network uses a USB transport. 1238 */ 1239 public static final int TRANSPORT_USB = 8; 1240 1241 /** 1242 * Indicates this network uses a Thread transport. 1243 */ 1244 public static final int TRANSPORT_THREAD = 9; 1245 1246 /** @hide */ 1247 public static final int MIN_TRANSPORT = TRANSPORT_CELLULAR; 1248 /** @hide */ 1249 public static final int MAX_TRANSPORT = TRANSPORT_THREAD; 1250 1251 private static final int ALL_VALID_TRANSPORTS; 1252 static { 1253 int transports = 0; 1254 for (int i = MIN_TRANSPORT; i <= MAX_TRANSPORT; ++i) { 1255 transports |= 1 << i; 1256 } 1257 ALL_VALID_TRANSPORTS = transports; 1258 } 1259 1260 /** @hide */ isValidTransport(@ransport int transportType)1261 public static boolean isValidTransport(@Transport int transportType) { 1262 return (MIN_TRANSPORT <= transportType) && (transportType <= MAX_TRANSPORT); 1263 } 1264 1265 private static final String[] TRANSPORT_NAMES = { 1266 "CELLULAR", 1267 "WIFI", 1268 "BLUETOOTH", 1269 "ETHERNET", 1270 "VPN", 1271 "WIFI_AWARE", 1272 "LOWPAN", 1273 "TEST", 1274 "USB", 1275 "THREAD", 1276 }; 1277 1278 /** 1279 * Allowed transports on an unrestricted test network (in addition to TRANSPORT_TEST). 1280 */ 1281 private static final long UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS = 1282 BitUtils.packBitList( 1283 TRANSPORT_TEST, 1284 // Test eth networks are created with EthernetManager#setIncludeTestInterfaces 1285 TRANSPORT_ETHERNET, 1286 // Test VPN networks can be created but their UID ranges must be empty. 1287 TRANSPORT_VPN); 1288 1289 /** 1290 * Adds the given transport type to this {@code NetworkCapability} instance. 1291 * Multiple transports may be applied. Note that when searching 1292 * for a network to satisfy a request, any listed in the request will satisfy the request. 1293 * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a 1294 * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network 1295 * to be selected. This is logically different than 1296 * {@code NetworkCapabilities.NET_CAPABILITY_*} listed above. 1297 * 1298 * @param transportType the transport type to be added. 1299 * @return This NetworkCapabilities instance, to facilitate chaining. 1300 * @hide 1301 */ addTransportType(@ransport int transportType)1302 public @NonNull NetworkCapabilities addTransportType(@Transport int transportType) { 1303 checkValidTransportType(transportType); 1304 mTransportTypes |= 1 << transportType; 1305 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking 1306 return this; 1307 } 1308 1309 /** 1310 * Removes (if found) the given transport from this {@code NetworkCapability} instance. 1311 * 1312 * @param transportType the transport type to be removed. 1313 * @return This NetworkCapabilities instance, to facilitate chaining. 1314 * @hide 1315 */ removeTransportType(@ransport int transportType)1316 public @NonNull NetworkCapabilities removeTransportType(@Transport int transportType) { 1317 checkValidTransportType(transportType); 1318 mTransportTypes &= ~(1 << transportType); 1319 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking 1320 return this; 1321 } 1322 1323 /** 1324 * Sets (or clears) the given transport on this {@link NetworkCapabilities} 1325 * instance. 1326 * 1327 * @hide 1328 */ setTransportType(@ransport int transportType, boolean value)1329 public @NonNull NetworkCapabilities setTransportType(@Transport int transportType, 1330 boolean value) { 1331 if (value) { 1332 addTransportType(transportType); 1333 } else { 1334 removeTransportType(transportType); 1335 } 1336 return this; 1337 } 1338 1339 /** 1340 * Gets all the transports set on this {@code NetworkCapability} instance. 1341 * 1342 * @return an array of transport type values for this instance. 1343 * @hide 1344 */ 1345 @SystemApi getTransportTypes()1346 @NonNull public @Transport int[] getTransportTypes() { 1347 return BitUtils.unpackBits(mTransportTypes); 1348 } 1349 1350 /** 1351 * Gets the transports as an int. Internal callers only. 1352 * 1353 * Prefer getTransportTypes/hasTransportType if not immediately collapsing back into a scalar. 1354 * 1355 * @return a long integer representing the transport types. 1356 * @hide 1357 */ getTransportTypesInternal()1358 public long getTransportTypesInternal() { 1359 return mTransportTypes; 1360 } 1361 1362 /** 1363 * Sets all the transports set on this {@code NetworkCapability} instance. 1364 * This overwrites any existing transports. 1365 * 1366 * @hide 1367 */ setTransportTypes(@ransport int[] transportTypes)1368 public void setTransportTypes(@Transport int[] transportTypes) { 1369 mTransportTypes = BitUtils.packBits(transportTypes); 1370 } 1371 1372 /** 1373 * Tests for the presence of a transport on this instance. 1374 * 1375 * @param transportType the transport type to be tested for. 1376 * @return {@code true} if set on this instance. 1377 */ hasTransport(@ransport int transportType)1378 public boolean hasTransport(@Transport int transportType) { 1379 return isValidTransport(transportType) && ((mTransportTypes & (1 << transportType)) != 0); 1380 } 1381 1382 /** 1383 * Returns true iff this NetworkCapabilities has the specified transport and no other. 1384 * @hide 1385 */ hasSingleTransport(@ransport int transportType)1386 public boolean hasSingleTransport(@Transport int transportType) { 1387 return mTransportTypes == (1 << transportType); 1388 } 1389 satisfiedByTransportTypes(NetworkCapabilities nc)1390 private boolean satisfiedByTransportTypes(NetworkCapabilities nc) { 1391 return ((this.mTransportTypes == 0) 1392 || ((this.mTransportTypes & nc.mTransportTypes) != 0)); 1393 } 1394 1395 /** @hide */ equalsTransportTypes(NetworkCapabilities nc)1396 public boolean equalsTransportTypes(NetworkCapabilities nc) { 1397 return (nc.mTransportTypes == this.mTransportTypes); 1398 } 1399 1400 /** 1401 * UID of the app that owns this network, or Process#INVALID_UID if none/unknown. 1402 * 1403 * <p>This field keeps track of the UID of the app that created this network and is in charge of 1404 * its lifecycle. This could be the UID of apps such as the Wifi network suggestor, the running 1405 * VPN, or Carrier Service app managing a cellular data connection. 1406 * 1407 * <p>For NetworkCapability instances being sent from ConnectivityService, this value MUST be 1408 * reset to Process.INVALID_UID unless all the following conditions are met: 1409 * 1410 * <p>The caller is the network owner, AND one of the following sets of requirements is met: 1411 * 1412 * <ol> 1413 * <li>The described Network is a VPN 1414 * </ol> 1415 * 1416 * <p>OR: 1417 * 1418 * <ol> 1419 * <li>The calling app is the network owner 1420 * <li>The calling app has the ACCESS_FINE_LOCATION permission granted 1421 * <li>The user's location toggle is on 1422 * </ol> 1423 * 1424 * This is because the owner UID is location-sensitive. The apps that request a network could 1425 * know where the device is if they can tell for sure the system has connected to the network 1426 * they requested. 1427 * 1428 * <p>This is populated by the network agents and for the NetworkCapabilities instance sent by 1429 * an app to the System Server, the value MUST be reset to Process.INVALID_UID by the system 1430 * server. 1431 */ 1432 private int mOwnerUid = Process.INVALID_UID; 1433 1434 /** 1435 * Set the UID of the owner app. 1436 * @hide 1437 */ setOwnerUid(final int uid)1438 public @NonNull NetworkCapabilities setOwnerUid(final int uid) { 1439 mOwnerUid = uid; 1440 return this; 1441 } 1442 1443 /** 1444 * Retrieves the UID of the app that owns this network. 1445 * 1446 * <p>For user privacy reasons, this field will only be populated if the following conditions 1447 * are met: 1448 * 1449 * <p>The caller is the network owner, AND one of the following sets of requirements is met: 1450 * 1451 * <ol> 1452 * <li>The described Network is a VPN 1453 * </ol> 1454 * 1455 * <p>OR: 1456 * 1457 * <ol> 1458 * <li>The calling app is the network owner 1459 * <li>The calling app has the ACCESS_FINE_LOCATION permission granted 1460 * <li>The user's location toggle is on 1461 * </ol> 1462 * 1463 * Instances of NetworkCapabilities sent to apps without the appropriate permissions will have 1464 * this field cleared out. 1465 * 1466 * <p> 1467 * This field will only be populated for VPN and wifi network suggestor apps (i.e using 1468 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}), and only for the 1469 * network they own. In the case of wifi network suggestors apps, this field is also location 1470 * sensitive, so the app needs to hold {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1471 * permission. If the app targets SDK version greater than or equal to 1472 * {@link Build.VERSION_CODES#S}, then they also need to use 1473 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} to get the info in their callback. If the 1474 * apps targets SDK version equal to {{@link Build.VERSION_CODES#R}, this field will always be 1475 * included. The app will be blamed for location access if this field is included. 1476 * </p> 1477 */ getOwnerUid()1478 public int getOwnerUid() { 1479 return mOwnerUid; 1480 } 1481 equalsOwnerUid(@onNull final NetworkCapabilities nc)1482 private boolean equalsOwnerUid(@NonNull final NetworkCapabilities nc) { 1483 return mOwnerUid == nc.mOwnerUid; 1484 } 1485 1486 /** 1487 * UIDs of packages that are administrators of this network, or empty if none. 1488 * 1489 * <p>This field tracks the UIDs of packages that have permission to manage this network. 1490 * 1491 * <p>Network owners will also be listed as administrators. 1492 * 1493 * <p>For NetworkCapability instances being sent from the System Server, this value MUST be 1494 * empty unless the destination is 1) the System Server, or 2) Telephony. In either case, the 1495 * receiving entity must have the ACCESS_FINE_LOCATION permission and target R+. 1496 * 1497 * <p>When received from an app in a NetworkRequest this is always cleared out by the system 1498 * server. This field is never used for matching NetworkRequests to NetworkAgents. 1499 */ 1500 @NonNull private int[] mAdministratorUids = new int[0]; 1501 1502 /** 1503 * Sets the int[] of UIDs that are administrators of this network. 1504 * 1505 * <p>UIDs included in administratorUids gain administrator privileges over this Network. 1506 * Examples of UIDs that should be included in administratorUids are: 1507 * 1508 * <ul> 1509 * <li>Carrier apps with privileges for the relevant subscription 1510 * <li>Active VPN apps 1511 * <li>Other application groups with a particular Network-related role 1512 * </ul> 1513 * 1514 * <p>In general, user-supplied networks (such as WiFi networks) do not have an administrator. 1515 * 1516 * <p>An app is granted owner privileges over Networks that it supplies. The owner UID MUST 1517 * always be included in administratorUids. 1518 * 1519 * <p>The administrator UIDs are set by network agents. 1520 * 1521 * @param administratorUids the UIDs to be set as administrators of this Network. 1522 * @throws IllegalArgumentException if duplicate UIDs are contained in administratorUids 1523 * @see #mAdministratorUids 1524 * @hide 1525 */ 1526 @NonNull setAdministratorUids(@onNull final int[] administratorUids)1527 public NetworkCapabilities setAdministratorUids(@NonNull final int[] administratorUids) { 1528 mAdministratorUids = Arrays.copyOf(administratorUids, administratorUids.length); 1529 Arrays.sort(mAdministratorUids); 1530 for (int i = 0; i < mAdministratorUids.length - 1; i++) { 1531 if (mAdministratorUids[i] >= mAdministratorUids[i + 1]) { 1532 throw new IllegalArgumentException("All administrator UIDs must be unique"); 1533 } 1534 } 1535 return this; 1536 } 1537 1538 /** 1539 * Retrieves the UIDs that are administrators of this Network. 1540 * 1541 * <p>This is only populated in NetworkCapabilities objects that come from network agents for 1542 * networks that are managed by specific apps on the system, such as carrier privileged apps or 1543 * wifi suggestion apps. This will include the network owner. 1544 * 1545 * @return the int[] of UIDs that are administrators of this Network 1546 * @see #mAdministratorUids 1547 * @hide 1548 */ 1549 @NonNull 1550 @SystemApi getAdministratorUids()1551 public int[] getAdministratorUids() { 1552 return Arrays.copyOf(mAdministratorUids, mAdministratorUids.length); 1553 } 1554 1555 /** 1556 * Tests if the set of administrator UIDs of this network is the same as that of the passed one. 1557 * 1558 * <p>The administrator UIDs must be in sorted order. 1559 * 1560 * <p>nc is assumed non-null. Else, NPE. 1561 * 1562 * @hide 1563 */ 1564 @VisibleForTesting(visibility = PRIVATE) equalsAdministratorUids(@onNull final NetworkCapabilities nc)1565 public boolean equalsAdministratorUids(@NonNull final NetworkCapabilities nc) { 1566 return Arrays.equals(mAdministratorUids, nc.mAdministratorUids); 1567 } 1568 1569 /** 1570 * Value indicating that link bandwidth is unspecified. 1571 * @hide 1572 */ 1573 public static final int LINK_BANDWIDTH_UNSPECIFIED = 0; 1574 1575 /** 1576 * Passive link bandwidth. This is a rough guide of the expected peak bandwidth 1577 * for the first hop on the given transport. It is not measured, but may take into account 1578 * link parameters (Radio technology, allocated channels, etc). 1579 */ 1580 private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 1581 private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 1582 1583 /** 1584 * Sets the upstream bandwidth for this network in Kbps. This always only refers to 1585 * the estimated first hop transport bandwidth. 1586 * <p> 1587 * @see Builder#setLinkUpstreamBandwidthKbps 1588 * 1589 * @param upKbps the estimated first hop upstream (device to network) bandwidth. 1590 * @hide 1591 */ setLinkUpstreamBandwidthKbps(int upKbps)1592 public @NonNull NetworkCapabilities setLinkUpstreamBandwidthKbps(int upKbps) { 1593 mLinkUpBandwidthKbps = upKbps; 1594 return this; 1595 } 1596 1597 /** 1598 * Retrieves the upstream bandwidth for this network in Kbps. This always only refers to 1599 * the estimated first hop transport bandwidth. 1600 * 1601 * @return The estimated first hop upstream (device to network) bandwidth. 1602 */ getLinkUpstreamBandwidthKbps()1603 public int getLinkUpstreamBandwidthKbps() { 1604 return mLinkUpBandwidthKbps; 1605 } 1606 1607 /** 1608 * Sets the downstream bandwidth for this network in Kbps. This always only refers to 1609 * the estimated first hop transport bandwidth. 1610 * <p> 1611 * @see Builder#setLinkUpstreamBandwidthKbps 1612 * 1613 * @param downKbps the estimated first hop downstream (network to device) bandwidth. 1614 * @hide 1615 */ setLinkDownstreamBandwidthKbps(int downKbps)1616 public @NonNull NetworkCapabilities setLinkDownstreamBandwidthKbps(int downKbps) { 1617 mLinkDownBandwidthKbps = downKbps; 1618 return this; 1619 } 1620 1621 /** 1622 * Retrieves the downstream bandwidth for this network in Kbps. This always only refers to 1623 * the estimated first hop transport bandwidth. 1624 * 1625 * @return The estimated first hop downstream (network to device) bandwidth. 1626 */ getLinkDownstreamBandwidthKbps()1627 public int getLinkDownstreamBandwidthKbps() { 1628 return mLinkDownBandwidthKbps; 1629 } 1630 satisfiedByLinkBandwidths(NetworkCapabilities nc)1631 private boolean satisfiedByLinkBandwidths(NetworkCapabilities nc) { 1632 return !(this.mLinkUpBandwidthKbps > nc.mLinkUpBandwidthKbps 1633 || this.mLinkDownBandwidthKbps > nc.mLinkDownBandwidthKbps); 1634 } equalsLinkBandwidths(NetworkCapabilities nc)1635 private boolean equalsLinkBandwidths(NetworkCapabilities nc) { 1636 return (this.mLinkUpBandwidthKbps == nc.mLinkUpBandwidthKbps 1637 && this.mLinkDownBandwidthKbps == nc.mLinkDownBandwidthKbps); 1638 } 1639 /** @hide */ minBandwidth(int a, int b)1640 public static int minBandwidth(int a, int b) { 1641 if (a == LINK_BANDWIDTH_UNSPECIFIED) { 1642 return b; 1643 } else if (b == LINK_BANDWIDTH_UNSPECIFIED) { 1644 return a; 1645 } else { 1646 return Math.min(a, b); 1647 } 1648 } 1649 /** @hide */ maxBandwidth(int a, int b)1650 public static int maxBandwidth(int a, int b) { 1651 return Math.max(a, b); 1652 } 1653 1654 private NetworkSpecifier mNetworkSpecifier = null; 1655 private TransportInfo mTransportInfo = null; 1656 1657 /** 1658 * Sets the optional bearer specific network specifier. 1659 * This has no meaning if a single transport is also not specified, so calling 1660 * this without a single transport set will generate an exception, as will 1661 * subsequently adding or removing transports after this is set. 1662 * </p> 1663 * 1664 * @param networkSpecifier A concrete, parcelable framework class that extends 1665 * NetworkSpecifier. 1666 * @return This NetworkCapabilities instance, to facilitate chaining. 1667 * @hide 1668 */ setNetworkSpecifier( @onNull NetworkSpecifier networkSpecifier)1669 public @NonNull NetworkCapabilities setNetworkSpecifier( 1670 @NonNull NetworkSpecifier networkSpecifier) { 1671 if (networkSpecifier != null 1672 // Transport can be test, or test + a single other transport 1673 && mTransportTypes != (1L << TRANSPORT_TEST) 1674 && Long.bitCount(mTransportTypes & ~(1L << TRANSPORT_TEST)) != 1) { 1675 throw new IllegalStateException("Must have a single non-test transport specified to " 1676 + "use setNetworkSpecifier"); 1677 } 1678 1679 mNetworkSpecifier = networkSpecifier; 1680 1681 return this; 1682 } 1683 1684 /** 1685 * Sets the optional transport specific information. 1686 * 1687 * @param transportInfo A concrete, parcelable framework class that extends 1688 * {@link TransportInfo}. 1689 * @return This NetworkCapabilities instance, to facilitate chaining. 1690 * @hide 1691 */ setTransportInfo(@onNull TransportInfo transportInfo)1692 public @NonNull NetworkCapabilities setTransportInfo(@NonNull TransportInfo transportInfo) { 1693 mTransportInfo = transportInfo; 1694 return this; 1695 } 1696 1697 /** 1698 * Gets the optional bearer specific network specifier. May be {@code null} if not set. 1699 * 1700 * @return The optional {@link NetworkSpecifier} specifying the bearer specific network 1701 * specifier or {@code null}. 1702 */ getNetworkSpecifier()1703 public @Nullable NetworkSpecifier getNetworkSpecifier() { 1704 return mNetworkSpecifier; 1705 } 1706 1707 /** 1708 * Returns a transport-specific information container. The application may cast this 1709 * container to a concrete sub-class based on its knowledge of the network request. The 1710 * application should be able to deal with a {@code null} return value or an invalid case, 1711 * e.g. use {@code instanceof} operator to verify expected type. 1712 * 1713 * @return A concrete implementation of the {@link TransportInfo} class or null if not 1714 * available for the network. 1715 */ getTransportInfo()1716 @Nullable public TransportInfo getTransportInfo() { 1717 return mTransportInfo; 1718 } 1719 satisfiedBySpecifier(NetworkCapabilities nc)1720 private boolean satisfiedBySpecifier(NetworkCapabilities nc) { 1721 return mNetworkSpecifier == null || mNetworkSpecifier.canBeSatisfiedBy(nc.mNetworkSpecifier) 1722 || nc.mNetworkSpecifier instanceof MatchAllNetworkSpecifier; 1723 } 1724 equalsSpecifier(NetworkCapabilities nc)1725 private boolean equalsSpecifier(NetworkCapabilities nc) { 1726 return Objects.equals(mNetworkSpecifier, nc.mNetworkSpecifier); 1727 } 1728 equalsTransportInfo(NetworkCapabilities nc)1729 private boolean equalsTransportInfo(NetworkCapabilities nc) { 1730 return Objects.equals(mTransportInfo, nc.mTransportInfo); 1731 } 1732 1733 /** 1734 * Magic value that indicates no signal strength provided. A request specifying this value is 1735 * always satisfied. 1736 */ 1737 public static final int SIGNAL_STRENGTH_UNSPECIFIED = Integer.MIN_VALUE; 1738 1739 /** 1740 * Signal strength. This is a signed integer, and higher values indicate better signal. 1741 * The exact units are bearer-dependent. For example, Wi-Fi uses RSSI. 1742 */ 1743 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) 1744 private int mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED; 1745 1746 /** 1747 * Sets the signal strength. This is a signed integer, with higher values indicating a stronger 1748 * signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same RSSI units 1749 * reported by wifi code. 1750 * <p> 1751 * Note that when used to register a network callback, this specifies the minimum acceptable 1752 * signal strength. When received as the state of an existing network it specifies the current 1753 * value. A value of {@link #SIGNAL_STRENGTH_UNSPECIFIED} means no value when received and has 1754 * no effect when requesting a callback. 1755 * 1756 * @param signalStrength the bearer-specific signal strength. 1757 * @hide 1758 */ setSignalStrength(int signalStrength)1759 public @NonNull NetworkCapabilities setSignalStrength(int signalStrength) { 1760 mSignalStrength = signalStrength; 1761 return this; 1762 } 1763 1764 /** 1765 * Returns {@code true} if this object specifies a signal strength. 1766 * 1767 * @hide 1768 */ 1769 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) hasSignalStrength()1770 public boolean hasSignalStrength() { 1771 return mSignalStrength > SIGNAL_STRENGTH_UNSPECIFIED; 1772 } 1773 1774 /** 1775 * Retrieves the signal strength. 1776 * 1777 * @return The bearer-specific signal strength. 1778 */ getSignalStrength()1779 public int getSignalStrength() { 1780 return mSignalStrength; 1781 } 1782 satisfiedBySignalStrength(NetworkCapabilities nc)1783 private boolean satisfiedBySignalStrength(NetworkCapabilities nc) { 1784 return this.mSignalStrength <= nc.mSignalStrength; 1785 } 1786 equalsSignalStrength(NetworkCapabilities nc)1787 private boolean equalsSignalStrength(NetworkCapabilities nc) { 1788 return this.mSignalStrength == nc.mSignalStrength; 1789 } 1790 1791 /** 1792 * List of UIDs this network applies to. No restriction if null. 1793 * <p> 1794 * For networks, mUids represent the list of network this applies to, and null means this 1795 * network applies to all UIDs. 1796 * For requests, mUids is the list of UIDs this network MUST apply to to match ; ALL UIDs 1797 * must be included in a network so that they match. As an exception to the general rule, 1798 * a null mUids field for requests mean "no requirements" rather than what the general rule 1799 * would suggest ("must apply to all UIDs") : this is because this has shown to be what users 1800 * of this API expect in practice. A network that must match all UIDs can still be 1801 * expressed with a set ranging the entire set of possible UIDs. 1802 * <p> 1803 * mUids is typically (and at this time, only) used by VPN. This network is only available to 1804 * the UIDs in this list, and it is their default network. Apps in this list that wish to 1805 * bypass the VPN can do so iff the VPN app allows them to or if they are privileged. If this 1806 * member is null, then the network is not restricted by app UID. If it's an empty list, then 1807 * it means nobody can use it. 1808 * As a special exception, the app managing this network (as identified by its UID stored in 1809 * mOwnerUid) can always see this network. This is embodied by a special check in 1810 * satisfiedByUids. That still does not mean the network necessarily <strong>applies</strong> 1811 * to the app that manages it as determined by #appliesToUid. 1812 * <p> 1813 * Please note that in principle a single app can be associated with multiple UIDs because 1814 * each app will have a different UID when it's run as a different (macro-)user. A single 1815 * macro user can only have a single active VPN app at any given time however. 1816 * <p> 1817 * Also please be aware this class does not try to enforce any normalization on this. Callers 1818 * can only alter the UIDs by setting them wholesale : this class does not provide any utility 1819 * to add or remove individual UIDs or ranges. If callers have any normalization needs on 1820 * their own (like requiring sortedness or no overlap) they need to enforce it 1821 * themselves. Some of the internal methods also assume this is normalized as in no adjacent 1822 * or overlapping ranges are present. 1823 * 1824 * @hide 1825 */ 1826 private ArraySet<UidRange> mUids = null; 1827 1828 /** 1829 * Convenience method to set the UIDs this network applies to to a single UID. 1830 * @hide 1831 */ setSingleUid(int uid)1832 public @NonNull NetworkCapabilities setSingleUid(int uid) { 1833 mUids = new ArraySet<>(1); 1834 mUids.add(new UidRange(uid, uid)); 1835 return this; 1836 } 1837 1838 /** 1839 * Set the list of UIDs this network applies to. 1840 * This makes a copy of the set so that callers can't modify it after the call. 1841 * @hide 1842 */ setUids(@ullable Set<Range<Integer>> uids)1843 public @NonNull NetworkCapabilities setUids(@Nullable Set<Range<Integer>> uids) { 1844 mUids = UidRange.fromIntRanges(uids); 1845 return this; 1846 } 1847 1848 /** 1849 * Get the list of UIDs this network applies to. 1850 * This returns a copy of the set so that callers can't modify the original object. 1851 * 1852 * @return the list of UIDs this network applies to. If {@code null}, then the network applies 1853 * to all UIDs. 1854 * @hide 1855 */ 1856 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 1857 @SuppressLint("NullableCollection") getUids()1858 public @Nullable Set<Range<Integer>> getUids() { 1859 return UidRange.toIntRanges(mUids); 1860 } 1861 1862 /** 1863 * Get the list of UIDs this network applies to. 1864 * This returns a copy of the set so that callers can't modify the original object. 1865 * @hide 1866 */ getUidRanges()1867 public @Nullable Set<UidRange> getUidRanges() { 1868 if (mUids == null) return null; 1869 1870 return new ArraySet<>(mUids); 1871 } 1872 1873 /** 1874 * Test whether this network applies to this UID. 1875 * @hide 1876 */ appliesToUid(int uid)1877 public boolean appliesToUid(int uid) { 1878 if (null == mUids) return true; 1879 for (UidRange range : mUids) { 1880 if (range.contains(uid)) { 1881 return true; 1882 } 1883 } 1884 return false; 1885 } 1886 1887 /** 1888 * Tests if the set of UIDs that this network applies to is the same as the passed network. 1889 * <p> 1890 * This test only checks whether equal range objects are in both sets. It will 1891 * return false if the ranges are not exactly the same, even if the covered UIDs 1892 * are for an equivalent result. 1893 * <p> 1894 * Note that this method is not very optimized, which is fine as long as it's not used very 1895 * often. 1896 * <p> 1897 * nc is assumed nonnull, else NPE. 1898 * 1899 * @hide 1900 */ 1901 @VisibleForTesting equalsUids(@onNull NetworkCapabilities nc)1902 public boolean equalsUids(@NonNull NetworkCapabilities nc) { 1903 return UidRange.hasSameUids(nc.mUids, mUids); 1904 } 1905 1906 /** 1907 * Test whether the passed NetworkCapabilities satisfies the UIDs this capabilities require. 1908 * 1909 * This method is called on the NetworkCapabilities embedded in a request with the 1910 * capabilities of an available network. It checks whether all the UIDs from this listen 1911 * (representing the UIDs that must have access to the network) are satisfied by the UIDs 1912 * in the passed nc (representing the UIDs that this network is available to). 1913 * <p> 1914 * As a special exception, the UID that created the passed network (as represented by its 1915 * mOwnerUid field) always satisfies a NetworkRequest requiring it (of LISTEN 1916 * or REQUEST types alike), even if the network does not apply to it. That is so a VPN app 1917 * can see its own network when it listens for it. 1918 * <p> 1919 * nc is assumed nonnull. Else, NPE. 1920 * @see #appliesToUid 1921 * @hide 1922 */ satisfiedByUids(@onNull NetworkCapabilities nc)1923 public boolean satisfiedByUids(@NonNull NetworkCapabilities nc) { 1924 if (null == nc.mUids || null == mUids) return true; // The network satisfies everything. 1925 for (UidRange requiredRange : mUids) { 1926 if (requiredRange.contains(nc.mOwnerUid)) return true; 1927 if (!nc.appliesToUidRange(requiredRange)) { 1928 return false; 1929 } 1930 } 1931 return true; 1932 } 1933 1934 /** 1935 * Returns whether this network applies to the passed ranges. 1936 * This assumes that to apply, the passed range has to be entirely contained 1937 * within one of the ranges this network applies to. If the ranges are not normalized, 1938 * this method may return false even though all required UIDs are covered because no 1939 * single range contained them all. 1940 * @hide 1941 */ 1942 @VisibleForTesting appliesToUidRange(@onNull UidRange requiredRange)1943 public boolean appliesToUidRange(@NonNull UidRange requiredRange) { 1944 if (null == mUids) return true; 1945 for (UidRange uidRange : mUids) { 1946 if (uidRange.containsRange(requiredRange)) { 1947 return true; 1948 } 1949 } 1950 return false; 1951 } 1952 1953 /** 1954 * List of UIDs that can always access this network. 1955 * <p> 1956 * UIDs in this list have access to this network, even if the network doesn't have the 1957 * {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the 1958 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission. 1959 * This is only useful for restricted networks. For non-restricted networks it has no effect. 1960 * <p> 1961 * This is disallowed in {@link NetworkRequest}, and can only be set by network agents. Network 1962 * agents also have restrictions on how they can set these ; they can only back a public 1963 * Android API. As such, Ethernet agents can set this when backing the per-UID access API, and 1964 * Telephony can set exactly one UID which has to match the manager app for the associated 1965 * subscription. Failure to comply with these rules will see this member cleared. 1966 * <p> 1967 * This member is never null, but can be empty. 1968 * @hide 1969 */ 1970 @NonNull 1971 private final ArraySet<Integer> mAllowedUids = new ArraySet<>(); 1972 1973 /** 1974 * Set the list of UIDs that can always access this network. 1975 * @param uids 1976 * @hide 1977 */ setAllowedUids(@onNull final Set<Integer> uids)1978 public void setAllowedUids(@NonNull final Set<Integer> uids) { 1979 // could happen with nc.set(nc), cheaper than always making a defensive copy 1980 if (uids == mAllowedUids) return; 1981 1982 Objects.requireNonNull(uids); 1983 mAllowedUids.clear(); 1984 mAllowedUids.addAll(uids); 1985 } 1986 1987 /** 1988 * The list of UIDs that can always access this network. 1989 * 1990 * The UIDs in this list can always access this network, even if it is restricted and 1991 * the UID doesn't hold the USE_RESTRICTED_NETWORKS permission. This is defined by the 1992 * network agent in charge of creating the network. 1993 * 1994 * The UIDs are only visible to network factories and the system server, since the system 1995 * server makes sure to redact them before sending a NetworkCapabilities to a process 1996 * that doesn't hold the permission. 1997 * 1998 * @hide 1999 */ 2000 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 2001 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) getAllowedUids()2002 public @NonNull Set<Integer> getAllowedUids() { 2003 return new ArraySet<>(mAllowedUids); 2004 } 2005 2006 /** @hide */ 2007 // For internal clients that know what they are doing and need to avoid the performance hit 2008 // of the defensive copy. getAllowedUidsNoCopy()2009 public @NonNull ArraySet<Integer> getAllowedUidsNoCopy() { 2010 return mAllowedUids; 2011 } 2012 2013 /** 2014 * Test whether this UID has special permission to access this network, as per mAllowedUids. 2015 * @hide 2016 */ 2017 // TODO : should this be "doesUidHaveAccess" and check the USE_RESTRICTED_NETWORKS permission ? isUidWithAccess(int uid)2018 public boolean isUidWithAccess(int uid) { 2019 return mAllowedUids.contains(uid); 2020 } 2021 2022 /** 2023 * @return whether any UID is in the list of access UIDs 2024 * @hide 2025 */ hasAllowedUids()2026 public boolean hasAllowedUids() { 2027 return !mAllowedUids.isEmpty(); 2028 } 2029 equalsAllowedUids(@onNull NetworkCapabilities other)2030 private boolean equalsAllowedUids(@NonNull NetworkCapabilities other) { 2031 return mAllowedUids.equals(other.mAllowedUids); 2032 } 2033 2034 /** 2035 * The SSID of the network, or null if not applicable or unknown. 2036 * <p> 2037 * This is filled in by wifi code. 2038 * @hide 2039 */ 2040 private String mSSID; 2041 2042 /** 2043 * Sets the SSID of this network. 2044 * @hide 2045 */ setSSID(@ullable String ssid)2046 public @NonNull NetworkCapabilities setSSID(@Nullable String ssid) { 2047 mSSID = ssid; 2048 return this; 2049 } 2050 2051 /** 2052 * Gets the SSID of this network, or null if none or unknown. 2053 * @hide 2054 */ 2055 @SystemApi getSsid()2056 public @Nullable String getSsid() { 2057 return mSSID; 2058 } 2059 2060 /** 2061 * Tests if the SSID of this network is the same as the SSID of the passed network. 2062 * @hide 2063 */ equalsSSID(@onNull NetworkCapabilities nc)2064 public boolean equalsSSID(@NonNull NetworkCapabilities nc) { 2065 return Objects.equals(mSSID, nc.mSSID); 2066 } 2067 2068 /** 2069 * Check if the SSID requirements of this object are matched by the passed object. 2070 * @hide 2071 */ satisfiedBySSID(@onNull NetworkCapabilities nc)2072 public boolean satisfiedBySSID(@NonNull NetworkCapabilities nc) { 2073 return mSSID == null || mSSID.equals(nc.mSSID); 2074 } 2075 2076 /** 2077 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}. 2078 * 2079 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 2080 * @param onlyImmutable if {@code true}, do not consider mutable requirements such as link 2081 * bandwidth, signal strength, or validation / captive portal status. 2082 * 2083 * @hide 2084 */ satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable)2085 private boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { 2086 return (nc != null 2087 && satisfiedByNetCapabilities(nc, onlyImmutable) 2088 && satisfiedByTransportTypes(nc) 2089 && (onlyImmutable || satisfiedByLinkBandwidths(nc)) 2090 && satisfiedBySpecifier(nc) 2091 && satisfiedByEnterpriseCapabilitiesId(nc) 2092 && (onlyImmutable || satisfiedBySignalStrength(nc)) 2093 && (onlyImmutable || satisfiedByUids(nc)) 2094 && (onlyImmutable || satisfiedBySSID(nc)) 2095 && (onlyImmutable || satisfiedByRequestor(nc)) 2096 && (onlyImmutable || satisfiedBySubscriptionIds(nc))); 2097 } 2098 2099 /** 2100 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}. 2101 * 2102 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 2103 * 2104 * @hide 2105 */ 2106 @SystemApi satisfiedByNetworkCapabilities(@ullable NetworkCapabilities nc)2107 public boolean satisfiedByNetworkCapabilities(@Nullable NetworkCapabilities nc) { 2108 return satisfiedByNetworkCapabilities(nc, false); 2109 } 2110 2111 /** 2112 * Check if our immutable requirements are satisfied by the given {@code NetworkCapabilities}. 2113 * 2114 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 2115 * 2116 * @hide 2117 */ satisfiedByImmutableNetworkCapabilities(@ullable NetworkCapabilities nc)2118 public boolean satisfiedByImmutableNetworkCapabilities(@Nullable NetworkCapabilities nc) { 2119 return satisfiedByNetworkCapabilities(nc, true); 2120 } 2121 2122 /** 2123 * Checks that our immutable capabilities are the same as those of the given 2124 * {@code NetworkCapabilities} and return a String describing any difference. 2125 * The returned String is empty if there is no difference. 2126 * 2127 * @hide 2128 */ describeImmutableDifferences(@ullable NetworkCapabilities that)2129 public String describeImmutableDifferences(@Nullable NetworkCapabilities that) { 2130 if (that == null) { 2131 return "other NetworkCapabilities was null"; 2132 } 2133 2134 StringJoiner joiner = new StringJoiner(", "); 2135 2136 // Ignore NOT_METERED being added or removed as it is effectively dynamic. http://b/63326103 2137 // TODO: properly support NOT_METERED as a mutable and requestable capability. 2138 final long mask = ~MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_NOT_METERED); 2139 long oldImmutableCapabilities = this.mNetworkCapabilities & mask; 2140 long newImmutableCapabilities = that.mNetworkCapabilities & mask; 2141 if (oldImmutableCapabilities != newImmutableCapabilities) { 2142 String before = capabilityNamesOf(BitUtils.unpackBits( 2143 oldImmutableCapabilities)); 2144 String after = capabilityNamesOf(BitUtils.unpackBits( 2145 newImmutableCapabilities)); 2146 joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after)); 2147 } 2148 2149 if (!equalsSpecifier(that)) { 2150 NetworkSpecifier before = this.getNetworkSpecifier(); 2151 NetworkSpecifier after = that.getNetworkSpecifier(); 2152 joiner.add(String.format("specifier changed: %s -> %s", before, after)); 2153 } 2154 2155 if (!equalsTransportTypes(that)) { 2156 String before = transportNamesOf(this.getTransportTypes()); 2157 String after = transportNamesOf(that.getTransportTypes()); 2158 joiner.add(String.format("transports changed: %s -> %s", before, after)); 2159 } 2160 2161 return joiner.toString(); 2162 } 2163 2164 /** 2165 * Returns a short but human-readable string of updates from an older set of capabilities. 2166 * @param old the old capabilities to diff from 2167 * @return a string fit for logging differences, or null if no differences. 2168 * this never returns the empty string. See BitUtils#describeDifferences. 2169 * @hide 2170 */ 2171 @Nullable describeCapsDifferencesFrom(@ullable final NetworkCapabilities old)2172 public String describeCapsDifferencesFrom(@Nullable final NetworkCapabilities old) { 2173 final long oldCaps = null == old ? 0 : old.mNetworkCapabilities; 2174 return describeDifferences(oldCaps, mNetworkCapabilities, 2175 NetworkCapabilities::capabilityNameOf); 2176 } 2177 2178 /** 2179 * Checks that our requestable capabilities are the same as those of the given 2180 * {@code NetworkCapabilities}. 2181 * 2182 * @hide 2183 */ equalRequestableCapabilities(@ullable NetworkCapabilities nc)2184 public boolean equalRequestableCapabilities(@Nullable NetworkCapabilities nc) { 2185 if (nc == null) return false; 2186 return (equalsNetCapabilitiesRequestable(nc) 2187 && equalsTransportTypes(nc) 2188 && equalsSpecifier(nc)); 2189 } 2190 2191 @Override equals(@ullable Object obj)2192 public boolean equals(@Nullable Object obj) { 2193 if (obj == null || (obj instanceof NetworkCapabilities == false)) return false; 2194 NetworkCapabilities that = (NetworkCapabilities) obj; 2195 return equalsNetCapabilities(that) 2196 && equalsTransportTypes(that) 2197 && equalsLinkBandwidths(that) 2198 && equalsSignalStrength(that) 2199 && equalsSpecifier(that) 2200 && equalsTransportInfo(that) 2201 && equalsUids(that) 2202 && equalsAllowedUids(that) 2203 && equalsSSID(that) 2204 && equalsOwnerUid(that) 2205 && equalsPrivateDnsBroken(that) 2206 && equalsRequestor(that) 2207 && equalsAdministratorUids(that) 2208 && equalsSubscriptionIds(that) 2209 && equalsUnderlyingNetworks(that) 2210 && equalsEnterpriseCapabilitiesId(that); 2211 } 2212 2213 @Override hashCode()2214 public int hashCode() { 2215 return (int) (mNetworkCapabilities & 0xFFFFFFFF) 2216 + ((int) (mNetworkCapabilities >> 32) * 3) 2217 + ((int) (mForbiddenNetworkCapabilities & 0xFFFFFFFF) * 5) 2218 + ((int) (mForbiddenNetworkCapabilities >> 32) * 7) 2219 + ((int) (mTransportTypes & 0xFFFFFFFF) * 11) 2220 + ((int) (mTransportTypes >> 32) * 13) 2221 + mLinkUpBandwidthKbps * 17 2222 + mLinkDownBandwidthKbps * 19 2223 + Objects.hashCode(mNetworkSpecifier) * 23 2224 + mSignalStrength * 29 2225 + mOwnerUid * 31 2226 + Objects.hashCode(mUids) * 37 2227 + Objects.hashCode(mAllowedUids) * 41 2228 + Objects.hashCode(mSSID) * 43 2229 + Objects.hashCode(mTransportInfo) * 47 2230 + Objects.hashCode(mPrivateDnsBroken) * 53 2231 + Objects.hashCode(mRequestorUid) * 59 2232 + Objects.hashCode(mRequestorPackageName) * 61 2233 + Arrays.hashCode(mAdministratorUids) * 67 2234 + Objects.hashCode(mSubIds) * 71 2235 + Objects.hashCode(mUnderlyingNetworks) * 73 2236 + mEnterpriseId * 79; 2237 } 2238 2239 @Override describeContents()2240 public int describeContents() { 2241 return 0; 2242 } 2243 writeParcelableArraySet(Parcel in, @Nullable ArraySet<T> val, int flags)2244 private <T extends Parcelable> void writeParcelableArraySet(Parcel in, 2245 @Nullable ArraySet<T> val, int flags) { 2246 final int size = (val != null) ? val.size() : -1; 2247 in.writeInt(size); 2248 for (int i = 0; i < size; i++) { 2249 in.writeParcelable(val.valueAt(i), flags); 2250 } 2251 } 2252 2253 @Override writeToParcel(Parcel dest, int flags)2254 public void writeToParcel(Parcel dest, int flags) { 2255 dest.writeLong(mNetworkCapabilities & ALL_VALID_CAPABILITIES); 2256 dest.writeLong(mForbiddenNetworkCapabilities & ALL_VALID_CAPABILITIES); 2257 dest.writeLong(mTransportTypes & ALL_VALID_TRANSPORTS); 2258 dest.writeInt(mLinkUpBandwidthKbps); 2259 dest.writeInt(mLinkDownBandwidthKbps); 2260 dest.writeParcelable((Parcelable) mNetworkSpecifier, flags); 2261 dest.writeParcelable((Parcelable) mTransportInfo, flags); 2262 dest.writeInt(mSignalStrength); 2263 writeParcelableArraySet(dest, mUids, flags); 2264 dest.writeIntArray(CollectionUtils.toIntArray(mAllowedUids)); 2265 dest.writeString(mSSID); 2266 dest.writeBoolean(mPrivateDnsBroken); 2267 dest.writeIntArray(getAdministratorUids()); 2268 dest.writeInt(mOwnerUid); 2269 dest.writeInt(mRequestorUid); 2270 dest.writeString(mRequestorPackageName); 2271 dest.writeIntArray(CollectionUtils.toIntArray(mSubIds)); 2272 dest.writeTypedList(mUnderlyingNetworks); 2273 dest.writeInt(mEnterpriseId & ALL_VALID_ENTERPRISE_IDS); 2274 } 2275 2276 public static final @android.annotation.NonNull Creator<NetworkCapabilities> CREATOR = 2277 new Creator<>() { 2278 @Override 2279 public NetworkCapabilities createFromParcel(Parcel in) { 2280 NetworkCapabilities netCap = new NetworkCapabilities(); 2281 // Validate the unparceled data, in case the parceling party was malicious. 2282 netCap.mNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES; 2283 netCap.mForbiddenNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES; 2284 netCap.mTransportTypes = in.readLong() & ALL_VALID_TRANSPORTS; 2285 netCap.mLinkUpBandwidthKbps = in.readInt(); 2286 netCap.mLinkDownBandwidthKbps = in.readInt(); 2287 netCap.mNetworkSpecifier = in.readParcelable(null); 2288 netCap.mTransportInfo = in.readParcelable(null); 2289 netCap.mSignalStrength = in.readInt(); 2290 netCap.mUids = readParcelableArraySet(in, null /* ClassLoader, null for default */); 2291 final int[] allowedUids = in.createIntArray(); 2292 netCap.mAllowedUids.ensureCapacity(allowedUids.length); 2293 for (int uid : allowedUids) { 2294 netCap.mAllowedUids.add(uid); 2295 } 2296 netCap.mSSID = in.readString(); 2297 netCap.mPrivateDnsBroken = in.readBoolean(); 2298 netCap.setAdministratorUids(in.createIntArray()); 2299 netCap.mOwnerUid = in.readInt(); 2300 netCap.mRequestorUid = in.readInt(); 2301 netCap.mRequestorPackageName = in.readString(); 2302 netCap.mSubIds = new ArraySet<>(); 2303 final int[] subIdInts = Objects.requireNonNull(in.createIntArray()); 2304 for (int i = 0; i < subIdInts.length; i++) { 2305 netCap.mSubIds.add(subIdInts[i]); 2306 } 2307 netCap.setUnderlyingNetworks(in.createTypedArrayList(Network.CREATOR)); 2308 netCap.mEnterpriseId = in.readInt() & ALL_VALID_ENTERPRISE_IDS; 2309 return netCap; 2310 } 2311 @Override 2312 public NetworkCapabilities[] newArray(int size) { 2313 return new NetworkCapabilities[size]; 2314 } 2315 2316 private @Nullable <T extends Parcelable> ArraySet<T> readParcelableArraySet(Parcel in, 2317 @Nullable ClassLoader loader) { 2318 final int size = in.readInt(); 2319 if (size < 0) { 2320 return null; 2321 } 2322 final ArraySet<T> result = new ArraySet<>(size); 2323 for (int i = 0; i < size; i++) { 2324 final T value = in.readParcelable(loader); 2325 result.add(value); 2326 } 2327 return result; 2328 } 2329 }; 2330 2331 @Override toString()2332 public @NonNull String toString() { 2333 final StringBuilder sb = new StringBuilder("["); 2334 if (0 != mTransportTypes) { 2335 sb.append(" Transports: "); 2336 appendStringRepresentationOfBitMaskToStringBuilder(sb, mTransportTypes, 2337 NetworkCapabilities::transportNameOf, "|"); 2338 } 2339 if (0 != mNetworkCapabilities) { 2340 sb.append(" Capabilities: "); 2341 appendStringRepresentationOfBitMaskToStringBuilder(sb, mNetworkCapabilities, 2342 NetworkCapabilities::capabilityNameOf, "&"); 2343 } 2344 if (0 != mForbiddenNetworkCapabilities) { 2345 sb.append(" Forbidden: "); 2346 appendStringRepresentationOfBitMaskToStringBuilder(sb, mForbiddenNetworkCapabilities, 2347 NetworkCapabilities::capabilityNameOf, "&"); 2348 } 2349 if (mLinkUpBandwidthKbps > 0) { 2350 sb.append(" LinkUpBandwidth>=").append(mLinkUpBandwidthKbps).append("Kbps"); 2351 } 2352 if (mLinkDownBandwidthKbps > 0) { 2353 sb.append(" LinkDnBandwidth>=").append(mLinkDownBandwidthKbps).append("Kbps"); 2354 } 2355 if (mNetworkSpecifier != null) { 2356 sb.append(" Specifier: <").append(mNetworkSpecifier).append(">"); 2357 } 2358 if (mTransportInfo != null) { 2359 sb.append(" TransportInfo: <").append(mTransportInfo).append(">"); 2360 } 2361 if (hasSignalStrength()) { 2362 sb.append(" SignalStrength: ").append(mSignalStrength); 2363 } 2364 2365 if (null != mUids) { 2366 if ((1 == mUids.size()) && (mUids.valueAt(0).count() == 1)) { 2367 sb.append(" Uid: ").append(mUids.valueAt(0).start); 2368 } else { 2369 sb.append(" Uids: <").append(mUids).append(">"); 2370 } 2371 } 2372 2373 if (hasAllowedUids()) { 2374 sb.append(" AllowedUids: <").append(mAllowedUids).append(">"); 2375 } 2376 2377 if (mOwnerUid != Process.INVALID_UID) { 2378 sb.append(" OwnerUid: ").append(mOwnerUid); 2379 } 2380 2381 if (mAdministratorUids != null && mAdministratorUids.length != 0) { 2382 sb.append(" AdminUids: ").append(Arrays.toString(mAdministratorUids)); 2383 } 2384 2385 if (mRequestorUid != Process.INVALID_UID) { 2386 sb.append(" RequestorUid: ").append(mRequestorUid); 2387 } 2388 2389 if (mRequestorPackageName != null) { 2390 sb.append(" RequestorPkg: ").append(mRequestorPackageName); 2391 } 2392 2393 if (null != mSSID) { 2394 sb.append(" SSID: ").append(mSSID); 2395 } 2396 2397 if (mPrivateDnsBroken) { 2398 sb.append(" PrivateDnsBroken"); 2399 } 2400 2401 if (!mSubIds.isEmpty()) { 2402 sb.append(" SubscriptionIds: ").append(mSubIds); 2403 } 2404 2405 if (0 != mEnterpriseId) { 2406 sb.append(" EnterpriseId: "); 2407 appendStringRepresentationOfBitMaskToStringBuilder(sb, mEnterpriseId, 2408 NetworkCapabilities::enterpriseIdNameOf, "&"); 2409 } 2410 2411 sb.append(" UnderlyingNetworks: "); 2412 if (mUnderlyingNetworks != null) { 2413 sb.append("["); 2414 final StringJoiner joiner = new StringJoiner(","); 2415 for (int i = 0; i < mUnderlyingNetworks.size(); i++) { 2416 joiner.add(mUnderlyingNetworks.get(i).toString()); 2417 } 2418 sb.append(joiner.toString()); 2419 sb.append("]"); 2420 } else { 2421 sb.append("Null"); 2422 } 2423 2424 sb.append("]"); 2425 return sb.toString(); 2426 } 2427 2428 /** 2429 * @hide 2430 */ capabilityNamesOf(@ullable @etCapability int[] capabilities)2431 public static @NonNull String capabilityNamesOf(@Nullable @NetCapability int[] capabilities) { 2432 StringJoiner joiner = new StringJoiner("|"); 2433 if (capabilities != null) { 2434 for (int c : capabilities) { 2435 joiner.add(capabilityNameOf(c)); 2436 } 2437 } 2438 return joiner.toString(); 2439 } 2440 2441 /** 2442 * @hide 2443 */ capabilityNameOf(@etCapability int capability)2444 public static @NonNull String capabilityNameOf(@NetCapability int capability) { 2445 switch (capability) { 2446 case NET_CAPABILITY_MMS: return "MMS"; 2447 case NET_CAPABILITY_SUPL: return "SUPL"; 2448 case NET_CAPABILITY_DUN: return "DUN"; 2449 case NET_CAPABILITY_FOTA: return "FOTA"; 2450 case NET_CAPABILITY_IMS: return "IMS"; 2451 case NET_CAPABILITY_CBS: return "CBS"; 2452 case NET_CAPABILITY_WIFI_P2P: return "WIFI_P2P"; 2453 case NET_CAPABILITY_IA: return "IA"; 2454 case NET_CAPABILITY_RCS: return "RCS"; 2455 case NET_CAPABILITY_XCAP: return "XCAP"; 2456 case NET_CAPABILITY_EIMS: return "EIMS"; 2457 case NET_CAPABILITY_NOT_METERED: return "NOT_METERED"; 2458 case NET_CAPABILITY_INTERNET: return "INTERNET"; 2459 case NET_CAPABILITY_NOT_RESTRICTED: return "NOT_RESTRICTED"; 2460 case NET_CAPABILITY_TRUSTED: return "TRUSTED"; 2461 case NET_CAPABILITY_NOT_VPN: return "NOT_VPN"; 2462 case NET_CAPABILITY_VALIDATED: return "VALIDATED"; 2463 case NET_CAPABILITY_CAPTIVE_PORTAL: return "CAPTIVE_PORTAL"; 2464 case NET_CAPABILITY_NOT_ROAMING: return "NOT_ROAMING"; 2465 case NET_CAPABILITY_FOREGROUND: return "FOREGROUND"; 2466 case NET_CAPABILITY_NOT_CONGESTED: return "NOT_CONGESTED"; 2467 case NET_CAPABILITY_NOT_SUSPENDED: return "NOT_SUSPENDED"; 2468 case NET_CAPABILITY_OEM_PAID: return "OEM_PAID"; 2469 case NET_CAPABILITY_MCX: return "MCX"; 2470 case NET_CAPABILITY_PARTIAL_CONNECTIVITY: return "PARTIAL_CONNECTIVITY"; 2471 case NET_CAPABILITY_TEMPORARILY_NOT_METERED: return "TEMPORARILY_NOT_METERED"; 2472 case NET_CAPABILITY_OEM_PRIVATE: return "OEM_PRIVATE"; 2473 case NET_CAPABILITY_VEHICLE_INTERNAL: return "VEHICLE_INTERNAL"; 2474 case NET_CAPABILITY_NOT_VCN_MANAGED: return "NOT_VCN_MANAGED"; 2475 case NET_CAPABILITY_ENTERPRISE: return "ENTERPRISE"; 2476 case NET_CAPABILITY_VSIM: return "VSIM"; 2477 case NET_CAPABILITY_BIP: return "BIP"; 2478 case NET_CAPABILITY_HEAD_UNIT: return "HEAD_UNIT"; 2479 case NET_CAPABILITY_MMTEL: return "MMTEL"; 2480 case NET_CAPABILITY_PRIORITIZE_LATENCY: return "PRIORITIZE_LATENCY"; 2481 case NET_CAPABILITY_PRIORITIZE_BANDWIDTH: return "PRIORITIZE_BANDWIDTH"; 2482 default: return Integer.toString(capability); 2483 } 2484 } 2485 enterpriseIdNameOf( @etCapability int capability)2486 private static @NonNull String enterpriseIdNameOf( 2487 @NetCapability int capability) { 2488 return Integer.toString(capability); 2489 } 2490 2491 /** 2492 * @hide 2493 */ 2494 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) transportNamesOf(@ullable @ransport int[] types)2495 public static @NonNull String transportNamesOf(@Nullable @Transport int[] types) { 2496 StringJoiner joiner = new StringJoiner("|"); 2497 if (types != null) { 2498 for (int t : types) { 2499 joiner.add(transportNameOf(t)); 2500 } 2501 } 2502 return joiner.toString(); 2503 } 2504 2505 /** 2506 * @hide 2507 */ transportNameOf(@ransport int transport)2508 public static @NonNull String transportNameOf(@Transport int transport) { 2509 if (!isValidTransport(transport)) { 2510 return "UNKNOWN"; 2511 } 2512 return TRANSPORT_NAMES[transport]; 2513 } 2514 checkValidTransportType(@ransport int transport)2515 private static void checkValidTransportType(@Transport int transport) { 2516 if (!isValidTransport(transport)) { 2517 throw new IllegalArgumentException("Invalid TransportType " + transport); 2518 } 2519 } 2520 isValidCapability(@etworkCapabilities.NetCapability int capability)2521 private static boolean isValidCapability(@NetworkCapabilities.NetCapability int capability) { 2522 return capability >= MIN_NET_CAPABILITY && capability <= MAX_NET_CAPABILITY; 2523 } 2524 checkValidCapability(@etworkCapabilities.NetCapability int capability)2525 private static void checkValidCapability(@NetworkCapabilities.NetCapability int capability) { 2526 if (!isValidCapability(capability)) { 2527 throw new IllegalArgumentException("NetworkCapability " + capability + " out of range"); 2528 } 2529 } 2530 isValidEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)2531 private static boolean isValidEnterpriseId( 2532 @NetworkCapabilities.EnterpriseId int enterpriseId) { 2533 return enterpriseId >= NET_ENTERPRISE_ID_1 2534 && enterpriseId <= NET_ENTERPRISE_ID_5; 2535 } 2536 checkValidEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)2537 private static void checkValidEnterpriseId( 2538 @NetworkCapabilities.EnterpriseId int enterpriseId) { 2539 if (!isValidEnterpriseId(enterpriseId)) { 2540 throw new IllegalArgumentException("enterprise capability identifier " 2541 + enterpriseId + " is out of range"); 2542 } 2543 } 2544 2545 /** 2546 * Check if this {@code NetworkCapability} instance is metered. 2547 * 2548 * @return {@code true} if {@code NET_CAPABILITY_NOT_METERED} is not set on this instance. 2549 * @hide 2550 */ isMetered()2551 public boolean isMetered() { 2552 return !hasCapability(NET_CAPABILITY_NOT_METERED); 2553 } 2554 2555 /** 2556 * Check if private dns is broken. 2557 * 2558 * @return {@code true} if private DNS is broken on this network. 2559 * @hide 2560 */ 2561 @SystemApi isPrivateDnsBroken()2562 public boolean isPrivateDnsBroken() { 2563 return mPrivateDnsBroken; 2564 } 2565 2566 /** 2567 * Set mPrivateDnsBroken to true when private dns is broken. 2568 * 2569 * @param broken the status of private DNS to be set. 2570 * @hide 2571 */ setPrivateDnsBroken(boolean broken)2572 public void setPrivateDnsBroken(boolean broken) { 2573 mPrivateDnsBroken = broken; 2574 } 2575 equalsPrivateDnsBroken(NetworkCapabilities nc)2576 private boolean equalsPrivateDnsBroken(NetworkCapabilities nc) { 2577 return mPrivateDnsBroken == nc.mPrivateDnsBroken; 2578 } 2579 2580 /** 2581 * Set the UID of the app making the request. 2582 * 2583 * For instances of NetworkCapabilities representing a request, sets the 2584 * UID of the app making the request. For a network created by the system, 2585 * sets the UID of the only app whose requests can match this network. 2586 * This can be set to {@link Process#INVALID_UID} if there is no such app, 2587 * or if this instance of NetworkCapabilities is about to be sent to a 2588 * party that should not learn about this. 2589 * 2590 * @param uid UID of the app. 2591 * @hide 2592 */ setRequestorUid(int uid)2593 public @NonNull NetworkCapabilities setRequestorUid(int uid) { 2594 mRequestorUid = uid; 2595 return this; 2596 } 2597 2598 /** 2599 * Returns the UID of the app making the request. 2600 * 2601 * For a NetworkRequest being made by an app, contains the app's UID. For a network 2602 * created by the system, contains the UID of the only app whose requests can match 2603 * this network, or {@link Process#INVALID_UID} if none or if the 2604 * caller does not have permission to learn about this. 2605 * 2606 * @return the uid of the app making the request. 2607 * @hide 2608 */ getRequestorUid()2609 public int getRequestorUid() { 2610 return mRequestorUid; 2611 } 2612 2613 /** 2614 * Set the package name of the app making the request. 2615 * 2616 * For instances of NetworkCapabilities representing a request, sets the 2617 * package name of the app making the request. For a network created by the system, 2618 * sets the package name of the only app whose requests can match this network. 2619 * This can be set to null if there is no such app, or if this instance of 2620 * NetworkCapabilities is about to be sent to a party that should not learn about this. 2621 * 2622 * @param packageName package name of the app. 2623 * @hide 2624 */ setRequestorPackageName(@onNull String packageName)2625 public @NonNull NetworkCapabilities setRequestorPackageName(@NonNull String packageName) { 2626 mRequestorPackageName = packageName; 2627 return this; 2628 } 2629 2630 /** 2631 * Returns the package name of the app making the request. 2632 * 2633 * For a NetworkRequest being made by an app, contains the app's package name. For a 2634 * network created by the system, contains the package name of the only app whose 2635 * requests can match this network, or null if none or if the caller does not have 2636 * permission to learn about this. 2637 * 2638 * @return the package name of the app making the request. 2639 * @hide 2640 */ 2641 @Nullable getRequestorPackageName()2642 public String getRequestorPackageName() { 2643 return mRequestorPackageName; 2644 } 2645 2646 /** 2647 * Set the uid and package name of the app causing this network to exist. 2648 * 2649 * See {@link #setRequestorUid} and {@link #setRequestorPackageName} 2650 * 2651 * @param uid UID of the app. 2652 * @param packageName package name of the app. 2653 * @hide 2654 */ setRequestorUidAndPackageName( int uid, @NonNull String packageName)2655 public @NonNull NetworkCapabilities setRequestorUidAndPackageName( 2656 int uid, @NonNull String packageName) { 2657 return setRequestorUid(uid).setRequestorPackageName(packageName); 2658 } 2659 2660 /** 2661 * Test whether the passed NetworkCapabilities satisfies the requestor restrictions of this 2662 * capabilities. 2663 * 2664 * This method is called on the NetworkCapabilities embedded in a request with the 2665 * capabilities of an available network. If the available network, sets a specific 2666 * requestor (by uid and optionally package name), then this will only match a request from the 2667 * same app. If either of the capabilities have an unset uid or package name, then it matches 2668 * everything. 2669 * <p> 2670 * nc is assumed nonnull. Else, NPE. 2671 */ satisfiedByRequestor(NetworkCapabilities nc)2672 private boolean satisfiedByRequestor(NetworkCapabilities nc) { 2673 // No uid set, matches everything. 2674 if (mRequestorUid == Process.INVALID_UID || nc.mRequestorUid == Process.INVALID_UID) { 2675 return true; 2676 } 2677 // uids don't match. 2678 if (mRequestorUid != nc.mRequestorUid) return false; 2679 // No package names set, matches everything 2680 if (null == nc.mRequestorPackageName || null == mRequestorPackageName) return true; 2681 // check for package name match. 2682 return TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName); 2683 } 2684 equalsRequestor(NetworkCapabilities nc)2685 private boolean equalsRequestor(NetworkCapabilities nc) { 2686 return mRequestorUid == nc.mRequestorUid 2687 && TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName); 2688 } 2689 2690 /** 2691 * Set of the subscription IDs that identifies the network or request, empty if none. 2692 */ 2693 @NonNull 2694 private ArraySet<Integer> mSubIds = new ArraySet<>(); 2695 2696 /** 2697 * Sets the subscription ID set that associated to this network or request. 2698 * 2699 * @hide 2700 */ 2701 @NonNull setSubscriptionIds(@onNull Set<Integer> subIds)2702 public NetworkCapabilities setSubscriptionIds(@NonNull Set<Integer> subIds) { 2703 mSubIds = new ArraySet(Objects.requireNonNull(subIds)); 2704 return this; 2705 } 2706 2707 /** 2708 * Gets the subscription ID set that associated to this network or request. 2709 * 2710 * <p>Instances of NetworkCapabilities will only have this field populated by the system if the 2711 * receiver holds the NETWORK_FACTORY permission. In all other cases, it will be the empty set. 2712 * 2713 * @return 2714 * @hide 2715 */ 2716 @NonNull 2717 @SystemApi getSubscriptionIds()2718 public Set<Integer> getSubscriptionIds() { 2719 return new ArraySet<>(mSubIds); 2720 } 2721 2722 /** 2723 * Tests if the subscription ID set of this network is the same as that of the passed one. 2724 */ equalsSubscriptionIds(@onNull NetworkCapabilities nc)2725 private boolean equalsSubscriptionIds(@NonNull NetworkCapabilities nc) { 2726 return Objects.equals(mSubIds, nc.mSubIds); 2727 } 2728 2729 /** 2730 * Check if the subscription ID set requirements of this object are matched by the passed one. 2731 * If specified in the request, the passed one need to have at least one subId and at least 2732 * one of them needs to be in the request set. 2733 */ satisfiedBySubscriptionIds(@onNull NetworkCapabilities nc)2734 private boolean satisfiedBySubscriptionIds(@NonNull NetworkCapabilities nc) { 2735 if (mSubIds.isEmpty()) return true; 2736 if (nc.mSubIds.isEmpty()) return false; 2737 for (final Integer subId : nc.mSubIds) { 2738 if (mSubIds.contains(subId)) return true; 2739 } 2740 return false; 2741 } 2742 2743 /** 2744 * Returns a bitmask of all the applicable redactions (based on the permissions held by the 2745 * receiving app) to be performed on this object. 2746 * 2747 * @return bitmask of redactions applicable on this instance. 2748 * @hide 2749 */ getApplicableRedactions()2750 public @RedactionType long getApplicableRedactions() { 2751 // Currently, there are no fields redacted in NetworkCapabilities itself, so we just 2752 // passthrough the redactions required by the embedded TransportInfo. If this changes 2753 // in the future, modify this method. 2754 if (mTransportInfo == null) { 2755 return NetworkCapabilities.REDACT_NONE; 2756 } 2757 return mTransportInfo.getApplicableRedactions(); 2758 } 2759 removeDefaultCapabilites()2760 private NetworkCapabilities removeDefaultCapabilites() { 2761 mNetworkCapabilities &= ~DEFAULT_CAPABILITIES; 2762 return this; 2763 } 2764 2765 /** 2766 * Builder class for NetworkCapabilities. 2767 * 2768 * This class is mainly for {@link NetworkAgent} instances to use. Many fields in 2769 * the built class require holding a signature permission to use - mostly 2770 * {@link android.Manifest.permission.NETWORK_FACTORY}, but refer to the specific 2771 * description of each setter. As this class lives entirely in app space it does not 2772 * enforce these restrictions itself but the system server clears out the relevant 2773 * fields when receiving a NetworkCapabilities object from a caller without the 2774 * appropriate permission. 2775 * 2776 * Apps don't use this builder directly. Instead, they use {@link NetworkRequest} via 2777 * its builder object. 2778 * 2779 * @hide 2780 */ 2781 @SystemApi 2782 public static final class Builder { 2783 private final NetworkCapabilities mCaps; 2784 2785 /** 2786 * Creates a new Builder to construct NetworkCapabilities objects. 2787 */ Builder()2788 public Builder() { 2789 mCaps = new NetworkCapabilities(); 2790 } 2791 2792 /** 2793 * Creates a new Builder of NetworkCapabilities from an existing instance. 2794 */ Builder(@onNull final NetworkCapabilities nc)2795 public Builder(@NonNull final NetworkCapabilities nc) { 2796 Objects.requireNonNull(nc); 2797 mCaps = new NetworkCapabilities(nc); 2798 } 2799 2800 /** 2801 * Creates a new Builder without the default capabilities. 2802 */ 2803 @NonNull withoutDefaultCapabilities()2804 public static Builder withoutDefaultCapabilities() { 2805 final NetworkCapabilities nc = new NetworkCapabilities(); 2806 nc.removeDefaultCapabilites(); 2807 return new Builder(nc); 2808 } 2809 2810 /** 2811 * Adds the given transport type. 2812 * 2813 * Multiple transports may be added. Note that when searching for a network to satisfy a 2814 * request, satisfying any of the transports listed in the request will satisfy the request. 2815 * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a 2816 * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network 2817 * to be selected. This is logically different than 2818 * {@code NetworkCapabilities.NET_CAPABILITY_*}. Also note that multiple networks with the 2819 * same transport type may be active concurrently. 2820 * 2821 * @param transportType the transport type to be added or removed. 2822 * @return this builder 2823 */ 2824 @NonNull addTransportType(@ransport int transportType)2825 public Builder addTransportType(@Transport int transportType) { 2826 checkValidTransportType(transportType); 2827 mCaps.addTransportType(transportType); 2828 return this; 2829 } 2830 2831 /** 2832 * Removes the given transport type. 2833 * 2834 * @see #addTransportType 2835 * 2836 * @param transportType the transport type to be added or removed. 2837 * @return this builder 2838 */ 2839 @NonNull removeTransportType(@ransport int transportType)2840 public Builder removeTransportType(@Transport int transportType) { 2841 checkValidTransportType(transportType); 2842 mCaps.removeTransportType(transportType); 2843 return this; 2844 } 2845 2846 /** 2847 * Adds the given capability. 2848 * 2849 * @param capability the capability 2850 * @return this builder 2851 */ 2852 @NonNull addCapability(@etCapability final int capability)2853 public Builder addCapability(@NetCapability final int capability) { 2854 mCaps.setCapability(capability, true); 2855 return this; 2856 } 2857 2858 /** 2859 * Removes the given capability. 2860 * 2861 * @param capability the capability 2862 * @return this builder 2863 */ 2864 @NonNull removeCapability(@etCapability final int capability)2865 public Builder removeCapability(@NetCapability final int capability) { 2866 mCaps.setCapability(capability, false); 2867 return this; 2868 } 2869 2870 /** 2871 * Adds the given enterprise capability identifier. 2872 * Note that when searching for a network to satisfy a request, all capabilities identifier 2873 * requested must be satisfied. Enterprise capability identifier is applicable only 2874 * for NET_CAPABILITY_ENTERPRISE capability 2875 * 2876 * @param enterpriseId enterprise capability identifier. 2877 * 2878 * @return this builder 2879 */ 2880 @NonNull addEnterpriseId( @nterpriseId int enterpriseId)2881 public Builder addEnterpriseId( 2882 @EnterpriseId int enterpriseId) { 2883 mCaps.addEnterpriseId(enterpriseId); 2884 return this; 2885 } 2886 2887 /** 2888 * Removes the given enterprise capability identifier. Enterprise capability identifier is 2889 * applicable only for NET_CAPABILITY_ENTERPRISE capability 2890 * 2891 * @param enterpriseId the enterprise capability identifier 2892 * @return this builder 2893 */ 2894 @NonNull removeEnterpriseId( @nterpriseId int enterpriseId)2895 public Builder removeEnterpriseId( 2896 @EnterpriseId int enterpriseId) { 2897 mCaps.removeEnterpriseId(enterpriseId); 2898 return this; 2899 } 2900 2901 /** 2902 * Sets the owner UID. 2903 * 2904 * The default value is {@link Process#INVALID_UID}. Pass this value to reset. 2905 * 2906 * Note: for security the system will clear out this field when received from a 2907 * non-privileged source. 2908 * 2909 * @param ownerUid the owner UID 2910 * @return this builder 2911 */ 2912 @NonNull 2913 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setOwnerUid(final int ownerUid)2914 public Builder setOwnerUid(final int ownerUid) { 2915 mCaps.setOwnerUid(ownerUid); 2916 return this; 2917 } 2918 2919 /** 2920 * Sets the list of UIDs that are administrators of this network. 2921 * 2922 * <p>UIDs included in administratorUids gain administrator privileges over this 2923 * Network. Examples of UIDs that should be included in administratorUids are: 2924 * <ul> 2925 * <li>Carrier apps with privileges for the relevant subscription 2926 * <li>Active VPN apps 2927 * <li>Other application groups with a particular Network-related role 2928 * </ul> 2929 * 2930 * <p>In general, user-supplied networks (such as WiFi networks) do not have 2931 * administrators. 2932 * 2933 * <p>An app is granted owner privileges over Networks that it supplies. The owner 2934 * UID MUST always be included in administratorUids. 2935 * 2936 * The default value is the empty array. Pass an empty array to reset. 2937 * 2938 * Note: for security the system will clear out this field when received from a 2939 * non-privileged source, such as an app using reflection to call this or 2940 * mutate the member in the built object. 2941 * 2942 * @param administratorUids the UIDs to be set as administrators of this Network. 2943 * @return this builder 2944 */ 2945 @NonNull 2946 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setAdministratorUids(@onNull final int[] administratorUids)2947 public Builder setAdministratorUids(@NonNull final int[] administratorUids) { 2948 Objects.requireNonNull(administratorUids); 2949 mCaps.setAdministratorUids(administratorUids); 2950 return this; 2951 } 2952 2953 /** 2954 * Sets the upstream bandwidth of the link. 2955 * 2956 * Sets the upstream bandwidth for this network in Kbps. This always only refers to 2957 * the estimated first hop transport bandwidth. 2958 * <p> 2959 * Note that when used to request a network, this specifies the minimum acceptable. 2960 * When received as the state of an existing network this specifies the typical 2961 * first hop bandwidth expected. This is never measured, but rather is inferred 2962 * from technology type and other link parameters. It could be used to differentiate 2963 * between very slow 1xRTT cellular links and other faster networks or even between 2964 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between 2965 * fast backhauls and slow backhauls. 2966 * 2967 * @param upKbps the estimated first hop upstream (device to network) bandwidth. 2968 * @return this builder 2969 */ 2970 @NonNull setLinkUpstreamBandwidthKbps(final int upKbps)2971 public Builder setLinkUpstreamBandwidthKbps(final int upKbps) { 2972 mCaps.setLinkUpstreamBandwidthKbps(upKbps); 2973 return this; 2974 } 2975 2976 /** 2977 * Sets the downstream bandwidth for this network in Kbps. This always only refers to 2978 * the estimated first hop transport bandwidth. 2979 * <p> 2980 * Note that when used to request a network, this specifies the minimum acceptable. 2981 * When received as the state of an existing network this specifies the typical 2982 * first hop bandwidth expected. This is never measured, but rather is inferred 2983 * from technology type and other link parameters. It could be used to differentiate 2984 * between very slow 1xRTT cellular links and other faster networks or even between 2985 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between 2986 * fast backhauls and slow backhauls. 2987 * 2988 * @param downKbps the estimated first hop downstream (network to device) bandwidth. 2989 * @return this builder 2990 */ 2991 @NonNull setLinkDownstreamBandwidthKbps(final int downKbps)2992 public Builder setLinkDownstreamBandwidthKbps(final int downKbps) { 2993 mCaps.setLinkDownstreamBandwidthKbps(downKbps); 2994 return this; 2995 } 2996 2997 /** 2998 * Sets the optional bearer specific network specifier. 2999 * This has no meaning if a single transport is also not specified, so calling 3000 * this without a single transport set will generate an exception, as will 3001 * subsequently adding or removing transports after this is set. 3002 * </p> 3003 * 3004 * @param specifier a concrete, parcelable framework class that extends NetworkSpecifier, 3005 * or null to clear it. 3006 * @return this builder 3007 */ 3008 @NonNull setNetworkSpecifier(@ullable final NetworkSpecifier specifier)3009 public Builder setNetworkSpecifier(@Nullable final NetworkSpecifier specifier) { 3010 mCaps.setNetworkSpecifier(specifier); 3011 return this; 3012 } 3013 3014 /** 3015 * Sets the optional transport specific information. 3016 * 3017 * @param info A concrete, parcelable framework class that extends {@link TransportInfo}, 3018 * or null to clear it. 3019 * @return this builder 3020 */ 3021 @NonNull setTransportInfo(@ullable final TransportInfo info)3022 public Builder setTransportInfo(@Nullable final TransportInfo info) { 3023 mCaps.setTransportInfo(info); 3024 return this; 3025 } 3026 3027 /** 3028 * Sets the signal strength. This is a signed integer, with higher values indicating a 3029 * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the 3030 * same RSSI units reported by wifi code. 3031 * <p> 3032 * Note that when used to register a network callback, this specifies the minimum 3033 * acceptable signal strength. When received as the state of an existing network it 3034 * specifies the current value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means 3035 * no value when received and has no effect when requesting a callback. 3036 * 3037 * Note: for security the system will throw if it receives a NetworkRequest where 3038 * the underlying NetworkCapabilities has this member set from a source that does 3039 * not hold the {@link android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP} 3040 * permission. Apps with this permission can use this indirectly through 3041 * {@link android.net.NetworkRequest}. 3042 * 3043 * @param signalStrength the bearer-specific signal strength. 3044 * @return this builder 3045 */ 3046 @NonNull 3047 @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP) setSignalStrength(final int signalStrength)3048 public Builder setSignalStrength(final int signalStrength) { 3049 mCaps.setSignalStrength(signalStrength); 3050 return this; 3051 } 3052 3053 /** 3054 * Sets the SSID of this network. 3055 * 3056 * Note: for security the system will clear out this field when received from a 3057 * non-privileged source, like an app using reflection to set this. 3058 * 3059 * @param ssid the SSID, or null to clear it. 3060 * @return this builder 3061 */ 3062 @NonNull 3063 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setSsid(@ullable final String ssid)3064 public Builder setSsid(@Nullable final String ssid) { 3065 mCaps.setSSID(ssid); 3066 return this; 3067 } 3068 3069 /** 3070 * Set the uid of the app causing this network to exist. 3071 * 3072 * Note: for security the system will clear out this field when received from a 3073 * non-privileged source. 3074 * 3075 * @param uid UID of the app. 3076 * @return this builder 3077 */ 3078 @NonNull 3079 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setRequestorUid(final int uid)3080 public Builder setRequestorUid(final int uid) { 3081 mCaps.setRequestorUid(uid); 3082 return this; 3083 } 3084 3085 /** 3086 * Set the package name of the app causing this network to exist. 3087 * 3088 * Note: for security the system will clear out this field when received from a 3089 * non-privileged source. 3090 * 3091 * @param packageName package name of the app, or null to clear it. 3092 * @return this builder 3093 */ 3094 @NonNull 3095 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setRequestorPackageName(@ullable final String packageName)3096 public Builder setRequestorPackageName(@Nullable final String packageName) { 3097 mCaps.setRequestorPackageName(packageName); 3098 return this; 3099 } 3100 3101 /** 3102 * Set the subscription ID set. 3103 * 3104 * <p>SubIds are populated in NetworkCapability instances from the system only for callers 3105 * that hold the NETWORK_FACTORY permission. Similarly, the system will reject any 3106 * NetworkRequests filed with a non-empty set of subIds unless the caller holds the 3107 * NETWORK_FACTORY permission. 3108 * 3109 * @param subIds a set that represent the subscription IDs. Empty if clean up. 3110 * @return this builder. 3111 * @hide 3112 */ 3113 @NonNull 3114 @SystemApi setSubscriptionIds(@onNull final Set<Integer> subIds)3115 public Builder setSubscriptionIds(@NonNull final Set<Integer> subIds) { 3116 mCaps.setSubscriptionIds(subIds); 3117 return this; 3118 } 3119 3120 /** 3121 * Set the list of UIDs this network applies to. 3122 * 3123 * @param uids the list of UIDs this network applies to, or {@code null} if this network 3124 * applies to all UIDs. 3125 * @return this builder 3126 * @hide 3127 */ 3128 @NonNull 3129 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) setUids(@ullable Set<Range<Integer>> uids)3130 public Builder setUids(@Nullable Set<Range<Integer>> uids) { 3131 mCaps.setUids(uids); 3132 return this; 3133 } 3134 3135 /** 3136 * Set a list of UIDs that can always access this network 3137 * <p> 3138 * Provide a list of UIDs that can access this network even if the network doesn't have the 3139 * {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the 3140 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission. 3141 * <p> 3142 * This is disallowed in {@link NetworkRequest}, and can only be set by 3143 * {@link NetworkAgent}s, who hold the 3144 * {@link android.Manifest.permission.NETWORK_FACTORY} permission. 3145 * Network agents also have restrictions on how they can set these ; they can only back 3146 * a public Android API. As such, Ethernet agents can set this when backing the per-UID 3147 * access API, and Telephony can set exactly one UID which has to match the manager app for 3148 * the associated subscription. Failure to comply with these rules will see this member 3149 * cleared. 3150 * <p> 3151 * These UIDs are only visible to network factories and the system server, since the system 3152 * server makes sure to redact them before sending a {@link NetworkCapabilities} instance 3153 * to a process that doesn't hold the {@link android.Manifest.permission.NETWORK_FACTORY} 3154 * permission. 3155 * <p> 3156 * This list cannot be null, but it can be empty to mean that no UID without the 3157 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission 3158 * can access this network. 3159 * 3160 * @param uids the list of UIDs that can always access this network 3161 * @return this builder 3162 * @hide 3163 */ 3164 @NonNull 3165 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) 3166 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setAllowedUids(@onNull Set<Integer> uids)3167 public Builder setAllowedUids(@NonNull Set<Integer> uids) { 3168 Objects.requireNonNull(uids); 3169 mCaps.setAllowedUids(uids); 3170 return this; 3171 } 3172 3173 /** 3174 * Set the underlying networks of this network. 3175 * 3176 * <p>This API is mainly for {@link NetworkAgent}s who hold 3177 * {@link android.Manifest.permission.NETWORK_FACTORY} to set its underlying networks. 3178 * 3179 * <p>The underlying networks are only visible for the receiver who has one of 3180 * {@link android.Manifest.permission.NETWORK_FACTORY}, 3181 * {@link android.Manifest.permission.NETWORK_SETTINGS} and 3182 * {@link NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}. 3183 * If the receiver doesn't have required permissions, the field will be cleared before 3184 * sending to the caller.</p> 3185 * 3186 * @param networks The underlying networks of this network. 3187 */ 3188 @NonNull 3189 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) setUnderlyingNetworks(@ullable List<Network> networks)3190 public Builder setUnderlyingNetworks(@Nullable List<Network> networks) { 3191 mCaps.setUnderlyingNetworks(networks); 3192 return this; 3193 } 3194 3195 /** 3196 * Builds the instance of the capabilities. 3197 * 3198 * @return the built instance of NetworkCapabilities. 3199 */ 3200 @NonNull build()3201 public NetworkCapabilities build() { 3202 if (mCaps.getOwnerUid() != Process.INVALID_UID) { 3203 if (!CollectionUtils.contains(mCaps.getAdministratorUids(), mCaps.getOwnerUid())) { 3204 throw new IllegalStateException("The owner UID must be included in " 3205 + " administrator UIDs."); 3206 } 3207 } 3208 3209 if ((mCaps.getEnterpriseIds().length != 0) 3210 && !mCaps.hasCapability(NET_CAPABILITY_ENTERPRISE)) { 3211 throw new IllegalStateException("Enterprise capability identifier is applicable" 3212 + " only with ENTERPRISE capability."); 3213 } 3214 return new NetworkCapabilities(mCaps); 3215 } 3216 } 3217 }