NetworkCapabilities.java revision 0a5570d49df7d438b618616e439192f3c216cfe8
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 17package android.net; 18 19import android.annotation.IntDef; 20import android.annotation.SystemApi; 21import android.net.ConnectivityManager.NetworkCallback; 22import android.os.Parcel; 23import android.os.Parcelable; 24import android.util.ArraySet; 25import android.util.proto.ProtoOutputStream; 26 27import com.android.internal.annotations.VisibleForTesting; 28import com.android.internal.util.BitUtils; 29import com.android.internal.util.Preconditions; 30 31import java.lang.annotation.Retention; 32import java.lang.annotation.RetentionPolicy; 33import java.util.Objects; 34import java.util.Set; 35import java.util.StringJoiner; 36 37/** 38 * Representation of the capabilities of an active network. Instances are 39 * typically obtained through 40 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} 41 * or {@link ConnectivityManager#getNetworkCapabilities(Network)}. 42 * <p> 43 * This replaces the old {@link ConnectivityManager#TYPE_MOBILE} method of 44 * network selection. Rather than indicate a need for Wi-Fi because an 45 * application needs high bandwidth and risk obsolescence when a new, fast 46 * network appears (like LTE), the application should specify it needs high 47 * bandwidth. Similarly if an application needs an unmetered network for a bulk 48 * transfer it can specify that rather than assuming all cellular based 49 * connections are metered and all Wi-Fi based connections are not. 50 */ 51public final class NetworkCapabilities implements Parcelable { 52 private static final String TAG = "NetworkCapabilities"; 53 private static final int INVALID_UID = -1; 54 55 /** 56 * @hide 57 */ 58 public NetworkCapabilities() { 59 clearAll(); 60 mNetworkCapabilities = DEFAULT_CAPABILITIES; 61 } 62 63 public NetworkCapabilities(NetworkCapabilities nc) { 64 if (nc != null) { 65 mNetworkCapabilities = nc.mNetworkCapabilities; 66 mTransportTypes = nc.mTransportTypes; 67 mLinkUpBandwidthKbps = nc.mLinkUpBandwidthKbps; 68 mLinkDownBandwidthKbps = nc.mLinkDownBandwidthKbps; 69 mNetworkSpecifier = nc.mNetworkSpecifier; 70 mSignalStrength = nc.mSignalStrength; 71 mUids = nc.mUids; 72 mEstablishingVpnAppUid = nc.mEstablishingVpnAppUid; 73 mUnwantedNetworkCapabilities = nc.mUnwantedNetworkCapabilities; 74 } 75 } 76 77 /** 78 * Completely clears the contents of this object, removing even the capabilities that are set 79 * by default when the object is constructed. 80 * @hide 81 */ 82 public void clearAll() { 83 mNetworkCapabilities = mTransportTypes = mUnwantedNetworkCapabilities = 0; 84 mLinkUpBandwidthKbps = mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 85 mNetworkSpecifier = null; 86 mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED; 87 mUids = null; 88 mEstablishingVpnAppUid = INVALID_UID; 89 } 90 91 /** 92 * Represents the network's capabilities. If any are specified they will be satisfied 93 * by any Network that matches all of them. 94 */ 95 private long mNetworkCapabilities; 96 97 /** 98 * If any capabilities specified here they must not exist in the matching Network. 99 */ 100 private long mUnwantedNetworkCapabilities; 101 102 /** @hide */ 103 @Retention(RetentionPolicy.SOURCE) 104 @IntDef(prefix = { "NET_CAPABILITY_" }, value = { 105 NET_CAPABILITY_MMS, 106 NET_CAPABILITY_SUPL, 107 NET_CAPABILITY_DUN, 108 NET_CAPABILITY_FOTA, 109 NET_CAPABILITY_IMS, 110 NET_CAPABILITY_CBS, 111 NET_CAPABILITY_WIFI_P2P, 112 NET_CAPABILITY_IA, 113 NET_CAPABILITY_RCS, 114 NET_CAPABILITY_XCAP, 115 NET_CAPABILITY_EIMS, 116 NET_CAPABILITY_NOT_METERED, 117 NET_CAPABILITY_INTERNET, 118 NET_CAPABILITY_NOT_RESTRICTED, 119 NET_CAPABILITY_TRUSTED, 120 NET_CAPABILITY_NOT_VPN, 121 NET_CAPABILITY_VALIDATED, 122 NET_CAPABILITY_CAPTIVE_PORTAL, 123 NET_CAPABILITY_NOT_ROAMING, 124 NET_CAPABILITY_FOREGROUND, 125 NET_CAPABILITY_NOT_CONGESTED, 126 NET_CAPABILITY_NOT_SUSPENDED, 127 NET_CAPABILITY_OEM_PAID, 128 }) 129 public @interface NetCapability { } 130 131 /** 132 * Indicates this is a network that has the ability to reach the 133 * carrier's MMSC for sending and receiving MMS messages. 134 */ 135 public static final int NET_CAPABILITY_MMS = 0; 136 137 /** 138 * Indicates this is a network that has the ability to reach the carrier's 139 * SUPL server, used to retrieve GPS information. 140 */ 141 public static final int NET_CAPABILITY_SUPL = 1; 142 143 /** 144 * Indicates this is a network that has the ability to reach the carrier's 145 * DUN or tethering gateway. 146 */ 147 public static final int NET_CAPABILITY_DUN = 2; 148 149 /** 150 * Indicates this is a network that has the ability to reach the carrier's 151 * FOTA portal, used for over the air updates. 152 */ 153 public static final int NET_CAPABILITY_FOTA = 3; 154 155 /** 156 * Indicates this is a network that has the ability to reach the carrier's 157 * IMS servers, used for network registration and signaling. 158 */ 159 public static final int NET_CAPABILITY_IMS = 4; 160 161 /** 162 * Indicates this is a network that has the ability to reach the carrier's 163 * CBS servers, used for carrier specific services. 164 */ 165 public static final int NET_CAPABILITY_CBS = 5; 166 167 /** 168 * Indicates this is a network that has the ability to reach a Wi-Fi direct 169 * peer. 170 */ 171 public static final int NET_CAPABILITY_WIFI_P2P = 6; 172 173 /** 174 * Indicates this is a network that has the ability to reach a carrier's 175 * Initial Attach servers. 176 */ 177 public static final int NET_CAPABILITY_IA = 7; 178 179 /** 180 * Indicates this is a network that has the ability to reach a carrier's 181 * RCS servers, used for Rich Communication Services. 182 */ 183 public static final int NET_CAPABILITY_RCS = 8; 184 185 /** 186 * Indicates this is a network that has the ability to reach a carrier's 187 * XCAP servers, used for configuration and control. 188 */ 189 public static final int NET_CAPABILITY_XCAP = 9; 190 191 /** 192 * Indicates this is a network that has the ability to reach a carrier's 193 * Emergency IMS servers or other services, used for network signaling 194 * during emergency calls. 195 */ 196 public static final int NET_CAPABILITY_EIMS = 10; 197 198 /** 199 * Indicates that this network is unmetered. 200 */ 201 public static final int NET_CAPABILITY_NOT_METERED = 11; 202 203 /** 204 * Indicates that this network should be able to reach the internet. 205 */ 206 public static final int NET_CAPABILITY_INTERNET = 12; 207 208 /** 209 * Indicates that this network is available for general use. If this is not set 210 * applications should not attempt to communicate on this network. Note that this 211 * is simply informative and not enforcement - enforcement is handled via other means. 212 * Set by default. 213 */ 214 public static final int NET_CAPABILITY_NOT_RESTRICTED = 13; 215 216 /** 217 * Indicates that the user has indicated implicit trust of this network. This 218 * generally means it's a sim-selected carrier, a plugged in ethernet, a paired 219 * BT device or a wifi the user asked to connect to. Untrusted networks 220 * are probably limited to unknown wifi AP. Set by default. 221 */ 222 public static final int NET_CAPABILITY_TRUSTED = 14; 223 224 /** 225 * Indicates that this network is not a VPN. This capability is set by default and should be 226 * explicitly cleared for VPN networks. 227 */ 228 public static final int NET_CAPABILITY_NOT_VPN = 15; 229 230 /** 231 * Indicates that connectivity on this network was successfully validated. For example, for a 232 * network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully 233 * detected. 234 */ 235 public static final int NET_CAPABILITY_VALIDATED = 16; 236 237 /** 238 * Indicates that this network was found to have a captive portal in place last time it was 239 * probed. 240 */ 241 public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17; 242 243 /** 244 * Indicates that this network is not roaming. 245 */ 246 public static final int NET_CAPABILITY_NOT_ROAMING = 18; 247 248 /** 249 * Indicates that this network is available for use by apps, and not a network that is being 250 * kept up in the background to facilitate fast network switching. 251 */ 252 public static final int NET_CAPABILITY_FOREGROUND = 19; 253 254 /** 255 * Indicates that this network is not congested. 256 * <p> 257 * When a network is congested, applications should defer network traffic 258 * that can be done at a later time, such as uploading analytics. 259 */ 260 public static final int NET_CAPABILITY_NOT_CONGESTED = 20; 261 262 /** 263 * Indicates that this network is not currently suspended. 264 * <p> 265 * When a network is suspended, the network's IP addresses and any connections 266 * established on the network remain valid, but the network is temporarily unable 267 * to transfer data. This can happen, for example, if a cellular network experiences 268 * a temporary loss of signal, such as when driving through a tunnel, etc. 269 * A network with this capability is not suspended, so is expected to be able to 270 * transfer data. 271 */ 272 public static final int NET_CAPABILITY_NOT_SUSPENDED = 21; 273 274 /** 275 * Indicates that traffic that goes through this network is paid by oem. For example, 276 * this network can be used by system apps to upload telemetry data. 277 * @hide 278 */ 279 @SystemApi 280 public static final int NET_CAPABILITY_OEM_PAID = 22; 281 282 private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS; 283 private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_OEM_PAID; 284 285 /** 286 * Network capabilities that are expected to be mutable, i.e., can change while a particular 287 * network is connected. 288 */ 289 private static final long MUTABLE_CAPABILITIES = 290 // TRUSTED can change when user explicitly connects to an untrusted network in Settings. 291 // http://b/18206275 292 (1 << NET_CAPABILITY_TRUSTED) 293 | (1 << NET_CAPABILITY_VALIDATED) 294 | (1 << NET_CAPABILITY_CAPTIVE_PORTAL) 295 | (1 << NET_CAPABILITY_NOT_ROAMING) 296 | (1 << NET_CAPABILITY_FOREGROUND) 297 | (1 << NET_CAPABILITY_NOT_CONGESTED) 298 | (1 << NET_CAPABILITY_NOT_SUSPENDED); 299 300 /** 301 * Network capabilities that are not allowed in NetworkRequests. This exists because the 302 * NetworkFactory / NetworkAgent model does not deal well with the situation where a 303 * capability's presence cannot be known in advance. If such a capability is requested, then we 304 * can get into a cycle where the NetworkFactory endlessly churns out NetworkAgents that then 305 * get immediately torn down because they do not have the requested capability. 306 */ 307 private static final long NON_REQUESTABLE_CAPABILITIES = 308 MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_TRUSTED); 309 310 /** 311 * Capabilities that are set by default when the object is constructed. 312 */ 313 private static final long DEFAULT_CAPABILITIES = 314 (1 << NET_CAPABILITY_NOT_RESTRICTED) | 315 (1 << NET_CAPABILITY_TRUSTED) | 316 (1 << NET_CAPABILITY_NOT_VPN); 317 318 /** 319 * Capabilities that suggest that a network is restricted. 320 * {@see #maybeMarkCapabilitiesRestricted}, {@see #FORCE_RESTRICTED_CAPABILITIES} 321 */ 322 @VisibleForTesting 323 /* package */ static final long RESTRICTED_CAPABILITIES = 324 (1 << NET_CAPABILITY_CBS) | 325 (1 << NET_CAPABILITY_DUN) | 326 (1 << NET_CAPABILITY_EIMS) | 327 (1 << NET_CAPABILITY_FOTA) | 328 (1 << NET_CAPABILITY_IA) | 329 (1 << NET_CAPABILITY_IMS) | 330 (1 << NET_CAPABILITY_RCS) | 331 (1 << NET_CAPABILITY_XCAP); 332 333 /** 334 * Capabilities that force network to be restricted. 335 * {@see #maybeMarkCapabilitiesRestricted}. 336 */ 337 private static final long FORCE_RESTRICTED_CAPABILITIES = 338 (1 << NET_CAPABILITY_OEM_PAID); 339 340 /** 341 * Capabilities that suggest that a network is unrestricted. 342 * {@see #maybeMarkCapabilitiesRestricted}. 343 */ 344 @VisibleForTesting 345 /* package */ static final long UNRESTRICTED_CAPABILITIES = 346 (1 << NET_CAPABILITY_INTERNET) | 347 (1 << NET_CAPABILITY_MMS) | 348 (1 << NET_CAPABILITY_SUPL) | 349 (1 << NET_CAPABILITY_WIFI_P2P); 350 351 /** 352 * Adds the given capability to this {@code NetworkCapability} instance. 353 * Multiple capabilities may be applied sequentially. Note that when searching 354 * for a network to satisfy a request, all capabilities requested must be satisfied. 355 * <p> 356 * If the given capability was previously added to the list of unwanted capabilities 357 * then the capability will also be removed from the list of unwanted capabilities. 358 * 359 * @param capability the capability to be added. 360 * @return This NetworkCapabilities instance, to facilitate chaining. 361 * @hide 362 */ 363 public NetworkCapabilities addCapability(@NetCapability int capability) { 364 checkValidCapability(capability); 365 mNetworkCapabilities |= 1 << capability; 366 mUnwantedNetworkCapabilities &= ~(1 << capability); // remove from unwanted capability list 367 return this; 368 } 369 370 /** 371 * Adds the given capability to the list of unwanted capabilities of this 372 * {@code NetworkCapability} instance. Multiple unwanted capabilities may be applied 373 * sequentially. Note that when searching for a network to satisfy a request, the network 374 * must not contain any capability from unwanted capability list. 375 * <p> 376 * If the capability was previously added to the list of required capabilities (for 377 * example, it was there by default or added using {@link #addCapability(int)} method), then 378 * it will be removed from the list of required capabilities as well. 379 * 380 * @see #addCapability(int) 381 * @hide 382 */ 383 public void addUnwantedCapability(@NetCapability int capability) { 384 checkValidCapability(capability); 385 mUnwantedNetworkCapabilities |= 1 << capability; 386 mNetworkCapabilities &= ~(1 << capability); // remove from requested capabilities 387 } 388 389 /** 390 * Removes (if found) the given capability from this {@code NetworkCapability} instance. 391 * <p> 392 * Note that this method removes capabilities that was added via {@link #addCapability(int)}, 393 * {@link #addUnwantedCapability(int)} or {@link #setCapabilities(int[], int[])} . 394 * 395 * @param capability the capability to be removed. 396 * @return This NetworkCapabilities instance, to facilitate chaining. 397 * @hide 398 */ 399 public NetworkCapabilities removeCapability(@NetCapability int capability) { 400 checkValidCapability(capability); 401 final long mask = ~(1 << capability); 402 mNetworkCapabilities &= mask; 403 mUnwantedNetworkCapabilities &= mask; 404 return this; 405 } 406 407 /** 408 * Sets (or clears) the given capability on this {@link NetworkCapabilities} 409 * instance. 410 * 411 * @hide 412 */ 413 public NetworkCapabilities setCapability(@NetCapability int capability, boolean value) { 414 if (value) { 415 addCapability(capability); 416 } else { 417 removeCapability(capability); 418 } 419 return this; 420 } 421 422 /** 423 * Gets all the capabilities set on this {@code NetworkCapability} instance. 424 * 425 * @return an array of capability values for this instance. 426 * @hide 427 */ 428 public @NetCapability int[] getCapabilities() { 429 return BitUtils.unpackBits(mNetworkCapabilities); 430 } 431 432 /** 433 * Gets all the unwanted capabilities set on this {@code NetworkCapability} instance. 434 * 435 * @return an array of unwanted capability values for this instance. 436 * @hide 437 */ 438 public @NetCapability int[] getUnwantedCapabilities() { 439 return BitUtils.unpackBits(mUnwantedNetworkCapabilities); 440 } 441 442 443 /** 444 * Sets all the capabilities set on this {@code NetworkCapability} instance. 445 * This overwrites any existing capabilities. 446 * 447 * @hide 448 */ 449 public void setCapabilities(@NetCapability int[] capabilities, 450 @NetCapability int[] unwantedCapabilities) { 451 mNetworkCapabilities = BitUtils.packBits(capabilities); 452 mUnwantedNetworkCapabilities = BitUtils.packBits(unwantedCapabilities); 453 } 454 455 /** 456 * @deprecated use {@link #setCapabilities(int[], int[])} 457 * @hide 458 */ 459 @Deprecated 460 public void setCapabilities(@NetCapability int[] capabilities) { 461 setCapabilities(capabilities, new int[] {}); 462 } 463 464 /** 465 * Tests for the presence of a capability on this instance. 466 * 467 * @param capability the capabilities to be tested for. 468 * @return {@code true} if set on this instance. 469 */ 470 public boolean hasCapability(@NetCapability int capability) { 471 return isValidCapability(capability) 472 && ((mNetworkCapabilities & (1 << capability)) != 0); 473 } 474 475 /** @hide */ 476 public boolean hasUnwantedCapability(@NetCapability int capability) { 477 return isValidCapability(capability) 478 && ((mUnwantedNetworkCapabilities & (1 << capability)) != 0); 479 } 480 481 private void combineNetCapabilities(NetworkCapabilities nc) { 482 this.mNetworkCapabilities |= nc.mNetworkCapabilities; 483 this.mUnwantedNetworkCapabilities |= nc.mUnwantedNetworkCapabilities; 484 } 485 486 /** 487 * Convenience function that returns a human-readable description of the first mutable 488 * capability we find. Used to present an error message to apps that request mutable 489 * capabilities. 490 * 491 * @hide 492 */ 493 public String describeFirstNonRequestableCapability() { 494 final long nonRequestable = (mNetworkCapabilities | mUnwantedNetworkCapabilities) 495 & NON_REQUESTABLE_CAPABILITIES; 496 497 if (nonRequestable != 0) { 498 return capabilityNameOf(BitUtils.unpackBits(nonRequestable)[0]); 499 } 500 if (mLinkUpBandwidthKbps != 0 || mLinkDownBandwidthKbps != 0) return "link bandwidth"; 501 if (hasSignalStrength()) return "signalStrength"; 502 return null; 503 } 504 505 private boolean satisfiedByNetCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { 506 long requestedCapabilities = mNetworkCapabilities; 507 long requestedUnwantedCapabilities = mUnwantedNetworkCapabilities; 508 long providedCapabilities = nc.mNetworkCapabilities; 509 510 if (onlyImmutable) { 511 requestedCapabilities &= ~MUTABLE_CAPABILITIES; 512 requestedUnwantedCapabilities &= ~MUTABLE_CAPABILITIES; 513 } 514 return ((providedCapabilities & requestedCapabilities) == requestedCapabilities) 515 && ((requestedUnwantedCapabilities & providedCapabilities) == 0); 516 } 517 518 /** @hide */ 519 public boolean equalsNetCapabilities(NetworkCapabilities nc) { 520 return (nc.mNetworkCapabilities == this.mNetworkCapabilities) 521 && (nc.mUnwantedNetworkCapabilities == this.mUnwantedNetworkCapabilities); 522 } 523 524 private boolean equalsNetCapabilitiesRequestable(NetworkCapabilities that) { 525 return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) == 526 (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)) 527 && ((this.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) == 528 (that.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)); 529 } 530 531 /** 532 * Removes the NET_CAPABILITY_NOT_RESTRICTED capability if all the capabilities it provides are 533 * typically provided by restricted networks. 534 * 535 * TODO: consider: 536 * - Renaming it to guessRestrictedCapability and make it set the 537 * restricted capability bit in addition to clearing it. 538 * @hide 539 */ 540 public void maybeMarkCapabilitiesRestricted() { 541 // Check if we have any capability that forces the network to be restricted. 542 final boolean forceRestrictedCapability = 543 (mNetworkCapabilities & FORCE_RESTRICTED_CAPABILITIES) != 0; 544 545 // Verify there aren't any unrestricted capabilities. If there are we say 546 // the whole thing is unrestricted unless it is forced to be restricted. 547 final boolean hasUnrestrictedCapabilities = 548 (mNetworkCapabilities & UNRESTRICTED_CAPABILITIES) != 0; 549 550 // Must have at least some restricted capabilities. 551 final boolean hasRestrictedCapabilities = 552 (mNetworkCapabilities & RESTRICTED_CAPABILITIES) != 0; 553 554 if (forceRestrictedCapability 555 || (hasRestrictedCapabilities && !hasUnrestrictedCapabilities)) { 556 removeCapability(NET_CAPABILITY_NOT_RESTRICTED); 557 } 558 } 559 560 /** 561 * Representing the transport type. Apps should generally not care about transport. A 562 * request for a fast internet connection could be satisfied by a number of different 563 * transports. If any are specified here it will be satisfied a Network that matches 564 * any of them. If a caller doesn't care about the transport it should not specify any. 565 */ 566 private long mTransportTypes; 567 568 /** @hide */ 569 @Retention(RetentionPolicy.SOURCE) 570 @IntDef(prefix = { "TRANSPORT_" }, value = { 571 TRANSPORT_CELLULAR, 572 TRANSPORT_WIFI, 573 TRANSPORT_BLUETOOTH, 574 TRANSPORT_ETHERNET, 575 TRANSPORT_VPN, 576 TRANSPORT_WIFI_AWARE, 577 TRANSPORT_LOWPAN, 578 }) 579 public @interface Transport { } 580 581 /** 582 * Indicates this network uses a Cellular transport. 583 */ 584 public static final int TRANSPORT_CELLULAR = 0; 585 586 /** 587 * Indicates this network uses a Wi-Fi transport. 588 */ 589 public static final int TRANSPORT_WIFI = 1; 590 591 /** 592 * Indicates this network uses a Bluetooth transport. 593 */ 594 public static final int TRANSPORT_BLUETOOTH = 2; 595 596 /** 597 * Indicates this network uses an Ethernet transport. 598 */ 599 public static final int TRANSPORT_ETHERNET = 3; 600 601 /** 602 * Indicates this network uses a VPN transport. 603 */ 604 public static final int TRANSPORT_VPN = 4; 605 606 /** 607 * Indicates this network uses a Wi-Fi Aware transport. 608 */ 609 public static final int TRANSPORT_WIFI_AWARE = 5; 610 611 /** 612 * Indicates this network uses a LoWPAN transport. 613 */ 614 public static final int TRANSPORT_LOWPAN = 6; 615 616 /** @hide */ 617 public static final int MIN_TRANSPORT = TRANSPORT_CELLULAR; 618 /** @hide */ 619 public static final int MAX_TRANSPORT = TRANSPORT_LOWPAN; 620 621 /** @hide */ 622 public static boolean isValidTransport(@Transport int transportType) { 623 return (MIN_TRANSPORT <= transportType) && (transportType <= MAX_TRANSPORT); 624 } 625 626 private static final String[] TRANSPORT_NAMES = { 627 "CELLULAR", 628 "WIFI", 629 "BLUETOOTH", 630 "ETHERNET", 631 "VPN", 632 "WIFI_AWARE", 633 "LOWPAN" 634 }; 635 636 /** 637 * Adds the given transport type to this {@code NetworkCapability} instance. 638 * Multiple transports may be applied sequentially. Note that when searching 639 * for a network to satisfy a request, any listed in the request will satisfy the request. 640 * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a 641 * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network 642 * to be selected. This is logically different than 643 * {@code NetworkCapabilities.NET_CAPABILITY_*} listed above. 644 * 645 * @param transportType the transport type to be added. 646 * @return This NetworkCapabilities instance, to facilitate chaining. 647 * @hide 648 */ 649 public NetworkCapabilities addTransportType(@Transport int transportType) { 650 checkValidTransportType(transportType); 651 mTransportTypes |= 1 << transportType; 652 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking 653 return this; 654 } 655 656 /** 657 * Removes (if found) the given transport from this {@code NetworkCapability} instance. 658 * 659 * @param transportType the transport type to be removed. 660 * @return This NetworkCapabilities instance, to facilitate chaining. 661 * @hide 662 */ 663 public NetworkCapabilities removeTransportType(@Transport int transportType) { 664 checkValidTransportType(transportType); 665 mTransportTypes &= ~(1 << transportType); 666 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking 667 return this; 668 } 669 670 /** 671 * Sets (or clears) the given transport on this {@link NetworkCapabilities} 672 * instance. 673 * 674 * @hide 675 */ 676 public NetworkCapabilities setTransportType(@Transport int transportType, boolean value) { 677 if (value) { 678 addTransportType(transportType); 679 } else { 680 removeTransportType(transportType); 681 } 682 return this; 683 } 684 685 /** 686 * Gets all the transports set on this {@code NetworkCapability} instance. 687 * 688 * @return an array of transport type values for this instance. 689 * @hide 690 */ 691 public @Transport int[] getTransportTypes() { 692 return BitUtils.unpackBits(mTransportTypes); 693 } 694 695 /** 696 * Sets all the transports set on this {@code NetworkCapability} instance. 697 * This overwrites any existing transports. 698 * 699 * @hide 700 */ 701 public void setTransportTypes(@Transport int[] transportTypes) { 702 mTransportTypes = BitUtils.packBits(transportTypes); 703 } 704 705 /** 706 * Tests for the presence of a transport on this instance. 707 * 708 * @param transportType the transport type to be tested for. 709 * @return {@code true} if set on this instance. 710 */ 711 public boolean hasTransport(@Transport int transportType) { 712 return isValidTransport(transportType) && ((mTransportTypes & (1 << transportType)) != 0); 713 } 714 715 private void combineTransportTypes(NetworkCapabilities nc) { 716 this.mTransportTypes |= nc.mTransportTypes; 717 } 718 719 private boolean satisfiedByTransportTypes(NetworkCapabilities nc) { 720 return ((this.mTransportTypes == 0) || 721 ((this.mTransportTypes & nc.mTransportTypes) != 0)); 722 } 723 724 /** @hide */ 725 public boolean equalsTransportTypes(NetworkCapabilities nc) { 726 return (nc.mTransportTypes == this.mTransportTypes); 727 } 728 729 /** 730 * UID of the app that manages this network, or INVALID_UID if none/unknown. 731 * 732 * This field keeps track of the UID of the app that created this network and is in charge 733 * of managing it. In the practice, it is used to store the UID of VPN apps so it is named 734 * accordingly, but it may be renamed if other mechanisms are offered for third party apps 735 * to create networks. 736 * 737 * Because this field is only used in the services side (and to avoid apps being able to 738 * set this to whatever they want), this field is not parcelled and will not be conserved 739 * across the IPC boundary. 740 * @hide 741 */ 742 private int mEstablishingVpnAppUid = INVALID_UID; 743 744 /** 745 * Set the UID of the managing app. 746 * @hide 747 */ 748 public void setEstablishingVpnAppUid(final int uid) { 749 mEstablishingVpnAppUid = uid; 750 } 751 752 /** 753 * Value indicating that link bandwidth is unspecified. 754 * @hide 755 */ 756 public static final int LINK_BANDWIDTH_UNSPECIFIED = 0; 757 758 /** 759 * Passive link bandwidth. This is a rough guide of the expected peak bandwidth 760 * for the first hop on the given transport. It is not measured, but may take into account 761 * link parameters (Radio technology, allocated channels, etc). 762 */ 763 private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 764 private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED; 765 766 /** 767 * Sets the upstream bandwidth for this network in Kbps. This always only refers to 768 * the estimated first hop transport bandwidth. 769 * <p> 770 * Note that when used to request a network, this specifies the minimum acceptable. 771 * When received as the state of an existing network this specifies the typical 772 * first hop bandwidth expected. This is never measured, but rather is inferred 773 * from technology type and other link parameters. It could be used to differentiate 774 * between very slow 1xRTT cellular links and other faster networks or even between 775 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between 776 * fast backhauls and slow backhauls. 777 * 778 * @param upKbps the estimated first hop upstream (device to network) bandwidth. 779 * @hide 780 */ 781 public NetworkCapabilities setLinkUpstreamBandwidthKbps(int upKbps) { 782 mLinkUpBandwidthKbps = upKbps; 783 return this; 784 } 785 786 /** 787 * Retrieves the upstream bandwidth for this network in Kbps. This always only refers to 788 * the estimated first hop transport bandwidth. 789 * 790 * @return The estimated first hop upstream (device to network) bandwidth. 791 */ 792 public int getLinkUpstreamBandwidthKbps() { 793 return mLinkUpBandwidthKbps; 794 } 795 796 /** 797 * Sets the downstream bandwidth for this network in Kbps. This always only refers to 798 * the estimated first hop transport bandwidth. 799 * <p> 800 * Note that when used to request a network, this specifies the minimum acceptable. 801 * When received as the state of an existing network this specifies the typical 802 * first hop bandwidth expected. This is never measured, but rather is inferred 803 * from technology type and other link parameters. It could be used to differentiate 804 * between very slow 1xRTT cellular links and other faster networks or even between 805 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between 806 * fast backhauls and slow backhauls. 807 * 808 * @param downKbps the estimated first hop downstream (network to device) bandwidth. 809 * @hide 810 */ 811 public NetworkCapabilities setLinkDownstreamBandwidthKbps(int downKbps) { 812 mLinkDownBandwidthKbps = downKbps; 813 return this; 814 } 815 816 /** 817 * Retrieves the downstream bandwidth for this network in Kbps. This always only refers to 818 * the estimated first hop transport bandwidth. 819 * 820 * @return The estimated first hop downstream (network to device) bandwidth. 821 */ 822 public int getLinkDownstreamBandwidthKbps() { 823 return mLinkDownBandwidthKbps; 824 } 825 826 private void combineLinkBandwidths(NetworkCapabilities nc) { 827 this.mLinkUpBandwidthKbps = 828 Math.max(this.mLinkUpBandwidthKbps, nc.mLinkUpBandwidthKbps); 829 this.mLinkDownBandwidthKbps = 830 Math.max(this.mLinkDownBandwidthKbps, nc.mLinkDownBandwidthKbps); 831 } 832 private boolean satisfiedByLinkBandwidths(NetworkCapabilities nc) { 833 return !(this.mLinkUpBandwidthKbps > nc.mLinkUpBandwidthKbps || 834 this.mLinkDownBandwidthKbps > nc.mLinkDownBandwidthKbps); 835 } 836 private boolean equalsLinkBandwidths(NetworkCapabilities nc) { 837 return (this.mLinkUpBandwidthKbps == nc.mLinkUpBandwidthKbps && 838 this.mLinkDownBandwidthKbps == nc.mLinkDownBandwidthKbps); 839 } 840 /** @hide */ 841 public static int minBandwidth(int a, int b) { 842 if (a == LINK_BANDWIDTH_UNSPECIFIED) { 843 return b; 844 } else if (b == LINK_BANDWIDTH_UNSPECIFIED) { 845 return a; 846 } else { 847 return Math.min(a, b); 848 } 849 } 850 /** @hide */ 851 public static int maxBandwidth(int a, int b) { 852 return Math.max(a, b); 853 } 854 855 private NetworkSpecifier mNetworkSpecifier = null; 856 857 /** 858 * Sets the optional bearer specific network specifier. 859 * This has no meaning if a single transport is also not specified, so calling 860 * this without a single transport set will generate an exception, as will 861 * subsequently adding or removing transports after this is set. 862 * </p> 863 * 864 * @param networkSpecifier A concrete, parcelable framework class that extends 865 * NetworkSpecifier. 866 * @return This NetworkCapabilities instance, to facilitate chaining. 867 * @hide 868 */ 869 public NetworkCapabilities setNetworkSpecifier(NetworkSpecifier networkSpecifier) { 870 if (networkSpecifier != null && Long.bitCount(mTransportTypes) != 1) { 871 throw new IllegalStateException("Must have a single transport specified to use " + 872 "setNetworkSpecifier"); 873 } 874 875 mNetworkSpecifier = networkSpecifier; 876 877 return this; 878 } 879 880 /** 881 * Gets the optional bearer specific network specifier. 882 * 883 * @return The optional {@link NetworkSpecifier} specifying the bearer specific network 884 * specifier. See {@link #setNetworkSpecifier}. 885 * @hide 886 */ 887 public NetworkSpecifier getNetworkSpecifier() { 888 return mNetworkSpecifier; 889 } 890 891 private void combineSpecifiers(NetworkCapabilities nc) { 892 if (mNetworkSpecifier != null && !mNetworkSpecifier.equals(nc.mNetworkSpecifier)) { 893 throw new IllegalStateException("Can't combine two networkSpecifiers"); 894 } 895 setNetworkSpecifier(nc.mNetworkSpecifier); 896 } 897 898 private boolean satisfiedBySpecifier(NetworkCapabilities nc) { 899 return mNetworkSpecifier == null || mNetworkSpecifier.satisfiedBy(nc.mNetworkSpecifier) 900 || nc.mNetworkSpecifier instanceof MatchAllNetworkSpecifier; 901 } 902 903 private boolean equalsSpecifier(NetworkCapabilities nc) { 904 return Objects.equals(mNetworkSpecifier, nc.mNetworkSpecifier); 905 } 906 907 /** 908 * Magic value that indicates no signal strength provided. A request specifying this value is 909 * always satisfied. 910 * 911 * @hide 912 */ 913 public static final int SIGNAL_STRENGTH_UNSPECIFIED = Integer.MIN_VALUE; 914 915 /** 916 * Signal strength. This is a signed integer, and higher values indicate better signal. 917 * The exact units are bearer-dependent. For example, Wi-Fi uses RSSI. 918 */ 919 private int mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED; 920 921 /** 922 * Sets the signal strength. This is a signed integer, with higher values indicating a stronger 923 * signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same RSSI units 924 * reported by WifiManager. 925 * <p> 926 * Note that when used to register a network callback, this specifies the minimum acceptable 927 * signal strength. When received as the state of an existing network it specifies the current 928 * value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means no value when received and has no 929 * effect when requesting a callback. 930 * 931 * @param signalStrength the bearer-specific signal strength. 932 * @hide 933 */ 934 public NetworkCapabilities setSignalStrength(int signalStrength) { 935 mSignalStrength = signalStrength; 936 return this; 937 } 938 939 /** 940 * Returns {@code true} if this object specifies a signal strength. 941 * 942 * @hide 943 */ 944 public boolean hasSignalStrength() { 945 return mSignalStrength > SIGNAL_STRENGTH_UNSPECIFIED; 946 } 947 948 /** 949 * Retrieves the signal strength. 950 * 951 * @return The bearer-specific signal strength. 952 * @hide 953 */ 954 public int getSignalStrength() { 955 return mSignalStrength; 956 } 957 958 private void combineSignalStrength(NetworkCapabilities nc) { 959 this.mSignalStrength = Math.max(this.mSignalStrength, nc.mSignalStrength); 960 } 961 962 private boolean satisfiedBySignalStrength(NetworkCapabilities nc) { 963 return this.mSignalStrength <= nc.mSignalStrength; 964 } 965 966 private boolean equalsSignalStrength(NetworkCapabilities nc) { 967 return this.mSignalStrength == nc.mSignalStrength; 968 } 969 970 /** 971 * List of UIDs this network applies to. No restriction if null. 972 * <p> 973 * For networks, mUids represent the list of network this applies to, and null means this 974 * network applies to all UIDs. 975 * For requests, mUids is the list of UIDs this network MUST apply to to match ; ALL UIDs 976 * must be included in a network so that they match. As an exception to the general rule, 977 * a null mUids field for requests mean "no requirements" rather than what the general rule 978 * would suggest ("must apply to all UIDs") : this is because this has shown to be what users 979 * of this API expect in practice. A network that must match all UIDs can still be 980 * expressed with a set ranging the entire set of possible UIDs. 981 * <p> 982 * mUids is typically (and at this time, only) used by VPN. This network is only available to 983 * the UIDs in this list, and it is their default network. Apps in this list that wish to 984 * bypass the VPN can do so iff the VPN app allows them to or if they are privileged. If this 985 * member is null, then the network is not restricted by app UID. If it's an empty list, then 986 * it means nobody can use it. 987 * As a special exception, the app managing this network (as identified by its UID stored in 988 * mEstablishingVpnAppUid) can always see this network. This is embodied by a special check in 989 * satisfiedByUids. That still does not mean the network necessarily <strong>applies</strong> 990 * to the app that manages it as determined by #appliesToUid. 991 * <p> 992 * Please note that in principle a single app can be associated with multiple UIDs because 993 * each app will have a different UID when it's run as a different (macro-)user. A single 994 * macro user can only have a single active VPN app at any given time however. 995 * <p> 996 * Also please be aware this class does not try to enforce any normalization on this. Callers 997 * can only alter the UIDs by setting them wholesale : this class does not provide any utility 998 * to add or remove individual UIDs or ranges. If callers have any normalization needs on 999 * their own (like requiring sortedness or no overlap) they need to enforce it 1000 * themselves. Some of the internal methods also assume this is normalized as in no adjacent 1001 * or overlapping ranges are present. 1002 * 1003 * @hide 1004 */ 1005 private ArraySet<UidRange> mUids = null; 1006 1007 /** 1008 * Convenience method to set the UIDs this network applies to to a single UID. 1009 * @hide 1010 */ 1011 public NetworkCapabilities setSingleUid(int uid) { 1012 final ArraySet<UidRange> identity = new ArraySet<>(1); 1013 identity.add(new UidRange(uid, uid)); 1014 setUids(identity); 1015 return this; 1016 } 1017 1018 /** 1019 * Set the list of UIDs this network applies to. 1020 * This makes a copy of the set so that callers can't modify it after the call. 1021 * @hide 1022 */ 1023 public NetworkCapabilities setUids(Set<UidRange> uids) { 1024 if (null == uids) { 1025 mUids = null; 1026 } else { 1027 mUids = new ArraySet<>(uids); 1028 } 1029 return this; 1030 } 1031 1032 /** 1033 * Get the list of UIDs this network applies to. 1034 * This returns a copy of the set so that callers can't modify the original object. 1035 * @hide 1036 */ 1037 public Set<UidRange> getUids() { 1038 return null == mUids ? null : new ArraySet<>(mUids); 1039 } 1040 1041 /** 1042 * Test whether this network applies to this UID. 1043 * @hide 1044 */ 1045 public boolean appliesToUid(int uid) { 1046 if (null == mUids) return true; 1047 for (UidRange range : mUids) { 1048 if (range.contains(uid)) { 1049 return true; 1050 } 1051 } 1052 return false; 1053 } 1054 1055 /** 1056 * Tests if the set of UIDs that this network applies to is the same of the passed set of UIDs. 1057 * <p> 1058 * This test only checks whether equal range objects are in both sets. It will 1059 * return false if the ranges are not exactly the same, even if the covered UIDs 1060 * are for an equivalent result. 1061 * <p> 1062 * Note that this method is not very optimized, which is fine as long as it's not used very 1063 * often. 1064 * <p> 1065 * nc is assumed nonnull. 1066 * 1067 * @hide 1068 */ 1069 @VisibleForTesting 1070 public boolean equalsUids(NetworkCapabilities nc) { 1071 Set<UidRange> comparedUids = nc.mUids; 1072 if (null == comparedUids) return null == mUids; 1073 if (null == mUids) return false; 1074 // Make a copy so it can be mutated to check that all ranges in mUids 1075 // also are in uids. 1076 final Set<UidRange> uids = new ArraySet<>(mUids); 1077 for (UidRange range : comparedUids) { 1078 if (!uids.contains(range)) { 1079 return false; 1080 } 1081 uids.remove(range); 1082 } 1083 return uids.isEmpty(); 1084 } 1085 1086 /** 1087 * Test whether the passed NetworkCapabilities satisfies the UIDs this capabilities require. 1088 * 1089 * This method is called on the NetworkCapabilities embedded in a request with the 1090 * capabilities of an available network. It checks whether all the UIDs from this listen 1091 * (representing the UIDs that must have access to the network) are satisfied by the UIDs 1092 * in the passed nc (representing the UIDs that this network is available to). 1093 * <p> 1094 * As a special exception, the UID that created the passed network (as represented by its 1095 * mEstablishingVpnAppUid field) always satisfies a NetworkRequest requiring it (of LISTEN 1096 * or REQUEST types alike), even if the network does not apply to it. That is so a VPN app 1097 * can see its own network when it listens for it. 1098 * <p> 1099 * nc is assumed nonnull. Else, NPE. 1100 * @see #appliesToUid 1101 * @hide 1102 */ 1103 public boolean satisfiedByUids(NetworkCapabilities nc) { 1104 if (null == nc.mUids || null == mUids) return true; // The network satisfies everything. 1105 for (UidRange requiredRange : mUids) { 1106 if (requiredRange.contains(nc.mEstablishingVpnAppUid)) return true; 1107 if (!nc.appliesToUidRange(requiredRange)) { 1108 return false; 1109 } 1110 } 1111 return true; 1112 } 1113 1114 /** 1115 * Returns whether this network applies to the passed ranges. 1116 * This assumes that to apply, the passed range has to be entirely contained 1117 * within one of the ranges this network applies to. If the ranges are not normalized, 1118 * this method may return false even though all required UIDs are covered because no 1119 * single range contained them all. 1120 * @hide 1121 */ 1122 @VisibleForTesting 1123 public boolean appliesToUidRange(UidRange requiredRange) { 1124 if (null == mUids) return true; 1125 for (UidRange uidRange : mUids) { 1126 if (uidRange.containsRange(requiredRange)) { 1127 return true; 1128 } 1129 } 1130 return false; 1131 } 1132 1133 /** 1134 * Combine the UIDs this network currently applies to with the UIDs the passed 1135 * NetworkCapabilities apply to. 1136 * nc is assumed nonnull. 1137 */ 1138 private void combineUids(NetworkCapabilities nc) { 1139 if (null == nc.mUids || null == mUids) { 1140 mUids = null; 1141 return; 1142 } 1143 mUids.addAll(nc.mUids); 1144 } 1145 1146 /** 1147 * Combine a set of Capabilities to this one. Useful for coming up with the complete set 1148 * @hide 1149 */ 1150 public void combineCapabilities(NetworkCapabilities nc) { 1151 combineNetCapabilities(nc); 1152 combineTransportTypes(nc); 1153 combineLinkBandwidths(nc); 1154 combineSpecifiers(nc); 1155 combineSignalStrength(nc); 1156 combineUids(nc); 1157 } 1158 1159 /** 1160 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}. 1161 * 1162 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 1163 * @param onlyImmutable if {@code true}, do not consider mutable requirements such as link 1164 * bandwidth, signal strength, or validation / captive portal status. 1165 * 1166 * @hide 1167 */ 1168 private boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { 1169 return (nc != null 1170 && satisfiedByNetCapabilities(nc, onlyImmutable) 1171 && satisfiedByTransportTypes(nc) 1172 && (onlyImmutable || satisfiedByLinkBandwidths(nc)) 1173 && satisfiedBySpecifier(nc) 1174 && (onlyImmutable || satisfiedBySignalStrength(nc)) 1175 && (onlyImmutable || satisfiedByUids(nc))); 1176 } 1177 1178 /** 1179 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}. 1180 * 1181 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 1182 * 1183 * @hide 1184 */ 1185 public boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc) { 1186 return satisfiedByNetworkCapabilities(nc, false); 1187 } 1188 1189 /** 1190 * Check if our immutable requirements are satisfied by the given {@code NetworkCapabilities}. 1191 * 1192 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements. 1193 * 1194 * @hide 1195 */ 1196 public boolean satisfiedByImmutableNetworkCapabilities(NetworkCapabilities nc) { 1197 return satisfiedByNetworkCapabilities(nc, true); 1198 } 1199 1200 /** 1201 * Checks that our immutable capabilities are the same as those of the given 1202 * {@code NetworkCapabilities} and return a String describing any difference. 1203 * The returned String is empty if there is no difference. 1204 * 1205 * @hide 1206 */ 1207 public String describeImmutableDifferences(NetworkCapabilities that) { 1208 if (that == null) { 1209 return "other NetworkCapabilities was null"; 1210 } 1211 1212 StringJoiner joiner = new StringJoiner(", "); 1213 1214 // Ignore NOT_METERED being added or removed as it is effectively dynamic. http://b/63326103 1215 // TODO: properly support NOT_METERED as a mutable and requestable capability. 1216 final long mask = ~MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_NOT_METERED); 1217 long oldImmutableCapabilities = this.mNetworkCapabilities & mask; 1218 long newImmutableCapabilities = that.mNetworkCapabilities & mask; 1219 if (oldImmutableCapabilities != newImmutableCapabilities) { 1220 String before = capabilityNamesOf(BitUtils.unpackBits(oldImmutableCapabilities)); 1221 String after = capabilityNamesOf(BitUtils.unpackBits(newImmutableCapabilities)); 1222 joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after)); 1223 } 1224 1225 if (!equalsSpecifier(that)) { 1226 NetworkSpecifier before = this.getNetworkSpecifier(); 1227 NetworkSpecifier after = that.getNetworkSpecifier(); 1228 joiner.add(String.format("specifier changed: %s -> %s", before, after)); 1229 } 1230 1231 if (!equalsTransportTypes(that)) { 1232 String before = transportNamesOf(this.getTransportTypes()); 1233 String after = transportNamesOf(that.getTransportTypes()); 1234 joiner.add(String.format("transports changed: %s -> %s", before, after)); 1235 } 1236 1237 return joiner.toString(); 1238 } 1239 1240 /** 1241 * Checks that our requestable capabilities are the same as those of the given 1242 * {@code NetworkCapabilities}. 1243 * 1244 * @hide 1245 */ 1246 public boolean equalRequestableCapabilities(NetworkCapabilities nc) { 1247 if (nc == null) return false; 1248 return (equalsNetCapabilitiesRequestable(nc) && 1249 equalsTransportTypes(nc) && 1250 equalsSpecifier(nc)); 1251 } 1252 1253 @Override 1254 public boolean equals(Object obj) { 1255 if (obj == null || (obj instanceof NetworkCapabilities == false)) return false; 1256 NetworkCapabilities that = (NetworkCapabilities) obj; 1257 return (equalsNetCapabilities(that) 1258 && equalsTransportTypes(that) 1259 && equalsLinkBandwidths(that) 1260 && equalsSignalStrength(that) 1261 && equalsSpecifier(that) 1262 && equalsUids(that)); 1263 } 1264 1265 @Override 1266 public int hashCode() { 1267 return (int) (mNetworkCapabilities & 0xFFFFFFFF) 1268 + ((int) (mNetworkCapabilities >> 32) * 3) 1269 + ((int) (mUnwantedNetworkCapabilities & 0xFFFFFFFF) * 5) 1270 + ((int) (mUnwantedNetworkCapabilities >> 32) * 7) 1271 + ((int) (mTransportTypes & 0xFFFFFFFF) * 11) 1272 + ((int) (mTransportTypes >> 32) * 13) 1273 + (mLinkUpBandwidthKbps * 17) 1274 + (mLinkDownBandwidthKbps * 19) 1275 + Objects.hashCode(mNetworkSpecifier) * 23 1276 + (mSignalStrength * 29) 1277 + Objects.hashCode(mUids) * 31; 1278 } 1279 1280 @Override 1281 public int describeContents() { 1282 return 0; 1283 } 1284 @Override 1285 public void writeToParcel(Parcel dest, int flags) { 1286 dest.writeLong(mNetworkCapabilities); 1287 dest.writeLong(mUnwantedNetworkCapabilities); 1288 dest.writeLong(mTransportTypes); 1289 dest.writeInt(mLinkUpBandwidthKbps); 1290 dest.writeInt(mLinkDownBandwidthKbps); 1291 dest.writeParcelable((Parcelable) mNetworkSpecifier, flags); 1292 dest.writeInt(mSignalStrength); 1293 dest.writeArraySet(mUids); 1294 } 1295 1296 public static final Creator<NetworkCapabilities> CREATOR = 1297 new Creator<NetworkCapabilities>() { 1298 @Override 1299 public NetworkCapabilities createFromParcel(Parcel in) { 1300 NetworkCapabilities netCap = new NetworkCapabilities(); 1301 1302 netCap.mNetworkCapabilities = in.readLong(); 1303 netCap.mUnwantedNetworkCapabilities = in.readLong(); 1304 netCap.mTransportTypes = in.readLong(); 1305 netCap.mLinkUpBandwidthKbps = in.readInt(); 1306 netCap.mLinkDownBandwidthKbps = in.readInt(); 1307 netCap.mNetworkSpecifier = in.readParcelable(null); 1308 netCap.mSignalStrength = in.readInt(); 1309 netCap.mUids = (ArraySet<UidRange>) in.readArraySet( 1310 null /* ClassLoader, null for default */); 1311 return netCap; 1312 } 1313 @Override 1314 public NetworkCapabilities[] newArray(int size) { 1315 return new NetworkCapabilities[size]; 1316 } 1317 }; 1318 1319 @Override 1320 public String toString() { 1321 final StringBuilder sb = new StringBuilder("["); 1322 if (0 != mTransportTypes) { 1323 sb.append(" Transports: "); 1324 appendStringRepresentationOfBitMaskToStringBuilder(sb, mTransportTypes, 1325 NetworkCapabilities::transportNameOf, "|"); 1326 } 1327 if (0 != mNetworkCapabilities) { 1328 sb.append(" Capabilities: "); 1329 appendStringRepresentationOfBitMaskToStringBuilder(sb, mNetworkCapabilities, 1330 NetworkCapabilities::capabilityNameOf, "&"); 1331 } 1332 if (0 != mNetworkCapabilities) { 1333 sb.append(" Unwanted: "); 1334 appendStringRepresentationOfBitMaskToStringBuilder(sb, mUnwantedNetworkCapabilities, 1335 NetworkCapabilities::capabilityNameOf, "&"); 1336 } 1337 if (mLinkUpBandwidthKbps > 0) { 1338 sb.append(" LinkUpBandwidth>=").append(mLinkUpBandwidthKbps).append("Kbps"); 1339 } 1340 if (mLinkDownBandwidthKbps > 0) { 1341 sb.append(" LinkDnBandwidth>=").append(mLinkDownBandwidthKbps).append("Kbps"); 1342 } 1343 if (mNetworkSpecifier != null) { 1344 sb.append(" Specifier: <").append(mNetworkSpecifier).append(">"); 1345 } 1346 if (hasSignalStrength()) { 1347 sb.append(" SignalStrength: ").append(mSignalStrength); 1348 } 1349 1350 if (null != mUids) { 1351 if ((1 == mUids.size()) && (mUids.valueAt(0).count() == 1)) { 1352 sb.append(" Uid: ").append(mUids.valueAt(0).start); 1353 } else { 1354 sb.append(" Uids: <").append(mUids).append(">"); 1355 } 1356 } 1357 if (mEstablishingVpnAppUid != INVALID_UID) { 1358 sb.append(" EstablishingAppUid: ").append(mEstablishingVpnAppUid); 1359 } 1360 1361 sb.append("]"); 1362 return sb.toString(); 1363 } 1364 1365 1366 private interface NameOf { 1367 String nameOf(int value); 1368 } 1369 /** 1370 * @hide 1371 */ 1372 public static void appendStringRepresentationOfBitMaskToStringBuilder(StringBuilder sb, 1373 long bitMask, NameOf nameFetcher, String separator) { 1374 int bitPos = 0; 1375 boolean firstElementAdded = false; 1376 while (bitMask != 0) { 1377 if ((bitMask & 1) != 0) { 1378 if (firstElementAdded) { 1379 sb.append(separator); 1380 } else { 1381 firstElementAdded = true; 1382 } 1383 sb.append(nameFetcher.nameOf(bitPos)); 1384 } 1385 bitMask >>= 1; 1386 ++bitPos; 1387 } 1388 } 1389 1390 /** @hide */ 1391 public void writeToProto(ProtoOutputStream proto, long fieldId) { 1392 final long token = proto.start(fieldId); 1393 1394 for (int transport : getTransportTypes()) { 1395 proto.write(NetworkCapabilitiesProto.TRANSPORTS, transport); 1396 } 1397 1398 for (int capability : getCapabilities()) { 1399 proto.write(NetworkCapabilitiesProto.CAPABILITIES, capability); 1400 } 1401 1402 proto.write(NetworkCapabilitiesProto.LINK_UP_BANDWIDTH_KBPS, mLinkUpBandwidthKbps); 1403 proto.write(NetworkCapabilitiesProto.LINK_DOWN_BANDWIDTH_KBPS, mLinkDownBandwidthKbps); 1404 1405 if (mNetworkSpecifier != null) { 1406 proto.write(NetworkCapabilitiesProto.NETWORK_SPECIFIER, mNetworkSpecifier.toString()); 1407 } 1408 1409 proto.write(NetworkCapabilitiesProto.CAN_REPORT_SIGNAL_STRENGTH, hasSignalStrength()); 1410 proto.write(NetworkCapabilitiesProto.SIGNAL_STRENGTH, mSignalStrength); 1411 1412 proto.end(token); 1413 } 1414 1415 /** 1416 * @hide 1417 */ 1418 public static String capabilityNamesOf(@NetCapability int[] capabilities) { 1419 StringJoiner joiner = new StringJoiner("|"); 1420 if (capabilities != null) { 1421 for (int c : capabilities) { 1422 joiner.add(capabilityNameOf(c)); 1423 } 1424 } 1425 return joiner.toString(); 1426 } 1427 1428 /** 1429 * @hide 1430 */ 1431 public static String capabilityNameOf(@NetCapability int capability) { 1432 switch (capability) { 1433 case NET_CAPABILITY_MMS: return "MMS"; 1434 case NET_CAPABILITY_SUPL: return "SUPL"; 1435 case NET_CAPABILITY_DUN: return "DUN"; 1436 case NET_CAPABILITY_FOTA: return "FOTA"; 1437 case NET_CAPABILITY_IMS: return "IMS"; 1438 case NET_CAPABILITY_CBS: return "CBS"; 1439 case NET_CAPABILITY_WIFI_P2P: return "WIFI_P2P"; 1440 case NET_CAPABILITY_IA: return "IA"; 1441 case NET_CAPABILITY_RCS: return "RCS"; 1442 case NET_CAPABILITY_XCAP: return "XCAP"; 1443 case NET_CAPABILITY_EIMS: return "EIMS"; 1444 case NET_CAPABILITY_NOT_METERED: return "NOT_METERED"; 1445 case NET_CAPABILITY_INTERNET: return "INTERNET"; 1446 case NET_CAPABILITY_NOT_RESTRICTED: return "NOT_RESTRICTED"; 1447 case NET_CAPABILITY_TRUSTED: return "TRUSTED"; 1448 case NET_CAPABILITY_NOT_VPN: return "NOT_VPN"; 1449 case NET_CAPABILITY_VALIDATED: return "VALIDATED"; 1450 case NET_CAPABILITY_CAPTIVE_PORTAL: return "CAPTIVE_PORTAL"; 1451 case NET_CAPABILITY_NOT_ROAMING: return "NOT_ROAMING"; 1452 case NET_CAPABILITY_FOREGROUND: return "FOREGROUND"; 1453 case NET_CAPABILITY_NOT_CONGESTED: return "NOT_CONGESTED"; 1454 case NET_CAPABILITY_NOT_SUSPENDED: return "NOT_SUSPENDED"; 1455 case NET_CAPABILITY_OEM_PAID: return "OEM_PAID"; 1456 default: return Integer.toString(capability); 1457 } 1458 } 1459 1460 /** 1461 * @hide 1462 */ 1463 public static String transportNamesOf(@Transport int[] types) { 1464 StringJoiner joiner = new StringJoiner("|"); 1465 if (types != null) { 1466 for (int t : types) { 1467 joiner.add(transportNameOf(t)); 1468 } 1469 } 1470 return joiner.toString(); 1471 } 1472 1473 /** 1474 * @hide 1475 */ 1476 public static String transportNameOf(@Transport int transport) { 1477 if (!isValidTransport(transport)) { 1478 return "UNKNOWN"; 1479 } 1480 return TRANSPORT_NAMES[transport]; 1481 } 1482 1483 private static void checkValidTransportType(@Transport int transport) { 1484 Preconditions.checkArgument( 1485 isValidTransport(transport), "Invalid TransportType " + transport); 1486 } 1487 1488 private static boolean isValidCapability(@NetworkCapabilities.NetCapability int capability) { 1489 return capability >= MIN_NET_CAPABILITY && capability <= MAX_NET_CAPABILITY; 1490 } 1491 1492 private static void checkValidCapability(@NetworkCapabilities.NetCapability int capability) { 1493 Preconditions.checkArgument(isValidCapability(capability), 1494 "NetworkCapability " + capability + "out of range"); 1495 } 1496} 1497