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