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