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