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