blob: 73c6b3daf2ec8369022ab108517df2e813b8883e [file] [log] [blame]
Robert Greenwalt1448f052014-04-08 13:41:39 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
Chalard Jean981dcca2020-02-06 18:31:19 +090019import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
20
Jeff Sharkeyde570312017-10-24 21:25:50 -060021import android.annotation.IntDef;
paulhud9736de2019-03-08 16:35:20 +080022import android.annotation.NonNull;
Etan Cohenca9fb562018-11-27 07:32:39 -080023import android.annotation.Nullable;
Chalard Jeane5e38502020-03-18 15:58:50 +090024import android.annotation.RequiresPermission;
Pavel Maltsevd9c9fff2018-03-22 11:41:32 -070025import android.annotation.SystemApi;
Jeff Sharkeya5ee62f2018-05-14 13:49:07 -060026import android.annotation.TestApi;
Artur Satayev26958002019-12-10 17:47:52 +000027import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060028import android.net.ConnectivityManager.NetworkCallback;
Mathew Inwood45d2c252018-09-14 12:35:36 +010029import android.os.Build;
Robert Greenwalt1448f052014-04-08 13:41:39 -070030import android.os.Parcel;
31import android.os.Parcelable;
Qingxi Li7cf06622020-01-17 17:54:27 -080032import android.os.Process;
Roshan Piuse38acab2020-01-16 12:17:17 -080033import android.text.TextUtils;
Chalard Jeanecacd5e2017-12-27 14:23:31 +090034import android.util.ArraySet;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080035import android.util.proto.ProtoOutputStream;
Robert Greenwalta7e148a2017-04-10 14:32:23 -070036
37import com.android.internal.annotations.VisibleForTesting;
Chalard Jeane5e38502020-03-18 15:58:50 +090038import com.android.internal.util.ArrayUtils;
Hugo Benichi9910dbc2017-03-22 18:29:58 +090039import com.android.internal.util.BitUtils;
Hugo Benichi16f0a942017-06-20 14:07:59 +090040import com.android.internal.util.Preconditions;
Etan Cohena7434272017-04-03 12:17:51 -070041
Jeff Sharkeyde570312017-10-24 21:25:50 -060042import java.lang.annotation.Retention;
43import java.lang.annotation.RetentionPolicy;
Cody Kestingf7ac9962020-03-16 18:15:28 -070044import java.util.Arrays;
Etan Cohena7434272017-04-03 12:17:51 -070045import java.util.Objects;
Chalard Jeanecacd5e2017-12-27 14:23:31 +090046import java.util.Set;
Hugo Benichieae7a222017-07-25 11:40:56 +090047import java.util.StringJoiner;
Robert Greenwalt1448f052014-04-08 13:41:39 -070048
49/**
Jeff Sharkey49bcd602017-11-09 13:11:50 -070050 * Representation of the capabilities of an active network. Instances are
51 * typically obtained through
Jeff Sharkey72f9c422017-10-27 17:22:59 -060052 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)}
53 * or {@link ConnectivityManager#getNetworkCapabilities(Network)}.
Jeff Sharkey72f9c422017-10-27 17:22:59 -060054 * <p>
55 * This replaces the old {@link ConnectivityManager#TYPE_MOBILE} method of
56 * network selection. Rather than indicate a need for Wi-Fi because an
57 * application needs high bandwidth and risk obsolescence when a new, fast
58 * network appears (like LTE), the application should specify it needs high
59 * bandwidth. Similarly if an application needs an unmetered network for a bulk
60 * transfer it can specify that rather than assuming all cellular based
61 * connections are metered and all Wi-Fi based connections are not.
Robert Greenwalt1448f052014-04-08 13:41:39 -070062 */
63public final class NetworkCapabilities implements Parcelable {
Etan Cohena7434272017-04-03 12:17:51 -070064 private static final String TAG = "NetworkCapabilities";
65
lucaslin783f2212019-10-22 18:27:33 +080066 // Set to true when private DNS is broken.
67 private boolean mPrivateDnsBroken;
68
Roshan Piuse38acab2020-01-16 12:17:17 -080069 /**
70 * Uid of the app making the request.
71 */
72 private int mRequestorUid;
73
74 /**
75 * Package name of the app making the request.
76 */
77 private String mRequestorPackageName;
78
Robert Greenwalt01d004e2014-05-18 15:24:21 -070079 public NetworkCapabilities() {
Lorenzo Colittif7058f52015-04-27 11:31:55 +090080 clearAll();
Lorenzo Colitti260a36d2015-07-08 12:49:04 +090081 mNetworkCapabilities = DEFAULT_CAPABILITIES;
Robert Greenwalt01d004e2014-05-18 15:24:21 -070082 }
83
84 public NetworkCapabilities(NetworkCapabilities nc) {
85 if (nc != null) {
Chalard Jean4c4bc932018-05-18 23:48:49 +090086 set(nc);
Robert Greenwalt01d004e2014-05-18 15:24:21 -070087 }
88 }
Robert Greenwalt1448f052014-04-08 13:41:39 -070089
90 /**
Lorenzo Colittif7058f52015-04-27 11:31:55 +090091 * Completely clears the contents of this object, removing even the capabilities that are set
92 * by default when the object is constructed.
Chalard Jeane5e38502020-03-18 15:58:50 +090093 * @hide
Lorenzo Colittif7058f52015-04-27 11:31:55 +090094 */
95 public void clearAll() {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -080096 mNetworkCapabilities = mTransportTypes = mUnwantedNetworkCapabilities = 0;
Jeff Sharkey49bcd602017-11-09 13:11:50 -070097 mLinkUpBandwidthKbps = mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colittif7058f52015-04-27 11:31:55 +090098 mNetworkSpecifier = null;
Etan Cohenca9fb562018-11-27 07:32:39 -080099 mTransportInfo = null;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900100 mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900101 mUids = null;
Cody Kestingf7ac9962020-03-16 18:15:28 -0700102 mAdministratorUids = new int[0];
Qingxi Li7cf06622020-01-17 17:54:27 -0800103 mOwnerUid = Process.INVALID_UID;
Chalard Jeanb03a6222018-04-11 21:09:10 +0900104 mSSID = null;
lucaslin783f2212019-10-22 18:27:33 +0800105 mPrivateDnsBroken = false;
Roshan Piuse38acab2020-01-16 12:17:17 -0800106 mRequestorUid = Process.INVALID_UID;
107 mRequestorPackageName = null;
Lorenzo Colittif7058f52015-04-27 11:31:55 +0900108 }
109
110 /**
Chalard Jean4c4bc932018-05-18 23:48:49 +0900111 * Set all contents of this object to the contents of a NetworkCapabilities.
112 * @hide
113 */
paulhud9736de2019-03-08 16:35:20 +0800114 public void set(@NonNull NetworkCapabilities nc) {
Chalard Jean4c4bc932018-05-18 23:48:49 +0900115 mNetworkCapabilities = nc.mNetworkCapabilities;
116 mTransportTypes = nc.mTransportTypes;
117 mLinkUpBandwidthKbps = nc.mLinkUpBandwidthKbps;
118 mLinkDownBandwidthKbps = nc.mLinkDownBandwidthKbps;
119 mNetworkSpecifier = nc.mNetworkSpecifier;
Etan Cohenca9fb562018-11-27 07:32:39 -0800120 mTransportInfo = nc.mTransportInfo;
Chalard Jean4c4bc932018-05-18 23:48:49 +0900121 mSignalStrength = nc.mSignalStrength;
122 setUids(nc.mUids); // Will make the defensive copy
Chalard Jean981dcca2020-02-06 18:31:19 +0900123 setAdministratorUids(nc.getAdministratorUids());
Qingxi Li7cf06622020-01-17 17:54:27 -0800124 mOwnerUid = nc.mOwnerUid;
Chalard Jean4c4bc932018-05-18 23:48:49 +0900125 mUnwantedNetworkCapabilities = nc.mUnwantedNetworkCapabilities;
126 mSSID = nc.mSSID;
lucaslin783f2212019-10-22 18:27:33 +0800127 mPrivateDnsBroken = nc.mPrivateDnsBroken;
Roshan Piuse38acab2020-01-16 12:17:17 -0800128 mRequestorUid = nc.mRequestorUid;
129 mRequestorPackageName = nc.mRequestorPackageName;
Chalard Jean4c4bc932018-05-18 23:48:49 +0900130 }
131
132 /**
Robert Greenwalt1448f052014-04-08 13:41:39 -0700133 * Represents the network's capabilities. If any are specified they will be satisfied
134 * by any Network that matches all of them.
135 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100136 @UnsupportedAppUsage
Lorenzo Colittif7058f52015-04-27 11:31:55 +0900137 private long mNetworkCapabilities;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700138
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800139 /**
140 * If any capabilities specified here they must not exist in the matching Network.
141 */
142 private long mUnwantedNetworkCapabilities;
143
Jeff Sharkeyde570312017-10-24 21:25:50 -0600144 /** @hide */
145 @Retention(RetentionPolicy.SOURCE)
146 @IntDef(prefix = { "NET_CAPABILITY_" }, value = {
147 NET_CAPABILITY_MMS,
148 NET_CAPABILITY_SUPL,
149 NET_CAPABILITY_DUN,
150 NET_CAPABILITY_FOTA,
151 NET_CAPABILITY_IMS,
152 NET_CAPABILITY_CBS,
153 NET_CAPABILITY_WIFI_P2P,
154 NET_CAPABILITY_IA,
155 NET_CAPABILITY_RCS,
156 NET_CAPABILITY_XCAP,
157 NET_CAPABILITY_EIMS,
158 NET_CAPABILITY_NOT_METERED,
159 NET_CAPABILITY_INTERNET,
160 NET_CAPABILITY_NOT_RESTRICTED,
161 NET_CAPABILITY_TRUSTED,
162 NET_CAPABILITY_NOT_VPN,
163 NET_CAPABILITY_VALIDATED,
164 NET_CAPABILITY_CAPTIVE_PORTAL,
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600165 NET_CAPABILITY_NOT_ROAMING,
Jeff Sharkeyde570312017-10-24 21:25:50 -0600166 NET_CAPABILITY_FOREGROUND,
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900167 NET_CAPABILITY_NOT_CONGESTED,
Chalard Jean804b8fb2018-01-30 22:41:41 +0900168 NET_CAPABILITY_NOT_SUSPENDED,
Pavel Maltsev43403202018-01-30 17:19:44 -0800169 NET_CAPABILITY_OEM_PAID,
lucasline252a742019-03-12 13:08:03 +0800170 NET_CAPABILITY_MCX,
171 NET_CAPABILITY_PARTIAL_CONNECTIVITY,
Jack Yu30be5e52020-04-02 15:34:33 -0700172 NET_CAPABILITY_TEMPORARILY_NOT_METERED,
Jeff Sharkeyde570312017-10-24 21:25:50 -0600173 })
174 public @interface NetCapability { }
175
Robert Greenwalt1448f052014-04-08 13:41:39 -0700176 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700177 * Indicates this is a network that has the ability to reach the
178 * carrier's MMSC for sending and receiving MMS messages.
Robert Greenwalt1448f052014-04-08 13:41:39 -0700179 */
180 public static final int NET_CAPABILITY_MMS = 0;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700181
182 /**
183 * Indicates this is a network that has the ability to reach the carrier's
184 * SUPL server, used to retrieve GPS information.
185 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700186 public static final int NET_CAPABILITY_SUPL = 1;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700187
188 /**
189 * Indicates this is a network that has the ability to reach the carrier's
190 * DUN or tethering gateway.
191 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700192 public static final int NET_CAPABILITY_DUN = 2;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700193
194 /**
195 * Indicates this is a network that has the ability to reach the carrier's
196 * FOTA portal, used for over the air updates.
197 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700198 public static final int NET_CAPABILITY_FOTA = 3;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700199
200 /**
201 * Indicates this is a network that has the ability to reach the carrier's
202 * IMS servers, used for network registration and signaling.
203 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700204 public static final int NET_CAPABILITY_IMS = 4;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700205
206 /**
207 * Indicates this is a network that has the ability to reach the carrier's
208 * CBS servers, used for carrier specific services.
209 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700210 public static final int NET_CAPABILITY_CBS = 5;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700211
212 /**
213 * Indicates this is a network that has the ability to reach a Wi-Fi direct
214 * peer.
215 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700216 public static final int NET_CAPABILITY_WIFI_P2P = 6;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700217
218 /**
219 * Indicates this is a network that has the ability to reach a carrier's
220 * Initial Attach servers.
221 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700222 public static final int NET_CAPABILITY_IA = 7;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700223
224 /**
225 * Indicates this is a network that has the ability to reach a carrier's
226 * RCS servers, used for Rich Communication Services.
227 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700228 public static final int NET_CAPABILITY_RCS = 8;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700229
230 /**
231 * Indicates this is a network that has the ability to reach a carrier's
232 * XCAP servers, used for configuration and control.
233 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700234 public static final int NET_CAPABILITY_XCAP = 9;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700235
236 /**
237 * Indicates this is a network that has the ability to reach a carrier's
Robert Greenwalt4bd43892015-07-09 14:49:35 -0700238 * Emergency IMS servers or other services, used for network signaling
239 * during emergency calls.
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700240 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700241 public static final int NET_CAPABILITY_EIMS = 10;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700242
243 /**
244 * Indicates that this network is unmetered.
245 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700246 public static final int NET_CAPABILITY_NOT_METERED = 11;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700247
248 /**
249 * Indicates that this network should be able to reach the internet.
250 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700251 public static final int NET_CAPABILITY_INTERNET = 12;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700252
253 /**
254 * Indicates that this network is available for general use. If this is not set
255 * applications should not attempt to communicate on this network. Note that this
256 * is simply informative and not enforcement - enforcement is handled via other means.
257 * Set by default.
258 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700259 public static final int NET_CAPABILITY_NOT_RESTRICTED = 13;
260
Robert Greenwalt16e12ab2014-07-08 15:31:37 -0700261 /**
262 * Indicates that the user has indicated implicit trust of this network. This
263 * generally means it's a sim-selected carrier, a plugged in ethernet, a paired
264 * BT device or a wifi the user asked to connect to. Untrusted networks
265 * are probably limited to unknown wifi AP. Set by default.
266 */
267 public static final int NET_CAPABILITY_TRUSTED = 14;
268
Paul Jensen76b610a2015-03-18 09:33:07 -0400269 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400270 * Indicates that this network is not a VPN. This capability is set by default and should be
Paul Jensen76b610a2015-03-18 09:33:07 -0400271 * explicitly cleared for VPN networks.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400272 */
273 public static final int NET_CAPABILITY_NOT_VPN = 15;
274
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900275 /**
276 * Indicates that connectivity on this network was successfully validated. For example, for a
277 * network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully
278 * detected.
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900279 */
280 public static final int NET_CAPABILITY_VALIDATED = 16;
Robert Greenwalt16e12ab2014-07-08 15:31:37 -0700281
Paul Jensen3d194ea2015-06-16 14:27:36 -0400282 /**
283 * Indicates that this network was found to have a captive portal in place last time it was
284 * probed.
285 */
286 public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17;
287
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900288 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600289 * Indicates that this network is not roaming.
290 */
291 public static final int NET_CAPABILITY_NOT_ROAMING = 18;
292
293 /**
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900294 * Indicates that this network is available for use by apps, and not a network that is being
295 * kept up in the background to facilitate fast network switching.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900296 */
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600297 public static final int NET_CAPABILITY_FOREGROUND = 19;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900298
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900299 /**
300 * Indicates that this network is not congested.
301 * <p>
Jeff Sharkey0a5570d2018-04-10 12:38:29 -0600302 * When a network is congested, applications should defer network traffic
303 * that can be done at a later time, such as uploading analytics.
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900304 */
305 public static final int NET_CAPABILITY_NOT_CONGESTED = 20;
306
Chalard Jean804b8fb2018-01-30 22:41:41 +0900307 /**
308 * Indicates that this network is not currently suspended.
309 * <p>
310 * When a network is suspended, the network's IP addresses and any connections
311 * established on the network remain valid, but the network is temporarily unable
312 * to transfer data. This can happen, for example, if a cellular network experiences
313 * a temporary loss of signal, such as when driving through a tunnel, etc.
314 * A network with this capability is not suspended, so is expected to be able to
315 * transfer data.
316 */
317 public static final int NET_CAPABILITY_NOT_SUSPENDED = 21;
318
Pavel Maltsev43403202018-01-30 17:19:44 -0800319 /**
320 * Indicates that traffic that goes through this network is paid by oem. For example,
321 * this network can be used by system apps to upload telemetry data.
322 * @hide
323 */
Pavel Maltsevd9c9fff2018-03-22 11:41:32 -0700324 @SystemApi
Pavel Maltsev43403202018-01-30 17:19:44 -0800325 public static final int NET_CAPABILITY_OEM_PAID = 22;
326
Amit Mahajanfd3ee572019-02-20 15:04:30 -0800327 /**
328 * Indicates this is a network that has the ability to reach a carrier's Mission Critical
329 * servers.
330 */
331 public static final int NET_CAPABILITY_MCX = 23;
332
lucasline252a742019-03-12 13:08:03 +0800333 /**
334 * Indicates that this network was tested to only provide partial connectivity.
335 * @hide
336 */
337 @SystemApi
338 public static final int NET_CAPABILITY_PARTIAL_CONNECTIVITY = 24;
339
Jack Yu30be5e52020-04-02 15:34:33 -0700340 /**
341 * This capability will be set for networks that are generally metered, but are currently
342 * unmetered, e.g., because the user is in a particular area. This capability can be changed at
343 * any time. When it is removed, applications are responsible for stopping any data transfer
344 * that should not occur on a metered network.
345 */
346 public static final int NET_CAPABILITY_TEMPORARILY_NOT_METERED = 25;
347
Robert Greenwalt1448f052014-04-08 13:41:39 -0700348 private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS;
Jack Yu30be5e52020-04-02 15:34:33 -0700349 private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700350
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700351 /**
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900352 * Network capabilities that are expected to be mutable, i.e., can change while a particular
353 * network is connected.
354 */
355 private static final long MUTABLE_CAPABILITIES =
356 // TRUSTED can change when user explicitly connects to an untrusted network in Settings.
357 // http://b/18206275
Chalard Jean804b8fb2018-01-30 22:41:41 +0900358 (1 << NET_CAPABILITY_TRUSTED)
359 | (1 << NET_CAPABILITY_VALIDATED)
360 | (1 << NET_CAPABILITY_CAPTIVE_PORTAL)
361 | (1 << NET_CAPABILITY_NOT_ROAMING)
362 | (1 << NET_CAPABILITY_FOREGROUND)
363 | (1 << NET_CAPABILITY_NOT_CONGESTED)
lucasline252a742019-03-12 13:08:03 +0800364 | (1 << NET_CAPABILITY_NOT_SUSPENDED)
Jack Yu30be5e52020-04-02 15:34:33 -0700365 | (1 << NET_CAPABILITY_PARTIAL_CONNECTIVITY
366 | (1 << NET_CAPABILITY_TEMPORARILY_NOT_METERED));
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900367
368 /**
369 * Network capabilities that are not allowed in NetworkRequests. This exists because the
370 * NetworkFactory / NetworkAgent model does not deal well with the situation where a
371 * capability's presence cannot be known in advance. If such a capability is requested, then we
372 * can get into a cycle where the NetworkFactory endlessly churns out NetworkAgents that then
373 * get immediately torn down because they do not have the requested capability.
374 */
375 private static final long NON_REQUESTABLE_CAPABILITIES =
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900376 MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_TRUSTED);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900377
378 /**
379 * Capabilities that are set by default when the object is constructed.
380 */
381 private static final long DEFAULT_CAPABILITIES =
382 (1 << NET_CAPABILITY_NOT_RESTRICTED) |
383 (1 << NET_CAPABILITY_TRUSTED) |
384 (1 << NET_CAPABILITY_NOT_VPN);
385
386 /**
Paul Jensen487ffe72015-07-24 15:57:11 -0400387 * Capabilities that suggest that a network is restricted.
Pavel Maltsev4af91072018-03-07 14:33:22 -0800388 * {@see #maybeMarkCapabilitiesRestricted}, {@see #FORCE_RESTRICTED_CAPABILITIES}
Paul Jensen487ffe72015-07-24 15:57:11 -0400389 */
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700390 @VisibleForTesting
391 /* package */ static final long RESTRICTED_CAPABILITIES =
Paul Jensen487ffe72015-07-24 15:57:11 -0400392 (1 << NET_CAPABILITY_CBS) |
393 (1 << NET_CAPABILITY_DUN) |
394 (1 << NET_CAPABILITY_EIMS) |
395 (1 << NET_CAPABILITY_FOTA) |
396 (1 << NET_CAPABILITY_IA) |
397 (1 << NET_CAPABILITY_IMS) |
398 (1 << NET_CAPABILITY_RCS) |
Amit Mahajanfd3ee572019-02-20 15:04:30 -0800399 (1 << NET_CAPABILITY_XCAP) |
400 (1 << NET_CAPABILITY_MCX);
Pavel Maltsev4af91072018-03-07 14:33:22 -0800401
402 /**
403 * Capabilities that force network to be restricted.
404 * {@see #maybeMarkCapabilitiesRestricted}.
405 */
406 private static final long FORCE_RESTRICTED_CAPABILITIES =
Pavel Maltsev43403202018-01-30 17:19:44 -0800407 (1 << NET_CAPABILITY_OEM_PAID);
Paul Jensen487ffe72015-07-24 15:57:11 -0400408
409 /**
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700410 * Capabilities that suggest that a network is unrestricted.
411 * {@see #maybeMarkCapabilitiesRestricted}.
412 */
413 @VisibleForTesting
414 /* package */ static final long UNRESTRICTED_CAPABILITIES =
415 (1 << NET_CAPABILITY_INTERNET) |
416 (1 << NET_CAPABILITY_MMS) |
417 (1 << NET_CAPABILITY_SUPL) |
418 (1 << NET_CAPABILITY_WIFI_P2P);
419
420 /**
lucasline252a742019-03-12 13:08:03 +0800421 * Capabilities that are managed by ConnectivityService.
422 */
423 private static final long CONNECTIVITY_MANAGED_CAPABILITIES =
424 (1 << NET_CAPABILITY_VALIDATED)
425 | (1 << NET_CAPABILITY_CAPTIVE_PORTAL)
426 | (1 << NET_CAPABILITY_FOREGROUND)
427 | (1 << NET_CAPABILITY_PARTIAL_CONNECTIVITY);
428
429 /**
Chalard Jean09c48e42020-03-25 10:33:55 +0000430 * Capabilities that are allowed for test networks. This list must be set so that it is safe
431 * for an unprivileged user to create a network with these capabilities via shell. As such,
432 * it must never contain capabilities that are generally useful to the system, such as
433 * INTERNET, IMS, SUPL, etc.
434 */
435 private static final long TEST_NETWORKS_ALLOWED_CAPABILITIES =
436 (1 << NET_CAPABILITY_NOT_METERED)
Jack Yu30be5e52020-04-02 15:34:33 -0700437 | (1 << NET_CAPABILITY_TEMPORARILY_NOT_METERED)
Chalard Jean09c48e42020-03-25 10:33:55 +0000438 | (1 << NET_CAPABILITY_NOT_RESTRICTED)
439 | (1 << NET_CAPABILITY_NOT_VPN)
440 | (1 << NET_CAPABILITY_NOT_ROAMING)
441 | (1 << NET_CAPABILITY_NOT_CONGESTED)
442 | (1 << NET_CAPABILITY_NOT_SUSPENDED);
443
444 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700445 * Adds the given capability to this {@code NetworkCapability} instance.
Chalard Jeane5e38502020-03-18 15:58:50 +0900446 * Note that when searching for a network to satisfy a request, all capabilities
447 * requested must be satisfied.
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700448 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600449 * @param capability the capability to be added.
Pierre Imaic8419a82016-03-22 17:54:54 +0900450 * @return This NetworkCapabilities instance, to facilitate chaining.
Chalard Jeane5e38502020-03-18 15:58:50 +0900451 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700452 */
paulhud9736de2019-03-08 16:35:20 +0800453 public @NonNull NetworkCapabilities addCapability(@NetCapability int capability) {
Aaron Huange6b62392019-09-20 22:52:54 +0800454 // If the given capability was previously added to the list of unwanted capabilities
455 // then the capability will also be removed from the list of unwanted capabilities.
456 // TODO: Consider adding unwanted capabilities to the public API and mention this
457 // in the documentation.
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800458 checkValidCapability(capability);
Robert Greenwalt7569f182014-06-08 16:42:59 -0700459 mNetworkCapabilities |= 1 << capability;
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800460 mUnwantedNetworkCapabilities &= ~(1 << capability); // remove from unwanted capability list
Robert Greenwalt7569f182014-06-08 16:42:59 -0700461 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700462 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700463
464 /**
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800465 * Adds the given capability to the list of unwanted capabilities of this
Chalard Jeane5e38502020-03-18 15:58:50 +0900466 * {@code NetworkCapability} instance. Note that when searching for a network to
467 * satisfy a request, the network must not contain any capability from unwanted capability
468 * list.
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800469 * <p>
470 * If the capability was previously added to the list of required capabilities (for
471 * example, it was there by default or added using {@link #addCapability(int)} method), then
472 * it will be removed from the list of required capabilities as well.
473 *
474 * @see #addCapability(int)
475 * @hide
476 */
477 public void addUnwantedCapability(@NetCapability int capability) {
478 checkValidCapability(capability);
479 mUnwantedNetworkCapabilities |= 1 << capability;
480 mNetworkCapabilities &= ~(1 << capability); // remove from requested capabilities
481 }
482
483 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700484 * Removes (if found) the given capability from this {@code NetworkCapability} instance.
485 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600486 * @param capability the capability to be removed.
Pierre Imaic8419a82016-03-22 17:54:54 +0900487 * @return This NetworkCapabilities instance, to facilitate chaining.
Chalard Jeane5e38502020-03-18 15:58:50 +0900488 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700489 */
paulhud9736de2019-03-08 16:35:20 +0800490 public @NonNull NetworkCapabilities removeCapability(@NetCapability int capability) {
Aaron Huange6b62392019-09-20 22:52:54 +0800491 // Note that this method removes capabilities that were added via addCapability(int),
492 // addUnwantedCapability(int) or setCapabilities(int[], int[]).
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800493 checkValidCapability(capability);
494 final long mask = ~(1 << capability);
495 mNetworkCapabilities &= mask;
496 mUnwantedNetworkCapabilities &= mask;
Robert Greenwalt7569f182014-06-08 16:42:59 -0700497 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700498 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700499
500 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600501 * Sets (or clears) the given capability on this {@link NetworkCapabilities}
502 * instance.
Chalard Jeane5e38502020-03-18 15:58:50 +0900503 * @hide
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600504 */
paulhud9736de2019-03-08 16:35:20 +0800505 public @NonNull NetworkCapabilities setCapability(@NetCapability int capability,
506 boolean value) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600507 if (value) {
508 addCapability(capability);
509 } else {
510 removeCapability(capability);
511 }
512 return this;
513 }
514
515 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700516 * Gets all the capabilities set on this {@code NetworkCapability} instance.
517 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600518 * @return an array of capability values for this instance.
Robert Greenwalt7569f182014-06-08 16:42:59 -0700519 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700520 */
Artur Satayevf0b7d0b2019-11-04 11:16:45 +0000521 @UnsupportedAppUsage
Jeff Sharkeya5ee62f2018-05-14 13:49:07 -0600522 @TestApi
Jeff Sharkeyde570312017-10-24 21:25:50 -0600523 public @NetCapability int[] getCapabilities() {
Hugo Benichi9910dbc2017-03-22 18:29:58 +0900524 return BitUtils.unpackBits(mNetworkCapabilities);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700525 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700526
527 /**
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800528 * Gets all the unwanted capabilities set on this {@code NetworkCapability} instance.
529 *
530 * @return an array of unwanted capability values for this instance.
531 * @hide
532 */
533 public @NetCapability int[] getUnwantedCapabilities() {
534 return BitUtils.unpackBits(mUnwantedNetworkCapabilities);
535 }
536
537
538 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600539 * Sets all the capabilities set on this {@code NetworkCapability} instance.
Jeff Sharkey49bcd602017-11-09 13:11:50 -0700540 * This overwrites any existing capabilities.
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600541 *
542 * @hide
543 */
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800544 public void setCapabilities(@NetCapability int[] capabilities,
545 @NetCapability int[] unwantedCapabilities) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600546 mNetworkCapabilities = BitUtils.packBits(capabilities);
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800547 mUnwantedNetworkCapabilities = BitUtils.packBits(unwantedCapabilities);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600548 }
549
550 /**
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800551 * @deprecated use {@link #setCapabilities(int[], int[])}
552 * @hide
553 */
554 @Deprecated
555 public void setCapabilities(@NetCapability int[] capabilities) {
556 setCapabilities(capabilities, new int[] {});
557 }
558
559 /**
560 * Tests for the presence of a capability on this instance.
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700561 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600562 * @param capability the capabilities to be tested for.
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700563 * @return {@code true} if set on this instance.
564 */
Jeff Sharkeyde570312017-10-24 21:25:50 -0600565 public boolean hasCapability(@NetCapability int capability) {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800566 return isValidCapability(capability)
567 && ((mNetworkCapabilities & (1 << capability)) != 0);
568 }
569
570 /** @hide */
571 public boolean hasUnwantedCapability(@NetCapability int capability) {
572 return isValidCapability(capability)
573 && ((mUnwantedNetworkCapabilities & (1 << capability)) != 0);
Robert Greenwalt5c55e332014-05-08 00:02:04 -0700574 }
Robert Greenwalt1448f052014-04-08 13:41:39 -0700575
lucasline252a742019-03-12 13:08:03 +0800576 /**
577 * Check if this NetworkCapabilities has system managed capabilities or not.
578 * @hide
579 */
580 public boolean hasConnectivityManagedCapability() {
581 return ((mNetworkCapabilities & CONNECTIVITY_MANAGED_CAPABILITIES) != 0);
582 }
583
Pavel Maltseve18ef262018-03-07 11:13:04 -0800584 /** Note this method may result in having the same capability in wanted and unwanted lists. */
paulhud9736de2019-03-08 16:35:20 +0800585 private void combineNetCapabilities(@NonNull NetworkCapabilities nc) {
Robert Greenwalt1448f052014-04-08 13:41:39 -0700586 this.mNetworkCapabilities |= nc.mNetworkCapabilities;
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800587 this.mUnwantedNetworkCapabilities |= nc.mUnwantedNetworkCapabilities;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700588 }
589
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900590 /**
591 * Convenience function that returns a human-readable description of the first mutable
592 * capability we find. Used to present an error message to apps that request mutable
593 * capabilities.
594 *
595 * @hide
596 */
paulhud9736de2019-03-08 16:35:20 +0800597 public @Nullable String describeFirstNonRequestableCapability() {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800598 final long nonRequestable = (mNetworkCapabilities | mUnwantedNetworkCapabilities)
599 & NON_REQUESTABLE_CAPABILITIES;
600
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900601 if (nonRequestable != 0) {
602 return capabilityNameOf(BitUtils.unpackBits(nonRequestable)[0]);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900603 }
604 if (mLinkUpBandwidthKbps != 0 || mLinkDownBandwidthKbps != 0) return "link bandwidth";
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900605 if (hasSignalStrength()) return "signalStrength";
lucaslin783f2212019-10-22 18:27:33 +0800606 if (isPrivateDnsBroken()) {
607 return "privateDnsBroken";
608 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900609 return null;
610 }
611
paulhud9736de2019-03-08 16:35:20 +0800612 private boolean satisfiedByNetCapabilities(@NonNull NetworkCapabilities nc,
613 boolean onlyImmutable) {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800614 long requestedCapabilities = mNetworkCapabilities;
615 long requestedUnwantedCapabilities = mUnwantedNetworkCapabilities;
616 long providedCapabilities = nc.mNetworkCapabilities;
617
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900618 if (onlyImmutable) {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800619 requestedCapabilities &= ~MUTABLE_CAPABILITIES;
620 requestedUnwantedCapabilities &= ~MUTABLE_CAPABILITIES;
Lorenzo Colitti260a36d2015-07-08 12:49:04 +0900621 }
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800622 return ((providedCapabilities & requestedCapabilities) == requestedCapabilities)
623 && ((requestedUnwantedCapabilities & providedCapabilities) == 0);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700624 }
625
Robert Greenwalt06314e42014-10-29 14:04:06 -0700626 /** @hide */
paulhud9736de2019-03-08 16:35:20 +0800627 public boolean equalsNetCapabilities(@NonNull NetworkCapabilities nc) {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800628 return (nc.mNetworkCapabilities == this.mNetworkCapabilities)
629 && (nc.mUnwantedNetworkCapabilities == this.mUnwantedNetworkCapabilities);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700630 }
631
paulhud9736de2019-03-08 16:35:20 +0800632 private boolean equalsNetCapabilitiesRequestable(@NonNull NetworkCapabilities that) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900633 return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) ==
Pavel Maltsev1cd48da2018-02-01 11:16:02 -0800634 (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES))
635 && ((this.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) ==
636 (that.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900637 }
638
Robert Greenwalt1448f052014-04-08 13:41:39 -0700639 /**
paulhu18354322020-01-09 17:08:11 +0800640 * Deduces that all the capabilities it provides are typically provided by restricted networks
641 * or not.
Paul Jensen487ffe72015-07-24 15:57:11 -0400642 *
paulhu18354322020-01-09 17:08:11 +0800643 * @return {@code true} if the network should be restricted.
Paul Jensen487ffe72015-07-24 15:57:11 -0400644 * @hide
645 */
paulhu18354322020-01-09 17:08:11 +0800646 public boolean deduceRestrictedCapability() {
Pavel Maltsev4af91072018-03-07 14:33:22 -0800647 // Check if we have any capability that forces the network to be restricted.
648 final boolean forceRestrictedCapability =
649 (mNetworkCapabilities & FORCE_RESTRICTED_CAPABILITIES) != 0;
650
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700651 // Verify there aren't any unrestricted capabilities. If there are we say
Pavel Maltsev4af91072018-03-07 14:33:22 -0800652 // the whole thing is unrestricted unless it is forced to be restricted.
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700653 final boolean hasUnrestrictedCapabilities =
Pavel Maltsev4af91072018-03-07 14:33:22 -0800654 (mNetworkCapabilities & UNRESTRICTED_CAPABILITIES) != 0;
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700655
656 // Must have at least some restricted capabilities.
657 final boolean hasRestrictedCapabilities =
Pavel Maltsev4af91072018-03-07 14:33:22 -0800658 (mNetworkCapabilities & RESTRICTED_CAPABILITIES) != 0;
Robert Greenwalta7e148a2017-04-10 14:32:23 -0700659
paulhu18354322020-01-09 17:08:11 +0800660 return forceRestrictedCapability
661 || (hasRestrictedCapabilities && !hasUnrestrictedCapabilities);
662 }
663
664 /**
665 * Removes the NET_CAPABILITY_NOT_RESTRICTED capability if deducing the network is restricted.
666 *
667 * @hide
668 */
669 public void maybeMarkCapabilitiesRestricted() {
670 if (deduceRestrictedCapability()) {
Paul Jensen487ffe72015-07-24 15:57:11 -0400671 removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
Paul Jensenaae613d2015-08-19 11:06:15 -0400672 }
Paul Jensen487ffe72015-07-24 15:57:11 -0400673 }
674
675 /**
Chalard Jean09c48e42020-03-25 10:33:55 +0000676 * Test networks have strong restrictions on what capabilities they can have. Enforce these
677 * restrictions.
678 * @hide
679 */
680 public void restrictCapabilitesForTestNetwork() {
681 final long originalCapabilities = mNetworkCapabilities;
682 final NetworkSpecifier originalSpecifier = mNetworkSpecifier;
683 clearAll();
684 // Reset the transports to only contain TRANSPORT_TEST.
685 mTransportTypes = (1 << TRANSPORT_TEST);
686 mNetworkCapabilities = originalCapabilities & TEST_NETWORKS_ALLOWED_CAPABILITIES;
687 mNetworkSpecifier = originalSpecifier;
688 }
689
690 /**
Robert Greenwalt1448f052014-04-08 13:41:39 -0700691 * Representing the transport type. Apps should generally not care about transport. A
692 * request for a fast internet connection could be satisfied by a number of different
693 * transports. If any are specified here it will be satisfied a Network that matches
694 * any of them. If a caller doesn't care about the transport it should not specify any.
695 */
696 private long mTransportTypes;
697
Jeff Sharkeyde570312017-10-24 21:25:50 -0600698 /** @hide */
699 @Retention(RetentionPolicy.SOURCE)
700 @IntDef(prefix = { "TRANSPORT_" }, value = {
701 TRANSPORT_CELLULAR,
702 TRANSPORT_WIFI,
703 TRANSPORT_BLUETOOTH,
704 TRANSPORT_ETHERNET,
705 TRANSPORT_VPN,
706 TRANSPORT_WIFI_AWARE,
707 TRANSPORT_LOWPAN,
Benedict Wong89ce5e32018-11-14 17:40:55 -0800708 TRANSPORT_TEST,
Jeff Sharkeyde570312017-10-24 21:25:50 -0600709 })
710 public @interface Transport { }
711
Robert Greenwalt1448f052014-04-08 13:41:39 -0700712 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700713 * Indicates this network uses a Cellular transport.
Robert Greenwalt1448f052014-04-08 13:41:39 -0700714 */
715 public static final int TRANSPORT_CELLULAR = 0;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700716
717 /**
718 * Indicates this network uses a Wi-Fi transport.
719 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700720 public static final int TRANSPORT_WIFI = 1;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700721
722 /**
723 * Indicates this network uses a Bluetooth transport.
724 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700725 public static final int TRANSPORT_BLUETOOTH = 2;
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700726
727 /**
728 * Indicates this network uses an Ethernet transport.
729 */
Robert Greenwalt1448f052014-04-08 13:41:39 -0700730 public static final int TRANSPORT_ETHERNET = 3;
731
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400732 /**
733 * Indicates this network uses a VPN transport.
734 */
735 public static final int TRANSPORT_VPN = 4;
736
Etan Cohen305ea282016-06-20 09:27:12 -0700737 /**
Etan Cohen0849ded2016-10-26 11:22:06 -0700738 * Indicates this network uses a Wi-Fi Aware transport.
Etan Cohen305ea282016-06-20 09:27:12 -0700739 */
Etan Cohen0849ded2016-10-26 11:22:06 -0700740 public static final int TRANSPORT_WIFI_AWARE = 5;
Etan Cohen305ea282016-06-20 09:27:12 -0700741
Robert Quattlebaum5f915762017-05-15 15:53:29 -0700742 /**
743 * Indicates this network uses a LoWPAN transport.
Robert Quattlebaum5f915762017-05-15 15:53:29 -0700744 */
745 public static final int TRANSPORT_LOWPAN = 6;
746
Benedict Wong89ce5e32018-11-14 17:40:55 -0800747 /**
748 * Indicates this network uses a Test-only virtual interface as a transport.
749 *
750 * @hide
751 */
752 @TestApi
753 public static final int TRANSPORT_TEST = 7;
754
Hugo Benichi6a9bb8e2017-03-15 23:05:01 +0900755 /** @hide */
756 public static final int MIN_TRANSPORT = TRANSPORT_CELLULAR;
757 /** @hide */
Benedict Wong89ce5e32018-11-14 17:40:55 -0800758 public static final int MAX_TRANSPORT = TRANSPORT_TEST;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700759
Hugo Benichi16f0a942017-06-20 14:07:59 +0900760 /** @hide */
Jeff Sharkeyde570312017-10-24 21:25:50 -0600761 public static boolean isValidTransport(@Transport int transportType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900762 return (MIN_TRANSPORT <= transportType) && (transportType <= MAX_TRANSPORT);
763 }
764
Hugo Benichi9910dbc2017-03-22 18:29:58 +0900765 private static final String[] TRANSPORT_NAMES = {
766 "CELLULAR",
767 "WIFI",
768 "BLUETOOTH",
769 "ETHERNET",
770 "VPN",
Robert Quattlebaum5f915762017-05-15 15:53:29 -0700771 "WIFI_AWARE",
Benedict Wong89ce5e32018-11-14 17:40:55 -0800772 "LOWPAN",
773 "TEST"
Hugo Benichi9910dbc2017-03-22 18:29:58 +0900774 };
775
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700776 /**
777 * Adds the given transport type to this {@code NetworkCapability} instance.
Chalard Jeane5e38502020-03-18 15:58:50 +0900778 * Multiple transports may be applied. Note that when searching
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700779 * for a network to satisfy a request, any listed in the request will satisfy the request.
780 * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a
781 * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network
782 * to be selected. This is logically different than
783 * {@code NetworkCapabilities.NET_CAPABILITY_*} listed above.
784 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600785 * @param transportType the transport type to be added.
Pierre Imaic8419a82016-03-22 17:54:54 +0900786 * @return This NetworkCapabilities instance, to facilitate chaining.
Chalard Jeane5e38502020-03-18 15:58:50 +0900787 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700788 */
paulhud9736de2019-03-08 16:35:20 +0800789 public @NonNull NetworkCapabilities addTransportType(@Transport int transportType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900790 checkValidTransportType(transportType);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700791 mTransportTypes |= 1 << transportType;
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -0700792 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking
Robert Greenwalt7569f182014-06-08 16:42:59 -0700793 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700794 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700795
796 /**
797 * Removes (if found) the given transport from this {@code NetworkCapability} instance.
798 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600799 * @param transportType the transport type to be removed.
Pierre Imaic8419a82016-03-22 17:54:54 +0900800 * @return This NetworkCapabilities instance, to facilitate chaining.
Robert Greenwalt7569f182014-06-08 16:42:59 -0700801 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700802 */
paulhud9736de2019-03-08 16:35:20 +0800803 public @NonNull NetworkCapabilities removeTransportType(@Transport int transportType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900804 checkValidTransportType(transportType);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700805 mTransportTypes &= ~(1 << transportType);
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -0700806 setNetworkSpecifier(mNetworkSpecifier); // used for exception checking
Robert Greenwalt7569f182014-06-08 16:42:59 -0700807 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -0700808 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700809
810 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600811 * Sets (or clears) the given transport on this {@link NetworkCapabilities}
812 * instance.
813 *
814 * @hide
815 */
paulhud9736de2019-03-08 16:35:20 +0800816 public @NonNull NetworkCapabilities setTransportType(@Transport int transportType,
817 boolean value) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600818 if (value) {
819 addTransportType(transportType);
820 } else {
821 removeTransportType(transportType);
822 }
823 return this;
824 }
825
826 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700827 * Gets all the transports set on this {@code NetworkCapability} instance.
828 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600829 * @return an array of transport type values for this instance.
Robert Greenwalt7569f182014-06-08 16:42:59 -0700830 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700831 */
Jeff Sharkeya5ee62f2018-05-14 13:49:07 -0600832 @TestApi
Remi NGUYEN VAN94a05572019-01-20 12:38:10 +0900833 @SystemApi
paulhud9736de2019-03-08 16:35:20 +0800834 @NonNull public @Transport int[] getTransportTypes() {
Hugo Benichi9910dbc2017-03-22 18:29:58 +0900835 return BitUtils.unpackBits(mTransportTypes);
Robert Greenwalt1448f052014-04-08 13:41:39 -0700836 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700837
838 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600839 * Sets all the transports set on this {@code NetworkCapability} instance.
Jeff Sharkey49bcd602017-11-09 13:11:50 -0700840 * This overwrites any existing transports.
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600841 *
842 * @hide
843 */
844 public void setTransportTypes(@Transport int[] transportTypes) {
845 mTransportTypes = BitUtils.packBits(transportTypes);
846 }
847
848 /**
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700849 * Tests for the presence of a transport on this instance.
850 *
Jeff Sharkeyde570312017-10-24 21:25:50 -0600851 * @param transportType the transport type to be tested for.
Robert Greenwalt01d004e2014-05-18 15:24:21 -0700852 * @return {@code true} if set on this instance.
853 */
Jeff Sharkeyde570312017-10-24 21:25:50 -0600854 public boolean hasTransport(@Transport int transportType) {
Hugo Benichi16f0a942017-06-20 14:07:59 +0900855 return isValidTransport(transportType) && ((mTransportTypes & (1 << transportType)) != 0);
Robert Greenwalt5c55e332014-05-08 00:02:04 -0700856 }
Robert Greenwalt1448f052014-04-08 13:41:39 -0700857
858 private void combineTransportTypes(NetworkCapabilities nc) {
859 this.mTransportTypes |= nc.mTransportTypes;
860 }
Hugo Benichieae7a222017-07-25 11:40:56 +0900861
Robert Greenwalt1448f052014-04-08 13:41:39 -0700862 private boolean satisfiedByTransportTypes(NetworkCapabilities nc) {
863 return ((this.mTransportTypes == 0) ||
864 ((this.mTransportTypes & nc.mTransportTypes) != 0));
865 }
Hugo Benichieae7a222017-07-25 11:40:56 +0900866
Robert Greenwalt06314e42014-10-29 14:04:06 -0700867 /** @hide */
868 public boolean equalsTransportTypes(NetworkCapabilities nc) {
Robert Greenwalt1448f052014-04-08 13:41:39 -0700869 return (nc.mTransportTypes == this.mTransportTypes);
870 }
871
872 /**
Roshan Piuse38acab2020-01-16 12:17:17 -0800873 * UID of the app that owns this network, or Process#INVALID_UID if none/unknown.
Chalard Jeanf474fc32018-01-17 15:10:05 +0900874 *
Qingxi Li7cf06622020-01-17 17:54:27 -0800875 * <p>This field keeps track of the UID of the app that created this network and is in charge of
876 * its lifecycle. This could be the UID of apps such as the Wifi network suggestor, the running
877 * VPN, or Carrier Service app managing a cellular data connection.
Qingxi Li9c5d8b92020-01-08 12:51:49 -0800878 *
879 * <p>For NetworkCapability instances being sent from ConnectivityService, this value MUST be
880 * reset to Process.INVALID_UID unless all the following conditions are met:
881 *
882 * <ol>
883 * <li>The destination app is the network owner
884 * <li>The destination app has the ACCESS_FINE_LOCATION permission granted
885 * <li>The user's location toggle is on
886 * </ol>
887 *
888 * This is because the owner UID is location-sensitive. The apps that request a network could
889 * know where the device is if they can tell for sure the system has connected to the network
890 * they requested.
891 *
892 * <p>This is populated by the network agents and for the NetworkCapabilities instance sent by
893 * an app to the System Server, the value MUST be reset to Process.INVALID_UID by the system
894 * server.
Chalard Jeanf474fc32018-01-17 15:10:05 +0900895 */
Qingxi Li7cf06622020-01-17 17:54:27 -0800896 private int mOwnerUid = Process.INVALID_UID;
Chalard Jeanf474fc32018-01-17 15:10:05 +0900897
898 /**
Qingxi Li7cf06622020-01-17 17:54:27 -0800899 * Set the UID of the owner app.
Chalard Jeane5e38502020-03-18 15:58:50 +0900900 * @hide
Chalard Jeanf474fc32018-01-17 15:10:05 +0900901 */
Roshan Piuse38acab2020-01-16 12:17:17 -0800902 public @NonNull NetworkCapabilities setOwnerUid(final int uid) {
Qingxi Li7cf06622020-01-17 17:54:27 -0800903 mOwnerUid = uid;
Roshan Piuse38acab2020-01-16 12:17:17 -0800904 return this;
Chalard Jeanf474fc32018-01-17 15:10:05 +0900905 }
906
Qingxi Li7cf06622020-01-17 17:54:27 -0800907 /**
Qingxi Li9c5d8b92020-01-08 12:51:49 -0800908 * Retrieves the UID of the app that owns this network.
909 *
910 * <p>For user privacy reasons, this field will only be populated if:
911 *
912 * <ol>
913 * <li>The calling app is the network owner
914 * <li>The calling app has the ACCESS_FINE_LOCATION permission granted
915 * <li>The user's location toggle is on
916 * </ol>
917 *
Chalard Jeane5e38502020-03-18 15:58:50 +0900918 * Instances of NetworkCapabilities sent to apps without the appropriate permissions will
919 * have this field cleared out.
Qingxi Li7cf06622020-01-17 17:54:27 -0800920 */
921 public int getOwnerUid() {
922 return mOwnerUid;
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +0000923 }
924
Chalard Jeanf474fc32018-01-17 15:10:05 +0900925 /**
Cody Kesting201fc132020-01-17 11:58:36 -0800926 * UIDs of packages that are administrators of this network, or empty if none.
927 *
928 * <p>This field tracks the UIDs of packages that have permission to manage this network.
929 *
930 * <p>Network owners will also be listed as administrators.
931 *
932 * <p>For NetworkCapability instances being sent from the System Server, this value MUST be
933 * empty unless the destination is 1) the System Server, or 2) Telephony. In either case, the
934 * receiving entity must have the ACCESS_FINE_LOCATION permission and target R+.
Chalard Jean981dcca2020-02-06 18:31:19 +0900935 *
936 * <p>When received from an app in a NetworkRequest this is always cleared out by the system
937 * server. This field is never used for matching NetworkRequests to NetworkAgents.
Cody Kesting201fc132020-01-17 11:58:36 -0800938 */
Cody Kesting919385b2020-03-18 15:22:12 -0700939 @NonNull private int[] mAdministratorUids = new int[0];
Cody Kesting201fc132020-01-17 11:58:36 -0800940
941 /**
Cody Kestingf7ac9962020-03-16 18:15:28 -0700942 * Sets the int[] of UIDs that are administrators of this network.
Cody Kesting201fc132020-01-17 11:58:36 -0800943 *
944 * <p>UIDs included in administratorUids gain administrator privileges over this Network.
945 * Examples of UIDs that should be included in administratorUids are:
Chalard Jean981dcca2020-02-06 18:31:19 +0900946 *
Cody Kesting201fc132020-01-17 11:58:36 -0800947 * <ul>
Chalard Jean981dcca2020-02-06 18:31:19 +0900948 * <li>Carrier apps with privileges for the relevant subscription
949 * <li>Active VPN apps
950 * <li>Other application groups with a particular Network-related role
Cody Kesting201fc132020-01-17 11:58:36 -0800951 * </ul>
952 *
953 * <p>In general, user-supplied networks (such as WiFi networks) do not have an administrator.
954 *
Cody Kestinga75e26b2020-01-05 14:06:39 -0800955 * <p>An app is granted owner privileges over Networks that it supplies. The owner UID MUST
956 * always be included in administratorUids.
Cody Kesting201fc132020-01-17 11:58:36 -0800957 *
Chalard Jean981dcca2020-02-06 18:31:19 +0900958 * <p>The administrator UIDs are set by network agents.
959 *
Cody Kesting201fc132020-01-17 11:58:36 -0800960 * @param administratorUids the UIDs to be set as administrators of this Network.
Cody Kesting93c1e652020-03-24 11:53:30 -0700961 * @throws IllegalArgumentException if duplicate UIDs are contained in administratorUids
Chalard Jean981dcca2020-02-06 18:31:19 +0900962 * @see #mAdministratorUids
Cody Kesting201fc132020-01-17 11:58:36 -0800963 * @hide
964 */
Qingxi Li9c5d8b92020-01-08 12:51:49 -0800965 @NonNull
Cody Kestingf7ac9962020-03-16 18:15:28 -0700966 public NetworkCapabilities setAdministratorUids(@NonNull final int[] administratorUids) {
967 mAdministratorUids = Arrays.copyOf(administratorUids, administratorUids.length);
Cody Kesting93c1e652020-03-24 11:53:30 -0700968 Arrays.sort(mAdministratorUids);
969 for (int i = 0; i < mAdministratorUids.length - 1; i++) {
970 if (mAdministratorUids[i] >= mAdministratorUids[i + 1]) {
971 throw new IllegalArgumentException("All administrator UIDs must be unique");
972 }
973 }
Roshan Piuse38acab2020-01-16 12:17:17 -0800974 return this;
Cody Kesting201fc132020-01-17 11:58:36 -0800975 }
976
977 /**
Cody Kestingf7ac9962020-03-16 18:15:28 -0700978 * Retrieves the UIDs that are administrators of this Network.
Cody Kesting201fc132020-01-17 11:58:36 -0800979 *
Chalard Jean981dcca2020-02-06 18:31:19 +0900980 * <p>This is only populated in NetworkCapabilities objects that come from network agents for
981 * networks that are managed by specific apps on the system, such as carrier privileged apps or
982 * wifi suggestion apps. This will include the network owner.
983 *
Cody Kestingf7ac9962020-03-16 18:15:28 -0700984 * @return the int[] of UIDs that are administrators of this Network
Chalard Jean981dcca2020-02-06 18:31:19 +0900985 * @see #mAdministratorUids
Cody Kesting201fc132020-01-17 11:58:36 -0800986 * @hide
987 */
988 @NonNull
989 @SystemApi
Chalard Jeane5e38502020-03-18 15:58:50 +0900990 @TestApi
Cody Kestingf7ac9962020-03-16 18:15:28 -0700991 public int[] getAdministratorUids() {
992 return Arrays.copyOf(mAdministratorUids, mAdministratorUids.length);
Cody Kesting201fc132020-01-17 11:58:36 -0800993 }
994
995 /**
Chalard Jean981dcca2020-02-06 18:31:19 +0900996 * Tests if the set of administrator UIDs of this network is the same as that of the passed one.
997 *
998 * <p>The administrator UIDs must be in sorted order.
999 *
1000 * <p>nc is assumed non-null. Else, NPE.
1001 *
1002 * @hide
1003 */
1004 @VisibleForTesting(visibility = PRIVATE)
1005 public boolean equalsAdministratorUids(@NonNull final NetworkCapabilities nc) {
1006 return Arrays.equals(mAdministratorUids, nc.mAdministratorUids);
1007 }
1008
1009 /**
1010 * Combine the administrator UIDs of the capabilities.
1011 *
1012 * <p>This is only legal if either of the administrators lists are empty, or if they are equal.
1013 * Combining administrator UIDs is only possible for combining non-overlapping sets of UIDs.
1014 *
1015 * <p>If both administrator lists are non-empty but not equal, they conflict with each other. In
1016 * this case, it would not make sense to add them together.
1017 */
1018 private void combineAdministratorUids(@NonNull final NetworkCapabilities nc) {
1019 if (nc.mAdministratorUids.length == 0) return;
1020 if (mAdministratorUids.length == 0) {
1021 mAdministratorUids = Arrays.copyOf(nc.mAdministratorUids, nc.mAdministratorUids.length);
1022 return;
1023 }
1024 if (!equalsAdministratorUids(nc)) {
1025 throw new IllegalStateException("Can't combine two different administrator UID lists");
1026 }
1027 }
1028
1029 /**
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001030 * Value indicating that link bandwidth is unspecified.
1031 * @hide
1032 */
1033 public static final int LINK_BANDWIDTH_UNSPECIFIED = 0;
1034
1035 /**
Robert Greenwalt1448f052014-04-08 13:41:39 -07001036 * Passive link bandwidth. This is a rough guide of the expected peak bandwidth
1037 * for the first hop on the given transport. It is not measured, but may take into account
1038 * link parameters (Radio technology, allocated channels, etc).
1039 */
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001040 private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
1041 private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
Robert Greenwalt1448f052014-04-08 13:41:39 -07001042
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001043 /**
1044 * Sets the upstream bandwidth for this network in Kbps. This always only refers to
1045 * the estimated first hop transport bandwidth.
1046 * <p>
Chalard Jeane5e38502020-03-18 15:58:50 +09001047 * {@see Builder#setLinkUpstreamBandwidthKbps}
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001048 *
1049 * @param upKbps the estimated first hop upstream (device to network) bandwidth.
Chalard Jeane5e38502020-03-18 15:58:50 +09001050 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001051 */
paulhud9736de2019-03-08 16:35:20 +08001052 public @NonNull NetworkCapabilities setLinkUpstreamBandwidthKbps(int upKbps) {
Robert Greenwalt1448f052014-04-08 13:41:39 -07001053 mLinkUpBandwidthKbps = upKbps;
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001054 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -07001055 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001056
1057 /**
1058 * Retrieves the upstream bandwidth for this network in Kbps. This always only refers to
1059 * the estimated first hop transport bandwidth.
1060 *
1061 * @return The estimated first hop upstream (device to network) bandwidth.
1062 */
Robert Greenwalt1448f052014-04-08 13:41:39 -07001063 public int getLinkUpstreamBandwidthKbps() {
1064 return mLinkUpBandwidthKbps;
1065 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001066
1067 /**
1068 * Sets the downstream bandwidth for this network in Kbps. This always only refers to
1069 * the estimated first hop transport bandwidth.
1070 * <p>
Chalard Jeane5e38502020-03-18 15:58:50 +09001071 * {@see Builder#setLinkUpstreamBandwidthKbps}
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001072 *
1073 * @param downKbps the estimated first hop downstream (network to device) bandwidth.
Chalard Jeane5e38502020-03-18 15:58:50 +09001074 * @hide
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001075 */
paulhud9736de2019-03-08 16:35:20 +08001076 public @NonNull NetworkCapabilities setLinkDownstreamBandwidthKbps(int downKbps) {
Robert Greenwalt1448f052014-04-08 13:41:39 -07001077 mLinkDownBandwidthKbps = downKbps;
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001078 return this;
Robert Greenwalt1448f052014-04-08 13:41:39 -07001079 }
Robert Greenwalt01d004e2014-05-18 15:24:21 -07001080
1081 /**
1082 * Retrieves the downstream bandwidth for this network in Kbps. This always only refers to
1083 * the estimated first hop transport bandwidth.
1084 *
1085 * @return The estimated first hop downstream (network to device) bandwidth.
1086 */
Robert Greenwalt1448f052014-04-08 13:41:39 -07001087 public int getLinkDownstreamBandwidthKbps() {
1088 return mLinkDownBandwidthKbps;
1089 }
1090
1091 private void combineLinkBandwidths(NetworkCapabilities nc) {
1092 this.mLinkUpBandwidthKbps =
1093 Math.max(this.mLinkUpBandwidthKbps, nc.mLinkUpBandwidthKbps);
1094 this.mLinkDownBandwidthKbps =
1095 Math.max(this.mLinkDownBandwidthKbps, nc.mLinkDownBandwidthKbps);
1096 }
1097 private boolean satisfiedByLinkBandwidths(NetworkCapabilities nc) {
1098 return !(this.mLinkUpBandwidthKbps > nc.mLinkUpBandwidthKbps ||
1099 this.mLinkDownBandwidthKbps > nc.mLinkDownBandwidthKbps);
1100 }
1101 private boolean equalsLinkBandwidths(NetworkCapabilities nc) {
1102 return (this.mLinkUpBandwidthKbps == nc.mLinkUpBandwidthKbps &&
1103 this.mLinkDownBandwidthKbps == nc.mLinkDownBandwidthKbps);
1104 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001105 /** @hide */
1106 public static int minBandwidth(int a, int b) {
1107 if (a == LINK_BANDWIDTH_UNSPECIFIED) {
1108 return b;
1109 } else if (b == LINK_BANDWIDTH_UNSPECIFIED) {
1110 return a;
1111 } else {
1112 return Math.min(a, b);
1113 }
1114 }
1115 /** @hide */
1116 public static int maxBandwidth(int a, int b) {
1117 return Math.max(a, b);
1118 }
Robert Greenwalt1448f052014-04-08 13:41:39 -07001119
Etan Cohena7434272017-04-03 12:17:51 -07001120 private NetworkSpecifier mNetworkSpecifier = null;
Etan Cohenca9fb562018-11-27 07:32:39 -08001121 private TransportInfo mTransportInfo = null;
Etan Cohena7434272017-04-03 12:17:51 -07001122
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001123 /**
1124 * Sets the optional bearer specific network specifier.
1125 * This has no meaning if a single transport is also not specified, so calling
1126 * this without a single transport set will generate an exception, as will
1127 * subsequently adding or removing transports after this is set.
1128 * </p>
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001129 *
Etan Cohena7434272017-04-03 12:17:51 -07001130 * @param networkSpecifier A concrete, parcelable framework class that extends
1131 * NetworkSpecifier.
Pierre Imaic8419a82016-03-22 17:54:54 +09001132 * @return This NetworkCapabilities instance, to facilitate chaining.
Chalard Jeane5e38502020-03-18 15:58:50 +09001133 * @hide
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001134 */
Aaron Huange6b62392019-09-20 22:52:54 +08001135 public @NonNull NetworkCapabilities setNetworkSpecifier(
1136 @NonNull NetworkSpecifier networkSpecifier) {
Etan Cohena7434272017-04-03 12:17:51 -07001137 if (networkSpecifier != null && Long.bitCount(mTransportTypes) != 1) {
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001138 throw new IllegalStateException("Must have a single transport specified to use " +
1139 "setNetworkSpecifier");
1140 }
Etan Cohena7434272017-04-03 12:17:51 -07001141
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001142 mNetworkSpecifier = networkSpecifier;
Etan Cohena7434272017-04-03 12:17:51 -07001143
Pierre Imaic8419a82016-03-22 17:54:54 +09001144 return this;
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001145 }
1146
1147 /**
Etan Cohenca9fb562018-11-27 07:32:39 -08001148 * Sets the optional transport specific information.
1149 *
1150 * @param transportInfo A concrete, parcelable framework class that extends
1151 * {@link TransportInfo}.
1152 * @return This NetworkCapabilities instance, to facilitate chaining.
1153 * @hide
1154 */
Aaron Huange6b62392019-09-20 22:52:54 +08001155 public @NonNull NetworkCapabilities setTransportInfo(@NonNull TransportInfo transportInfo) {
Etan Cohenca9fb562018-11-27 07:32:39 -08001156 mTransportInfo = transportInfo;
1157 return this;
1158 }
1159
1160 /**
paulhud9736de2019-03-08 16:35:20 +08001161 * Gets the optional bearer specific network specifier. May be {@code null} if not set.
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001162 *
Etan Cohena7434272017-04-03 12:17:51 -07001163 * @return The optional {@link NetworkSpecifier} specifying the bearer specific network
Chalard Jeane5e38502020-03-18 15:58:50 +09001164 * specifier or {@code null}.
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001165 */
paulhud9736de2019-03-08 16:35:20 +08001166 public @Nullable NetworkSpecifier getNetworkSpecifier() {
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001167 return mNetworkSpecifier;
1168 }
1169
Etan Cohenca9fb562018-11-27 07:32:39 -08001170 /**
1171 * Returns a transport-specific information container. The application may cast this
1172 * container to a concrete sub-class based on its knowledge of the network request. The
1173 * application should be able to deal with a {@code null} return value or an invalid case,
Etan Cohenbd648ce2018-12-10 14:07:15 -08001174 * e.g. use {@code instanceof} operator to verify expected type.
Etan Cohenca9fb562018-11-27 07:32:39 -08001175 *
1176 * @return A concrete implementation of the {@link TransportInfo} class or null if not
1177 * available for the network.
1178 */
1179 @Nullable public TransportInfo getTransportInfo() {
1180 return mTransportInfo;
1181 }
1182
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001183 private void combineSpecifiers(NetworkCapabilities nc) {
Etan Cohena7434272017-04-03 12:17:51 -07001184 if (mNetworkSpecifier != null && !mNetworkSpecifier.equals(nc.mNetworkSpecifier)) {
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001185 throw new IllegalStateException("Can't combine two networkSpecifiers");
1186 }
Etan Cohena7434272017-04-03 12:17:51 -07001187 setNetworkSpecifier(nc.mNetworkSpecifier);
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001188 }
Etan Cohena7434272017-04-03 12:17:51 -07001189
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001190 private boolean satisfiedBySpecifier(NetworkCapabilities nc) {
Chalard Jean2da4f9f2020-03-27 17:57:34 +09001191 return mNetworkSpecifier == null || mNetworkSpecifier.canBeSatisfiedBy(nc.mNetworkSpecifier)
Etan Cohena7434272017-04-03 12:17:51 -07001192 || nc.mNetworkSpecifier instanceof MatchAllNetworkSpecifier;
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001193 }
Etan Cohena7434272017-04-03 12:17:51 -07001194
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001195 private boolean equalsSpecifier(NetworkCapabilities nc) {
Etan Cohena7434272017-04-03 12:17:51 -07001196 return Objects.equals(mNetworkSpecifier, nc.mNetworkSpecifier);
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001197 }
1198
Etan Cohenca9fb562018-11-27 07:32:39 -08001199 private void combineTransportInfos(NetworkCapabilities nc) {
1200 if (mTransportInfo != null && !mTransportInfo.equals(nc.mTransportInfo)) {
1201 throw new IllegalStateException("Can't combine two TransportInfos");
1202 }
1203 setTransportInfo(nc.mTransportInfo);
1204 }
1205
1206 private boolean equalsTransportInfo(NetworkCapabilities nc) {
1207 return Objects.equals(mTransportInfo, nc.mTransportInfo);
1208 }
1209
Robert Greenwalt1448f052014-04-08 13:41:39 -07001210 /**
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001211 * Magic value that indicates no signal strength provided. A request specifying this value is
1212 * always satisfied.
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001213 */
1214 public static final int SIGNAL_STRENGTH_UNSPECIFIED = Integer.MIN_VALUE;
1215
1216 /**
1217 * Signal strength. This is a signed integer, and higher values indicate better signal.
1218 * The exact units are bearer-dependent. For example, Wi-Fi uses RSSI.
1219 */
paulhud9736de2019-03-08 16:35:20 +08001220 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Jeff Sharkey49bcd602017-11-09 13:11:50 -07001221 private int mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001222
1223 /**
1224 * Sets the signal strength. This is a signed integer, with higher values indicating a stronger
1225 * signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same RSSI units
Chalard Jeanb03a6222018-04-11 21:09:10 +09001226 * reported by wifi code.
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001227 * <p>
1228 * Note that when used to register a network callback, this specifies the minimum acceptable
1229 * signal strength. When received as the state of an existing network it specifies the current
1230 * value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means no value when received and has no
1231 * effect when requesting a callback.
1232 *
1233 * @param signalStrength the bearer-specific signal strength.
Chalard Jeane5e38502020-03-18 15:58:50 +09001234 * @hide
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001235 */
paulhud9736de2019-03-08 16:35:20 +08001236 public @NonNull NetworkCapabilities setSignalStrength(int signalStrength) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001237 mSignalStrength = signalStrength;
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001238 return this;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001239 }
1240
1241 /**
1242 * Returns {@code true} if this object specifies a signal strength.
1243 *
1244 * @hide
1245 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001246 @UnsupportedAppUsage
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001247 public boolean hasSignalStrength() {
1248 return mSignalStrength > SIGNAL_STRENGTH_UNSPECIFIED;
1249 }
1250
1251 /**
1252 * Retrieves the signal strength.
1253 *
1254 * @return The bearer-specific signal strength.
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001255 */
1256 public int getSignalStrength() {
1257 return mSignalStrength;
1258 }
1259
1260 private void combineSignalStrength(NetworkCapabilities nc) {
1261 this.mSignalStrength = Math.max(this.mSignalStrength, nc.mSignalStrength);
1262 }
1263
1264 private boolean satisfiedBySignalStrength(NetworkCapabilities nc) {
1265 return this.mSignalStrength <= nc.mSignalStrength;
1266 }
1267
1268 private boolean equalsSignalStrength(NetworkCapabilities nc) {
1269 return this.mSignalStrength == nc.mSignalStrength;
1270 }
1271
1272 /**
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001273 * List of UIDs this network applies to. No restriction if null.
1274 * <p>
Chalard Jeanb552c462018-02-21 18:43:54 +09001275 * For networks, mUids represent the list of network this applies to, and null means this
1276 * network applies to all UIDs.
1277 * For requests, mUids is the list of UIDs this network MUST apply to to match ; ALL UIDs
1278 * must be included in a network so that they match. As an exception to the general rule,
1279 * a null mUids field for requests mean "no requirements" rather than what the general rule
1280 * would suggest ("must apply to all UIDs") : this is because this has shown to be what users
1281 * of this API expect in practice. A network that must match all UIDs can still be
1282 * expressed with a set ranging the entire set of possible UIDs.
1283 * <p>
1284 * mUids is typically (and at this time, only) used by VPN. This network is only available to
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001285 * the UIDs in this list, and it is their default network. Apps in this list that wish to
1286 * bypass the VPN can do so iff the VPN app allows them to or if they are privileged. If this
1287 * member is null, then the network is not restricted by app UID. If it's an empty list, then
1288 * it means nobody can use it.
Chalard Jeanf474fc32018-01-17 15:10:05 +09001289 * As a special exception, the app managing this network (as identified by its UID stored in
Qingxi Li7cf06622020-01-17 17:54:27 -08001290 * mOwnerUid) can always see this network. This is embodied by a special check in
Chalard Jeanf474fc32018-01-17 15:10:05 +09001291 * satisfiedByUids. That still does not mean the network necessarily <strong>applies</strong>
1292 * to the app that manages it as determined by #appliesToUid.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001293 * <p>
1294 * Please note that in principle a single app can be associated with multiple UIDs because
1295 * each app will have a different UID when it's run as a different (macro-)user. A single
1296 * macro user can only have a single active VPN app at any given time however.
1297 * <p>
1298 * Also please be aware this class does not try to enforce any normalization on this. Callers
1299 * can only alter the UIDs by setting them wholesale : this class does not provide any utility
1300 * to add or remove individual UIDs or ranges. If callers have any normalization needs on
1301 * their own (like requiring sortedness or no overlap) they need to enforce it
1302 * themselves. Some of the internal methods also assume this is normalized as in no adjacent
1303 * or overlapping ranges are present.
1304 *
1305 * @hide
1306 */
Chalard Jean477e36c2018-01-25 09:41:51 +09001307 private ArraySet<UidRange> mUids = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001308
1309 /**
Chalard Jeandda156a2018-01-10 21:19:32 +09001310 * Convenience method to set the UIDs this network applies to to a single UID.
1311 * @hide
1312 */
paulhud9736de2019-03-08 16:35:20 +08001313 public @NonNull NetworkCapabilities setSingleUid(int uid) {
Chalard Jeandda156a2018-01-10 21:19:32 +09001314 final ArraySet<UidRange> identity = new ArraySet<>(1);
1315 identity.add(new UidRange(uid, uid));
1316 setUids(identity);
1317 return this;
1318 }
1319
1320 /**
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001321 * Set the list of UIDs this network applies to.
1322 * This makes a copy of the set so that callers can't modify it after the call.
1323 * @hide
1324 */
paulhud9736de2019-03-08 16:35:20 +08001325 public @NonNull NetworkCapabilities setUids(Set<UidRange> uids) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001326 if (null == uids) {
1327 mUids = null;
1328 } else {
1329 mUids = new ArraySet<>(uids);
1330 }
1331 return this;
1332 }
1333
1334 /**
1335 * Get the list of UIDs this network applies to.
1336 * This returns a copy of the set so that callers can't modify the original object.
1337 * @hide
1338 */
paulhud9736de2019-03-08 16:35:20 +08001339 public @Nullable Set<UidRange> getUids() {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001340 return null == mUids ? null : new ArraySet<>(mUids);
1341 }
1342
1343 /**
1344 * Test whether this network applies to this UID.
1345 * @hide
1346 */
1347 public boolean appliesToUid(int uid) {
1348 if (null == mUids) return true;
1349 for (UidRange range : mUids) {
1350 if (range.contains(uid)) {
1351 return true;
1352 }
1353 }
1354 return false;
1355 }
1356
1357 /**
Chalard Jeanb03a6222018-04-11 21:09:10 +09001358 * Tests if the set of UIDs that this network applies to is the same as the passed network.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001359 * <p>
1360 * This test only checks whether equal range objects are in both sets. It will
1361 * return false if the ranges are not exactly the same, even if the covered UIDs
1362 * are for an equivalent result.
1363 * <p>
1364 * Note that this method is not very optimized, which is fine as long as it's not used very
1365 * often.
1366 * <p>
1367 * nc is assumed nonnull.
1368 *
1369 * @hide
1370 */
1371 @VisibleForTesting
paulhud9736de2019-03-08 16:35:20 +08001372 public boolean equalsUids(@NonNull NetworkCapabilities nc) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001373 Set<UidRange> comparedUids = nc.mUids;
1374 if (null == comparedUids) return null == mUids;
1375 if (null == mUids) return false;
1376 // Make a copy so it can be mutated to check that all ranges in mUids
1377 // also are in uids.
1378 final Set<UidRange> uids = new ArraySet<>(mUids);
1379 for (UidRange range : comparedUids) {
1380 if (!uids.contains(range)) {
1381 return false;
1382 }
1383 uids.remove(range);
1384 }
1385 return uids.isEmpty();
1386 }
1387
1388 /**
1389 * Test whether the passed NetworkCapabilities satisfies the UIDs this capabilities require.
1390 *
Chalard Jeanf474fc32018-01-17 15:10:05 +09001391 * This method is called on the NetworkCapabilities embedded in a request with the
1392 * capabilities of an available network. It checks whether all the UIDs from this listen
1393 * (representing the UIDs that must have access to the network) are satisfied by the UIDs
1394 * in the passed nc (representing the UIDs that this network is available to).
1395 * <p>
1396 * As a special exception, the UID that created the passed network (as represented by its
Qingxi Li7cf06622020-01-17 17:54:27 -08001397 * mOwnerUid field) always satisfies a NetworkRequest requiring it (of LISTEN
Chalard Jeanf474fc32018-01-17 15:10:05 +09001398 * or REQUEST types alike), even if the network does not apply to it. That is so a VPN app
1399 * can see its own network when it listens for it.
1400 * <p>
1401 * nc is assumed nonnull. Else, NPE.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001402 * @see #appliesToUid
1403 * @hide
1404 */
paulhud9736de2019-03-08 16:35:20 +08001405 public boolean satisfiedByUids(@NonNull NetworkCapabilities nc) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001406 if (null == nc.mUids || null == mUids) return true; // The network satisfies everything.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001407 for (UidRange requiredRange : mUids) {
Qingxi Li7cf06622020-01-17 17:54:27 -08001408 if (requiredRange.contains(nc.mOwnerUid)) return true;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001409 if (!nc.appliesToUidRange(requiredRange)) {
1410 return false;
1411 }
1412 }
1413 return true;
1414 }
1415
1416 /**
1417 * Returns whether this network applies to the passed ranges.
1418 * This assumes that to apply, the passed range has to be entirely contained
1419 * within one of the ranges this network applies to. If the ranges are not normalized,
1420 * this method may return false even though all required UIDs are covered because no
1421 * single range contained them all.
1422 * @hide
1423 */
1424 @VisibleForTesting
paulhud9736de2019-03-08 16:35:20 +08001425 public boolean appliesToUidRange(@Nullable UidRange requiredRange) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001426 if (null == mUids) return true;
1427 for (UidRange uidRange : mUids) {
1428 if (uidRange.containsRange(requiredRange)) {
1429 return true;
1430 }
1431 }
1432 return false;
1433 }
1434
1435 /**
1436 * Combine the UIDs this network currently applies to with the UIDs the passed
1437 * NetworkCapabilities apply to.
1438 * nc is assumed nonnull.
1439 */
paulhud9736de2019-03-08 16:35:20 +08001440 private void combineUids(@NonNull NetworkCapabilities nc) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001441 if (null == nc.mUids || null == mUids) {
1442 mUids = null;
1443 return;
1444 }
1445 mUids.addAll(nc.mUids);
1446 }
1447
Chalard Jeanb03a6222018-04-11 21:09:10 +09001448
1449 /**
1450 * The SSID of the network, or null if not applicable or unknown.
1451 * <p>
1452 * This is filled in by wifi code.
1453 * @hide
1454 */
1455 private String mSSID;
1456
1457 /**
1458 * Sets the SSID of this network.
1459 * @hide
1460 */
paulhud9736de2019-03-08 16:35:20 +08001461 public @NonNull NetworkCapabilities setSSID(@Nullable String ssid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001462 mSSID = ssid;
1463 return this;
1464 }
1465
1466 /**
1467 * Gets the SSID of this network, or null if none or unknown.
1468 * @hide
1469 */
Remi NGUYEN VANaa4c5112020-01-22 22:52:53 +09001470 @SystemApi
Chalard Jeane5e38502020-03-18 15:58:50 +09001471 @TestApi
1472 public @Nullable String getSsid() {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001473 return mSSID;
1474 }
1475
1476 /**
1477 * Tests if the SSID of this network is the same as the SSID of the passed network.
1478 * @hide
1479 */
paulhud9736de2019-03-08 16:35:20 +08001480 public boolean equalsSSID(@NonNull NetworkCapabilities nc) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001481 return Objects.equals(mSSID, nc.mSSID);
1482 }
1483
1484 /**
1485 * Check if the SSID requirements of this object are matched by the passed object.
1486 * @hide
1487 */
paulhud9736de2019-03-08 16:35:20 +08001488 public boolean satisfiedBySSID(@NonNull NetworkCapabilities nc) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001489 return mSSID == null || mSSID.equals(nc.mSSID);
1490 }
1491
1492 /**
1493 * Combine SSIDs of the capabilities.
1494 * <p>
1495 * This is only legal if either the SSID of this object is null, or both SSIDs are
1496 * equal.
1497 * @hide
1498 */
paulhud9736de2019-03-08 16:35:20 +08001499 private void combineSSIDs(@NonNull NetworkCapabilities nc) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001500 if (mSSID != null && !mSSID.equals(nc.mSSID)) {
1501 throw new IllegalStateException("Can't combine two SSIDs");
1502 }
1503 setSSID(nc.mSSID);
1504 }
1505
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001506 /**
Pavel Maltseve18ef262018-03-07 11:13:04 -08001507 * Combine a set of Capabilities to this one. Useful for coming up with the complete set.
1508 * <p>
1509 * Note that this method may break an invariant of having a particular capability in either
1510 * wanted or unwanted lists but never in both. Requests that have the same capability in
1511 * both lists will never be satisfied.
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001512 * @hide
Robert Greenwalt1448f052014-04-08 13:41:39 -07001513 */
paulhud9736de2019-03-08 16:35:20 +08001514 public void combineCapabilities(@NonNull NetworkCapabilities nc) {
Robert Greenwalt1448f052014-04-08 13:41:39 -07001515 combineNetCapabilities(nc);
1516 combineTransportTypes(nc);
1517 combineLinkBandwidths(nc);
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001518 combineSpecifiers(nc);
Etan Cohenca9fb562018-11-27 07:32:39 -08001519 combineTransportInfos(nc);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001520 combineSignalStrength(nc);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001521 combineUids(nc);
Chalard Jeanb03a6222018-04-11 21:09:10 +09001522 combineSSIDs(nc);
Roshan Piuse38acab2020-01-16 12:17:17 -08001523 combineRequestor(nc);
Chalard Jean981dcca2020-02-06 18:31:19 +09001524 combineAdministratorUids(nc);
Robert Greenwalt1448f052014-04-08 13:41:39 -07001525 }
1526
1527 /**
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001528 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
1529 *
1530 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
1531 * @param onlyImmutable if {@code true}, do not consider mutable requirements such as link
1532 * bandwidth, signal strength, or validation / captive portal status.
1533 *
1534 * @hide
1535 */
1536 private boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001537 return (nc != null
1538 && satisfiedByNetCapabilities(nc, onlyImmutable)
1539 && satisfiedByTransportTypes(nc)
1540 && (onlyImmutable || satisfiedByLinkBandwidths(nc))
1541 && satisfiedBySpecifier(nc)
1542 && (onlyImmutable || satisfiedBySignalStrength(nc))
Chalard Jeanb03a6222018-04-11 21:09:10 +09001543 && (onlyImmutable || satisfiedByUids(nc))
Roshan Piuse38acab2020-01-16 12:17:17 -08001544 && (onlyImmutable || satisfiedBySSID(nc)))
1545 && (onlyImmutable || satisfiedByRequestor(nc));
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001546 }
1547
1548 /**
1549 * Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
1550 *
1551 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
1552 *
1553 * @hide
Robert Greenwalt1448f052014-04-08 13:41:39 -07001554 */
Remi NGUYEN VAN94a05572019-01-20 12:38:10 +09001555 @TestApi
1556 @SystemApi
paulhud9736de2019-03-08 16:35:20 +08001557 public boolean satisfiedByNetworkCapabilities(@Nullable NetworkCapabilities nc) {
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001558 return satisfiedByNetworkCapabilities(nc, false);
1559 }
1560
1561 /**
1562 * Check if our immutable requirements are satisfied by the given {@code NetworkCapabilities}.
1563 *
1564 * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
1565 *
1566 * @hide
1567 */
paulhud9736de2019-03-08 16:35:20 +08001568 public boolean satisfiedByImmutableNetworkCapabilities(@Nullable NetworkCapabilities nc) {
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001569 return satisfiedByNetworkCapabilities(nc, true);
1570 }
1571
1572 /**
1573 * Checks that our immutable capabilities are the same as those of the given
Hugo Benichieae7a222017-07-25 11:40:56 +09001574 * {@code NetworkCapabilities} and return a String describing any difference.
1575 * The returned String is empty if there is no difference.
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001576 *
1577 * @hide
1578 */
paulhud9736de2019-03-08 16:35:20 +08001579 public String describeImmutableDifferences(@Nullable NetworkCapabilities that) {
Hugo Benichieae7a222017-07-25 11:40:56 +09001580 if (that == null) {
1581 return "other NetworkCapabilities was null";
1582 }
1583
1584 StringJoiner joiner = new StringJoiner(", ");
1585
Hugo Benichieae7a222017-07-25 11:40:56 +09001586 // Ignore NOT_METERED being added or removed as it is effectively dynamic. http://b/63326103
1587 // TODO: properly support NOT_METERED as a mutable and requestable capability.
Hugo Benichi2ecb9402017-08-04 13:18:40 +09001588 final long mask = ~MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_NOT_METERED);
Hugo Benichieae7a222017-07-25 11:40:56 +09001589 long oldImmutableCapabilities = this.mNetworkCapabilities & mask;
1590 long newImmutableCapabilities = that.mNetworkCapabilities & mask;
1591 if (oldImmutableCapabilities != newImmutableCapabilities) {
1592 String before = capabilityNamesOf(BitUtils.unpackBits(oldImmutableCapabilities));
1593 String after = capabilityNamesOf(BitUtils.unpackBits(newImmutableCapabilities));
1594 joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after));
1595 }
1596
1597 if (!equalsSpecifier(that)) {
1598 NetworkSpecifier before = this.getNetworkSpecifier();
1599 NetworkSpecifier after = that.getNetworkSpecifier();
1600 joiner.add(String.format("specifier changed: %s -> %s", before, after));
1601 }
1602
1603 if (!equalsTransportTypes(that)) {
1604 String before = transportNamesOf(this.getTransportTypes());
1605 String after = transportNamesOf(that.getTransportTypes());
1606 joiner.add(String.format("transports changed: %s -> %s", before, after));
1607 }
1608
1609 return joiner.toString();
Robert Greenwalt1448f052014-04-08 13:41:39 -07001610 }
1611
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09001612 /**
1613 * Checks that our requestable capabilities are the same as those of the given
1614 * {@code NetworkCapabilities}.
1615 *
1616 * @hide
1617 */
paulhud9736de2019-03-08 16:35:20 +08001618 public boolean equalRequestableCapabilities(@Nullable NetworkCapabilities nc) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09001619 if (nc == null) return false;
1620 return (equalsNetCapabilitiesRequestable(nc) &&
1621 equalsTransportTypes(nc) &&
1622 equalsSpecifier(nc));
1623 }
1624
Robert Greenwalt1448f052014-04-08 13:41:39 -07001625 @Override
paulhud9736de2019-03-08 16:35:20 +08001626 public boolean equals(@Nullable Object obj) {
Robert Greenwalt1448f052014-04-08 13:41:39 -07001627 if (obj == null || (obj instanceof NetworkCapabilities == false)) return false;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001628 NetworkCapabilities that = (NetworkCapabilities) obj;
Roshan Piuse38acab2020-01-16 12:17:17 -08001629 return equalsNetCapabilities(that)
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001630 && equalsTransportTypes(that)
1631 && equalsLinkBandwidths(that)
1632 && equalsSignalStrength(that)
1633 && equalsSpecifier(that)
Etan Cohenca9fb562018-11-27 07:32:39 -08001634 && equalsTransportInfo(that)
Chalard Jeanb03a6222018-04-11 21:09:10 +09001635 && equalsUids(that)
lucaslin783f2212019-10-22 18:27:33 +08001636 && equalsSSID(that)
Roshan Piuse38acab2020-01-16 12:17:17 -08001637 && equalsPrivateDnsBroken(that)
Chalard Jean981dcca2020-02-06 18:31:19 +09001638 && equalsRequestor(that)
1639 && equalsAdministratorUids(that);
Robert Greenwalt1448f052014-04-08 13:41:39 -07001640 }
1641
1642 @Override
1643 public int hashCode() {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001644 return (int) (mNetworkCapabilities & 0xFFFFFFFF)
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001645 + ((int) (mNetworkCapabilities >> 32) * 3)
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001646 + ((int) (mUnwantedNetworkCapabilities & 0xFFFFFFFF) * 5)
1647 + ((int) (mUnwantedNetworkCapabilities >> 32) * 7)
1648 + ((int) (mTransportTypes & 0xFFFFFFFF) * 11)
1649 + ((int) (mTransportTypes >> 32) * 13)
1650 + (mLinkUpBandwidthKbps * 17)
1651 + (mLinkDownBandwidthKbps * 19)
1652 + Objects.hashCode(mNetworkSpecifier) * 23
1653 + (mSignalStrength * 29)
Chalard Jeanb03a6222018-04-11 21:09:10 +09001654 + Objects.hashCode(mUids) * 31
Etan Cohenca9fb562018-11-27 07:32:39 -08001655 + Objects.hashCode(mSSID) * 37
lucaslin783f2212019-10-22 18:27:33 +08001656 + Objects.hashCode(mTransportInfo) * 41
Roshan Piuse38acab2020-01-16 12:17:17 -08001657 + Objects.hashCode(mPrivateDnsBroken) * 43
1658 + Objects.hashCode(mRequestorUid) * 47
Chalard Jean981dcca2020-02-06 18:31:19 +09001659 + Objects.hashCode(mRequestorPackageName) * 53
1660 + Arrays.hashCode(mAdministratorUids) * 59;
Robert Greenwalt1448f052014-04-08 13:41:39 -07001661 }
1662
Wink Saville4e2dea72014-09-20 11:04:03 -07001663 @Override
Robert Greenwalt1448f052014-04-08 13:41:39 -07001664 public int describeContents() {
1665 return 0;
1666 }
Cody Kesting201fc132020-01-17 11:58:36 -08001667
Wink Saville4e2dea72014-09-20 11:04:03 -07001668 @Override
Robert Greenwalt1448f052014-04-08 13:41:39 -07001669 public void writeToParcel(Parcel dest, int flags) {
1670 dest.writeLong(mNetworkCapabilities);
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001671 dest.writeLong(mUnwantedNetworkCapabilities);
Robert Greenwalt1448f052014-04-08 13:41:39 -07001672 dest.writeLong(mTransportTypes);
1673 dest.writeInt(mLinkUpBandwidthKbps);
1674 dest.writeInt(mLinkDownBandwidthKbps);
Etan Cohena7434272017-04-03 12:17:51 -07001675 dest.writeParcelable((Parcelable) mNetworkSpecifier, flags);
Etan Cohenca9fb562018-11-27 07:32:39 -08001676 dest.writeParcelable((Parcelable) mTransportInfo, flags);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001677 dest.writeInt(mSignalStrength);
Chalard Jean477e36c2018-01-25 09:41:51 +09001678 dest.writeArraySet(mUids);
Chalard Jeanb03a6222018-04-11 21:09:10 +09001679 dest.writeString(mSSID);
lucaslin783f2212019-10-22 18:27:33 +08001680 dest.writeBoolean(mPrivateDnsBroken);
Chalard Jean981dcca2020-02-06 18:31:19 +09001681 dest.writeIntArray(getAdministratorUids());
Qingxi Li7cf06622020-01-17 17:54:27 -08001682 dest.writeInt(mOwnerUid);
Roshan Piuse38acab2020-01-16 12:17:17 -08001683 dest.writeInt(mRequestorUid);
1684 dest.writeString(mRequestorPackageName);
Robert Greenwalt1448f052014-04-08 13:41:39 -07001685 }
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001686
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -07001687 public static final @android.annotation.NonNull Creator<NetworkCapabilities> CREATOR =
Robert Greenwalt1448f052014-04-08 13:41:39 -07001688 new Creator<NetworkCapabilities>() {
Wink Saville4e2dea72014-09-20 11:04:03 -07001689 @Override
Robert Greenwalt1448f052014-04-08 13:41:39 -07001690 public NetworkCapabilities createFromParcel(Parcel in) {
1691 NetworkCapabilities netCap = new NetworkCapabilities();
1692
1693 netCap.mNetworkCapabilities = in.readLong();
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001694 netCap.mUnwantedNetworkCapabilities = in.readLong();
Robert Greenwalt1448f052014-04-08 13:41:39 -07001695 netCap.mTransportTypes = in.readLong();
1696 netCap.mLinkUpBandwidthKbps = in.readInt();
1697 netCap.mLinkDownBandwidthKbps = in.readInt();
Etan Cohena7434272017-04-03 12:17:51 -07001698 netCap.mNetworkSpecifier = in.readParcelable(null);
Etan Cohenca9fb562018-11-27 07:32:39 -08001699 netCap.mTransportInfo = in.readParcelable(null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001700 netCap.mSignalStrength = in.readInt();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001701 netCap.mUids = (ArraySet<UidRange>) in.readArraySet(
1702 null /* ClassLoader, null for default */);
Chalard Jeanb03a6222018-04-11 21:09:10 +09001703 netCap.mSSID = in.readString();
lucaslin783f2212019-10-22 18:27:33 +08001704 netCap.mPrivateDnsBroken = in.readBoolean();
Cody Kestingf7ac9962020-03-16 18:15:28 -07001705 netCap.setAdministratorUids(in.createIntArray());
Qingxi Li7cf06622020-01-17 17:54:27 -08001706 netCap.mOwnerUid = in.readInt();
Roshan Piuse38acab2020-01-16 12:17:17 -08001707 netCap.mRequestorUid = in.readInt();
1708 netCap.mRequestorPackageName = in.readString();
Robert Greenwalt1448f052014-04-08 13:41:39 -07001709 return netCap;
1710 }
Wink Saville4e2dea72014-09-20 11:04:03 -07001711 @Override
Robert Greenwalt1448f052014-04-08 13:41:39 -07001712 public NetworkCapabilities[] newArray(int size) {
1713 return new NetworkCapabilities[size];
1714 }
1715 };
1716
Wink Saville4e2dea72014-09-20 11:04:03 -07001717 @Override
paulhud9736de2019-03-08 16:35:20 +08001718 public @NonNull String toString() {
Chalard Jean07ace0f2018-02-26 19:00:45 +09001719 final StringBuilder sb = new StringBuilder("[");
1720 if (0 != mTransportTypes) {
1721 sb.append(" Transports: ");
1722 appendStringRepresentationOfBitMaskToStringBuilder(sb, mTransportTypes,
1723 NetworkCapabilities::transportNameOf, "|");
1724 }
1725 if (0 != mNetworkCapabilities) {
1726 sb.append(" Capabilities: ");
1727 appendStringRepresentationOfBitMaskToStringBuilder(sb, mNetworkCapabilities,
1728 NetworkCapabilities::capabilityNameOf, "&");
1729 }
jiayanhonge20a4fe2018-11-23 14:23:04 +08001730 if (0 != mUnwantedNetworkCapabilities) {
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001731 sb.append(" Unwanted: ");
1732 appendStringRepresentationOfBitMaskToStringBuilder(sb, mUnwantedNetworkCapabilities,
1733 NetworkCapabilities::capabilityNameOf, "&");
1734 }
Chalard Jean07ace0f2018-02-26 19:00:45 +09001735 if (mLinkUpBandwidthKbps > 0) {
1736 sb.append(" LinkUpBandwidth>=").append(mLinkUpBandwidthKbps).append("Kbps");
1737 }
1738 if (mLinkDownBandwidthKbps > 0) {
1739 sb.append(" LinkDnBandwidth>=").append(mLinkDownBandwidthKbps).append("Kbps");
1740 }
1741 if (mNetworkSpecifier != null) {
1742 sb.append(" Specifier: <").append(mNetworkSpecifier).append(">");
1743 }
Etan Cohenca9fb562018-11-27 07:32:39 -08001744 if (mTransportInfo != null) {
1745 sb.append(" TransportInfo: <").append(mTransportInfo).append(">");
1746 }
Chalard Jean07ace0f2018-02-26 19:00:45 +09001747 if (hasSignalStrength()) {
1748 sb.append(" SignalStrength: ").append(mSignalStrength);
Robert Greenwalt1448f052014-04-08 13:41:39 -07001749 }
1750
Chalard Jean07ace0f2018-02-26 19:00:45 +09001751 if (null != mUids) {
1752 if ((1 == mUids.size()) && (mUids.valueAt(0).count() == 1)) {
1753 sb.append(" Uid: ").append(mUids.valueAt(0).start);
1754 } else {
1755 sb.append(" Uids: <").append(mUids).append(">");
1756 }
1757 }
Qingxi Li7cf06622020-01-17 17:54:27 -08001758 if (mOwnerUid != Process.INVALID_UID) {
1759 sb.append(" OwnerUid: ").append(mOwnerUid);
Chalard Jean07ace0f2018-02-26 19:00:45 +09001760 }
Robert Greenwalt1448f052014-04-08 13:41:39 -07001761
Cody Kestingf7ac9962020-03-16 18:15:28 -07001762 if (mAdministratorUids.length == 0) {
1763 sb.append(" AdministratorUids: ").append(Arrays.toString(mAdministratorUids));
Cody Kesting201fc132020-01-17 11:58:36 -08001764 }
1765
Chalard Jeanb03a6222018-04-11 21:09:10 +09001766 if (null != mSSID) {
1767 sb.append(" SSID: ").append(mSSID);
1768 }
1769
lucaslin783f2212019-10-22 18:27:33 +08001770 if (mPrivateDnsBroken) {
1771 sb.append(" Private DNS is broken");
1772 }
1773
Roshan Piuse38acab2020-01-16 12:17:17 -08001774 sb.append(" RequestorUid: ").append(mRequestorUid);
1775 sb.append(" RequestorPackageName: ").append(mRequestorPackageName);
1776
Chalard Jean07ace0f2018-02-26 19:00:45 +09001777 sb.append("]");
1778 return sb.toString();
1779 }
Robert Greenwalt5f90bcc2014-07-09 17:25:41 -07001780
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001781
Chalard Jean07ace0f2018-02-26 19:00:45 +09001782 private interface NameOf {
1783 String nameOf(int value);
1784 }
Roshan Piuse38acab2020-01-16 12:17:17 -08001785
Chalard Jean07ace0f2018-02-26 19:00:45 +09001786 /**
1787 * @hide
1788 */
paulhud9736de2019-03-08 16:35:20 +08001789 public static void appendStringRepresentationOfBitMaskToStringBuilder(@NonNull StringBuilder sb,
1790 long bitMask, @NonNull NameOf nameFetcher, @NonNull String separator) {
Chalard Jean07ace0f2018-02-26 19:00:45 +09001791 int bitPos = 0;
1792 boolean firstElementAdded = false;
1793 while (bitMask != 0) {
1794 if ((bitMask & 1) != 0) {
1795 if (firstElementAdded) {
1796 sb.append(separator);
1797 } else {
1798 firstElementAdded = true;
1799 }
1800 sb.append(nameFetcher.nameOf(bitPos));
1801 }
1802 bitMask >>= 1;
1803 ++bitPos;
1804 }
Robert Greenwalt1448f052014-04-08 13:41:39 -07001805 }
Hugo Benichi5df9d722016-04-25 17:16:35 +09001806
Kweku Adams85f2fbc2017-12-18 12:04:12 -08001807 /** @hide */
Jeffrey Huangcb782852019-12-05 11:28:11 -08001808 public void dumpDebug(@NonNull ProtoOutputStream proto, long fieldId) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08001809 final long token = proto.start(fieldId);
1810
1811 for (int transport : getTransportTypes()) {
1812 proto.write(NetworkCapabilitiesProto.TRANSPORTS, transport);
1813 }
1814
1815 for (int capability : getCapabilities()) {
1816 proto.write(NetworkCapabilitiesProto.CAPABILITIES, capability);
1817 }
1818
1819 proto.write(NetworkCapabilitiesProto.LINK_UP_BANDWIDTH_KBPS, mLinkUpBandwidthKbps);
1820 proto.write(NetworkCapabilitiesProto.LINK_DOWN_BANDWIDTH_KBPS, mLinkDownBandwidthKbps);
1821
1822 if (mNetworkSpecifier != null) {
1823 proto.write(NetworkCapabilitiesProto.NETWORK_SPECIFIER, mNetworkSpecifier.toString());
1824 }
Etan Cohenca9fb562018-11-27 07:32:39 -08001825 if (mTransportInfo != null) {
1826 // TODO b/120653863: write transport-specific info to proto?
1827 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08001828
1829 proto.write(NetworkCapabilitiesProto.CAN_REPORT_SIGNAL_STRENGTH, hasSignalStrength());
1830 proto.write(NetworkCapabilitiesProto.SIGNAL_STRENGTH, mSignalStrength);
1831
1832 proto.end(token);
1833 }
1834
Hugo Benichi5df9d722016-04-25 17:16:35 +09001835 /**
1836 * @hide
1837 */
paulhud9736de2019-03-08 16:35:20 +08001838 public static @NonNull String capabilityNamesOf(@Nullable @NetCapability int[] capabilities) {
Hugo Benichieae7a222017-07-25 11:40:56 +09001839 StringJoiner joiner = new StringJoiner("|");
1840 if (capabilities != null) {
1841 for (int c : capabilities) {
1842 joiner.add(capabilityNameOf(c));
1843 }
1844 }
1845 return joiner.toString();
1846 }
1847
1848 /**
1849 * @hide
1850 */
paulhud9736de2019-03-08 16:35:20 +08001851 public static @NonNull String capabilityNameOf(@NetCapability int capability) {
Hugo Benichieae7a222017-07-25 11:40:56 +09001852 switch (capability) {
lucasline252a742019-03-12 13:08:03 +08001853 case NET_CAPABILITY_MMS: return "MMS";
1854 case NET_CAPABILITY_SUPL: return "SUPL";
1855 case NET_CAPABILITY_DUN: return "DUN";
1856 case NET_CAPABILITY_FOTA: return "FOTA";
1857 case NET_CAPABILITY_IMS: return "IMS";
1858 case NET_CAPABILITY_CBS: return "CBS";
1859 case NET_CAPABILITY_WIFI_P2P: return "WIFI_P2P";
1860 case NET_CAPABILITY_IA: return "IA";
1861 case NET_CAPABILITY_RCS: return "RCS";
1862 case NET_CAPABILITY_XCAP: return "XCAP";
1863 case NET_CAPABILITY_EIMS: return "EIMS";
1864 case NET_CAPABILITY_NOT_METERED: return "NOT_METERED";
1865 case NET_CAPABILITY_INTERNET: return "INTERNET";
1866 case NET_CAPABILITY_NOT_RESTRICTED: return "NOT_RESTRICTED";
1867 case NET_CAPABILITY_TRUSTED: return "TRUSTED";
1868 case NET_CAPABILITY_NOT_VPN: return "NOT_VPN";
1869 case NET_CAPABILITY_VALIDATED: return "VALIDATED";
1870 case NET_CAPABILITY_CAPTIVE_PORTAL: return "CAPTIVE_PORTAL";
1871 case NET_CAPABILITY_NOT_ROAMING: return "NOT_ROAMING";
1872 case NET_CAPABILITY_FOREGROUND: return "FOREGROUND";
1873 case NET_CAPABILITY_NOT_CONGESTED: return "NOT_CONGESTED";
1874 case NET_CAPABILITY_NOT_SUSPENDED: return "NOT_SUSPENDED";
1875 case NET_CAPABILITY_OEM_PAID: return "OEM_PAID";
1876 case NET_CAPABILITY_MCX: return "MCX";
1877 case NET_CAPABILITY_PARTIAL_CONNECTIVITY: return "PARTIAL_CONNECTIVITY";
Jack Yu30be5e52020-04-02 15:34:33 -07001878 case NET_CAPABILITY_TEMPORARILY_NOT_METERED: return "TEMPORARILY_NOT_METERED";
lucasline252a742019-03-12 13:08:03 +08001879 default: return Integer.toString(capability);
Hugo Benichieae7a222017-07-25 11:40:56 +09001880 }
1881 }
1882
1883 /**
1884 * @hide
1885 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +01001886 @UnsupportedAppUsage
paulhud9736de2019-03-08 16:35:20 +08001887 public static @NonNull String transportNamesOf(@Nullable @Transport int[] types) {
Hugo Benichieae7a222017-07-25 11:40:56 +09001888 StringJoiner joiner = new StringJoiner("|");
1889 if (types != null) {
1890 for (int t : types) {
1891 joiner.add(transportNameOf(t));
1892 }
Hugo Benichi5df9d722016-04-25 17:16:35 +09001893 }
Hugo Benichieae7a222017-07-25 11:40:56 +09001894 return joiner.toString();
Hugo Benichi9910dbc2017-03-22 18:29:58 +09001895 }
1896
1897 /**
1898 * @hide
1899 */
paulhud9736de2019-03-08 16:35:20 +08001900 public static @NonNull String transportNameOf(@Transport int transport) {
Hugo Benichi16f0a942017-06-20 14:07:59 +09001901 if (!isValidTransport(transport)) {
Hugo Benichi9910dbc2017-03-22 18:29:58 +09001902 return "UNKNOWN";
1903 }
1904 return TRANSPORT_NAMES[transport];
Hugo Benichi5df9d722016-04-25 17:16:35 +09001905 }
Hugo Benichi16f0a942017-06-20 14:07:59 +09001906
Jeff Sharkeyde570312017-10-24 21:25:50 -06001907 private static void checkValidTransportType(@Transport int transport) {
Hugo Benichi16f0a942017-06-20 14:07:59 +09001908 Preconditions.checkArgument(
1909 isValidTransport(transport), "Invalid TransportType " + transport);
1910 }
Pavel Maltsev1cd48da2018-02-01 11:16:02 -08001911
1912 private static boolean isValidCapability(@NetworkCapabilities.NetCapability int capability) {
1913 return capability >= MIN_NET_CAPABILITY && capability <= MAX_NET_CAPABILITY;
1914 }
1915
1916 private static void checkValidCapability(@NetworkCapabilities.NetCapability int capability) {
1917 Preconditions.checkArgument(isValidCapability(capability),
1918 "NetworkCapability " + capability + "out of range");
1919 }
junyulai05986c62018-08-07 19:50:45 +08001920
1921 /**
1922 * Check if this {@code NetworkCapability} instance is metered.
1923 *
1924 * @return {@code true} if {@code NET_CAPABILITY_NOT_METERED} is not set on this instance.
1925 * @hide
1926 */
1927 public boolean isMetered() {
1928 return !hasCapability(NET_CAPABILITY_NOT_METERED);
1929 }
lucaslin783f2212019-10-22 18:27:33 +08001930
1931 /**
1932 * Check if private dns is broken.
1933 *
1934 * @return {@code true} if {@code mPrivateDnsBroken} is set when private DNS is broken.
1935 * @hide
1936 */
1937 public boolean isPrivateDnsBroken() {
1938 return mPrivateDnsBroken;
1939 }
1940
1941 /**
1942 * Set mPrivateDnsBroken to true when private dns is broken.
1943 *
1944 * @param broken the status of private DNS to be set.
1945 * @hide
1946 */
1947 public void setPrivateDnsBroken(boolean broken) {
1948 mPrivateDnsBroken = broken;
1949 }
1950
1951 private boolean equalsPrivateDnsBroken(NetworkCapabilities nc) {
1952 return mPrivateDnsBroken == nc.mPrivateDnsBroken;
1953 }
Roshan Piuse38acab2020-01-16 12:17:17 -08001954
1955 /**
Chalard Jeane5e38502020-03-18 15:58:50 +09001956 * Set the UID of the app making the request.
Roshan Piuse38acab2020-01-16 12:17:17 -08001957 *
Chalard Jeane5e38502020-03-18 15:58:50 +09001958 * For instances of NetworkCapabilities representing a request, sets the
1959 * UID of the app making the request. For a network created by the system,
1960 * sets the UID of the only app whose requests can match this network.
1961 * This can be set to {@link Process#INVALID_UID} if there is no such app,
1962 * or if this instance of NetworkCapabilities is about to be sent to a
1963 * party that should not learn about this.
Roshan Piuse38acab2020-01-16 12:17:17 -08001964 *
1965 * @param uid UID of the app.
1966 * @hide
1967 */
Roshan Piuse38acab2020-01-16 12:17:17 -08001968 public @NonNull NetworkCapabilities setRequestorUid(int uid) {
1969 mRequestorUid = uid;
1970 return this;
1971 }
1972
1973 /**
Chalard Jeane5e38502020-03-18 15:58:50 +09001974 * Returns the UID of the app making the request.
Roshan Piuse38acab2020-01-16 12:17:17 -08001975 *
Chalard Jeane5e38502020-03-18 15:58:50 +09001976 * For a NetworkRequest being made by an app, contains the app's UID. For a network
1977 * created by the system, contains the UID of the only app whose requests can match
1978 * this network, or {@link Process#INVALID_UID} if none or if the
1979 * caller does not have permission to learn about this.
1980 *
1981 * @return the uid of the app making the request.
Roshan Piuse38acab2020-01-16 12:17:17 -08001982 * @hide
1983 */
1984 public int getRequestorUid() {
1985 return mRequestorUid;
1986 }
1987
1988 /**
1989 * Set the package name of the app making the request.
1990 *
Chalard Jeane5e38502020-03-18 15:58:50 +09001991 * For instances of NetworkCapabilities representing a request, sets the
1992 * package name of the app making the request. For a network created by the system,
1993 * sets the package name of the only app whose requests can match this network.
1994 * This can be set to null if there is no such app, or if this instance of
1995 * NetworkCapabilities is about to be sent to a party that should not learn about this.
Roshan Piuse38acab2020-01-16 12:17:17 -08001996 *
1997 * @param packageName package name of the app.
1998 * @hide
1999 */
Roshan Piuse38acab2020-01-16 12:17:17 -08002000 public @NonNull NetworkCapabilities setRequestorPackageName(@NonNull String packageName) {
2001 mRequestorPackageName = packageName;
2002 return this;
2003 }
2004
2005 /**
Chalard Jeane5e38502020-03-18 15:58:50 +09002006 * Returns the package name of the app making the request.
Roshan Piuse38acab2020-01-16 12:17:17 -08002007 *
Chalard Jeane5e38502020-03-18 15:58:50 +09002008 * For a NetworkRequest being made by an app, contains the app's package name. For a
2009 * network created by the system, contains the package name of the only app whose
2010 * requests can match this network, or null if none or if the caller does not have
2011 * permission to learn about this.
2012 *
2013 * @return the package name of the app making the request.
Roshan Piuse38acab2020-01-16 12:17:17 -08002014 * @hide
2015 */
2016 @Nullable
2017 public String getRequestorPackageName() {
2018 return mRequestorPackageName;
2019 }
2020
2021 /**
Chalard Jeane5e38502020-03-18 15:58:50 +09002022 * Set the uid and package name of the app causing this network to exist.
Roshan Piuse38acab2020-01-16 12:17:17 -08002023 *
Chalard Jeane5e38502020-03-18 15:58:50 +09002024 * {@see #setRequestorUid} and {@link #setRequestorPackageName}
Roshan Piuse38acab2020-01-16 12:17:17 -08002025 *
2026 * @param uid UID of the app.
2027 * @param packageName package name of the app.
2028 * @hide
2029 */
2030 public @NonNull NetworkCapabilities setRequestorUidAndPackageName(
2031 int uid, @NonNull String packageName) {
2032 return setRequestorUid(uid).setRequestorPackageName(packageName);
2033 }
2034
2035 /**
2036 * Test whether the passed NetworkCapabilities satisfies the requestor restrictions of this
2037 * capabilities.
2038 *
2039 * This method is called on the NetworkCapabilities embedded in a request with the
2040 * capabilities of an available network. If the available network, sets a specific
2041 * requestor (by uid and optionally package name), then this will only match a request from the
2042 * same app. If either of the capabilities have an unset uid or package name, then it matches
2043 * everything.
2044 * <p>
2045 * nc is assumed nonnull. Else, NPE.
2046 */
2047 private boolean satisfiedByRequestor(NetworkCapabilities nc) {
2048 // No uid set, matches everything.
2049 if (mRequestorUid == Process.INVALID_UID || nc.mRequestorUid == Process.INVALID_UID) {
2050 return true;
2051 }
2052 // uids don't match.
2053 if (mRequestorUid != nc.mRequestorUid) return false;
2054 // No package names set, matches everything
2055 if (null == nc.mRequestorPackageName || null == mRequestorPackageName) return true;
2056 // check for package name match.
2057 return TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
2058 }
2059
2060 /**
2061 * Combine requestor info of the capabilities.
2062 * <p>
2063 * This is only legal if either the requestor info of this object is reset, or both info are
2064 * equal.
2065 * nc is assumed nonnull.
2066 */
2067 private void combineRequestor(@NonNull NetworkCapabilities nc) {
2068 if (mRequestorUid != Process.INVALID_UID && mRequestorUid != nc.mOwnerUid) {
2069 throw new IllegalStateException("Can't combine two uids");
2070 }
2071 if (mRequestorPackageName != null
2072 && !mRequestorPackageName.equals(nc.mRequestorPackageName)) {
2073 throw new IllegalStateException("Can't combine two package names");
2074 }
2075 setRequestorUid(nc.mRequestorUid);
2076 setRequestorPackageName(nc.mRequestorPackageName);
2077 }
2078
2079 private boolean equalsRequestor(NetworkCapabilities nc) {
2080 return mRequestorUid == nc.mRequestorUid
2081 && TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
2082 }
Chalard Jeane5e38502020-03-18 15:58:50 +09002083
2084 /**
2085 * Builder class for NetworkCapabilities.
2086 *
2087 * This class is mainly for for {@link NetworkAgent} instances to use. Many fields in
2088 * the built class require holding a signature permission to use - mostly
2089 * {@link android.Manifest.permission.NETWORK_FACTORY}, but refer to the specific
2090 * description of each setter. As this class lives entirely in app space it does not
2091 * enforce these restrictions itself but the system server clears out the relevant
2092 * fields when receiving a NetworkCapabilities object from a caller without the
2093 * appropriate permission.
2094 *
2095 * Apps don't use this builder directly. Instead, they use {@link NetworkRequest} via
2096 * its builder object.
2097 *
2098 * @hide
2099 */
2100 @SystemApi
2101 @TestApi
Aaron Huangfbb485a2020-03-25 13:36:38 +08002102 public static final class Builder {
Chalard Jeane5e38502020-03-18 15:58:50 +09002103 private final NetworkCapabilities mCaps;
2104
2105 /**
2106 * Creates a new Builder to construct NetworkCapabilities objects.
2107 */
2108 public Builder() {
2109 mCaps = new NetworkCapabilities();
2110 }
2111
2112 /**
2113 * Creates a new Builder of NetworkCapabilities from an existing instance.
2114 */
2115 public Builder(@NonNull final NetworkCapabilities nc) {
2116 Objects.requireNonNull(nc);
2117 mCaps = new NetworkCapabilities(nc);
2118 }
2119
2120 /**
2121 * Adds the given transport type.
2122 *
2123 * Multiple transports may be added. Note that when searching for a network to satisfy a
2124 * request, satisfying any of the transports listed in the request will satisfy the request.
2125 * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a
2126 * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network
2127 * to be selected. This is logically different than
2128 * {@code NetworkCapabilities.NET_CAPABILITY_*}.
2129 *
2130 * @param transportType the transport type to be added or removed.
2131 * @return this builder
2132 */
2133 @NonNull
2134 public Builder addTransportType(@Transport int transportType) {
2135 checkValidTransportType(transportType);
2136 mCaps.addTransportType(transportType);
2137 return this;
2138 }
2139
2140 /**
2141 * Removes the given transport type.
2142 *
2143 * {@see #addTransportType}.
2144 *
2145 * @param transportType the transport type to be added or removed.
2146 * @return this builder
2147 */
2148 @NonNull
2149 public Builder removeTransportType(@Transport int transportType) {
2150 checkValidTransportType(transportType);
2151 mCaps.removeTransportType(transportType);
2152 return this;
2153 }
2154
2155 /**
2156 * Adds the given capability.
2157 *
2158 * @param capability the capability
2159 * @return this builder
2160 */
2161 @NonNull
2162 public Builder addCapability(@NetCapability final int capability) {
2163 mCaps.setCapability(capability, true);
2164 return this;
2165 }
2166
2167 /**
2168 * Removes the given capability.
2169 *
2170 * @param capability the capability
2171 * @return this builder
2172 */
2173 @NonNull
2174 public Builder removeCapability(@NetCapability final int capability) {
2175 mCaps.setCapability(capability, false);
2176 return this;
2177 }
2178
2179 /**
2180 * Sets the owner UID.
2181 *
2182 * The default value is {@link Process#INVALID_UID}. Pass this value to reset.
2183 *
2184 * Note: for security the system will clear out this field when received from a
2185 * non-privileged source.
2186 *
2187 * @param ownerUid the owner UID
2188 * @return this builder
2189 */
2190 @NonNull
2191 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
2192 public Builder setOwnerUid(final int ownerUid) {
2193 mCaps.setOwnerUid(ownerUid);
2194 return this;
2195 }
2196
2197 /**
2198 * Sets the list of UIDs that are administrators of this network.
2199 *
2200 * <p>UIDs included in administratorUids gain administrator privileges over this
2201 * Network. Examples of UIDs that should be included in administratorUids are:
2202 * <ul>
2203 * <li>Carrier apps with privileges for the relevant subscription
2204 * <li>Active VPN apps
2205 * <li>Other application groups with a particular Network-related role
2206 * </ul>
2207 *
2208 * <p>In general, user-supplied networks (such as WiFi networks) do not have
2209 * administrators.
2210 *
2211 * <p>An app is granted owner privileges over Networks that it supplies. The owner
2212 * UID MUST always be included in administratorUids.
2213 *
2214 * The default value is the empty array. Pass an empty array to reset.
2215 *
2216 * Note: for security the system will clear out this field when received from a
2217 * non-privileged source, such as an app using reflection to call this or
2218 * mutate the member in the built object.
2219 *
2220 * @param administratorUids the UIDs to be set as administrators of this Network.
2221 * @return this builder
2222 */
2223 @NonNull
2224 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
2225 public Builder setAdministratorUids(@NonNull final int[] administratorUids) {
2226 Objects.requireNonNull(administratorUids);
2227 mCaps.setAdministratorUids(administratorUids);
2228 return this;
2229 }
2230
2231 /**
2232 * Sets the upstream bandwidth of the link.
2233 *
2234 * Sets the upstream bandwidth for this network in Kbps. This always only refers to
2235 * the estimated first hop transport bandwidth.
2236 * <p>
2237 * Note that when used to request a network, this specifies the minimum acceptable.
2238 * When received as the state of an existing network this specifies the typical
2239 * first hop bandwidth expected. This is never measured, but rather is inferred
2240 * from technology type and other link parameters. It could be used to differentiate
2241 * between very slow 1xRTT cellular links and other faster networks or even between
2242 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
2243 * fast backhauls and slow backhauls.
2244 *
2245 * @param upKbps the estimated first hop upstream (device to network) bandwidth.
2246 * @return this builder
2247 */
2248 @NonNull
2249 public Builder setLinkUpstreamBandwidthKbps(final int upKbps) {
2250 mCaps.setLinkUpstreamBandwidthKbps(upKbps);
2251 return this;
2252 }
2253
2254 /**
2255 * Sets the downstream bandwidth for this network in Kbps. This always only refers to
2256 * the estimated first hop transport bandwidth.
2257 * <p>
2258 * Note that when used to request a network, this specifies the minimum acceptable.
2259 * When received as the state of an existing network this specifies the typical
2260 * first hop bandwidth expected. This is never measured, but rather is inferred
2261 * from technology type and other link parameters. It could be used to differentiate
2262 * between very slow 1xRTT cellular links and other faster networks or even between
2263 * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
2264 * fast backhauls and slow backhauls.
2265 *
2266 * @param downKbps the estimated first hop downstream (network to device) bandwidth.
2267 * @return this builder
2268 */
2269 @NonNull
2270 public Builder setLinkDownstreamBandwidthKbps(final int downKbps) {
2271 mCaps.setLinkDownstreamBandwidthKbps(downKbps);
2272 return this;
2273 }
2274
2275 /**
2276 * Sets the optional bearer specific network specifier.
2277 * This has no meaning if a single transport is also not specified, so calling
2278 * this without a single transport set will generate an exception, as will
2279 * subsequently adding or removing transports after this is set.
2280 * </p>
2281 *
2282 * @param specifier a concrete, parcelable framework class that extends NetworkSpecifier,
2283 * or null to clear it.
2284 * @return this builder
2285 */
2286 @NonNull
2287 public Builder setNetworkSpecifier(@Nullable final NetworkSpecifier specifier) {
2288 mCaps.setNetworkSpecifier(specifier);
2289 return this;
2290 }
2291
2292 /**
2293 * Sets the optional transport specific information.
2294 *
2295 * @param info A concrete, parcelable framework class that extends {@link TransportInfo},
2296 * or null to clear it.
2297 * @return this builder
2298 */
2299 @NonNull
2300 public Builder setTransportInfo(@Nullable final TransportInfo info) {
2301 mCaps.setTransportInfo(info);
2302 return this;
2303 }
2304
2305 /**
2306 * Sets the signal strength. This is a signed integer, with higher values indicating a
2307 * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the
2308 * same RSSI units reported by wifi code.
2309 * <p>
2310 * Note that when used to register a network callback, this specifies the minimum
2311 * acceptable signal strength. When received as the state of an existing network it
2312 * specifies the current value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means
2313 * no value when received and has no effect when requesting a callback.
2314 *
2315 * Note: for security the system will throw if it receives a NetworkRequest where
2316 * the underlying NetworkCapabilities has this member set from a source that does
2317 * not hold the {@link android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP}
2318 * permission. Apps with this permission can use this indirectly through
2319 * {@link android.net.NetworkRequest}.
2320 *
2321 * @param signalStrength the bearer-specific signal strength.
2322 * @return this builder
2323 */
2324 @NonNull
2325 @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP)
2326 public Builder setSignalStrength(final int signalStrength) {
2327 mCaps.setSignalStrength(signalStrength);
2328 return this;
2329 }
2330
2331 /**
2332 * Sets the SSID of this network.
2333 *
2334 * Note: for security the system will clear out this field when received from a
2335 * non-privileged source, like an app using reflection to set this.
2336 *
2337 * @param ssid the SSID, or null to clear it.
2338 * @return this builder
2339 */
2340 @NonNull
2341 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
2342 public Builder setSsid(@Nullable final String ssid) {
2343 mCaps.setSSID(ssid);
2344 return this;
2345 }
2346
2347 /**
2348 * Set the uid of the app causing this network to exist.
2349 *
2350 * Note: for security the system will clear out this field when received from a
2351 * non-privileged source.
2352 *
2353 * @param uid UID of the app.
2354 * @return this builder
2355 */
2356 @NonNull
2357 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
2358 public Builder setRequestorUid(final int uid) {
2359 mCaps.setRequestorUid(uid);
2360 return this;
2361 }
2362
2363 /**
2364 * Set the package name of the app causing this network to exist.
2365 *
2366 * Note: for security the system will clear out this field when received from a
2367 * non-privileged source.
2368 *
2369 * @param packageName package name of the app, or null to clear it.
2370 * @return this builder
2371 */
2372 @NonNull
2373 @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
2374 public Builder setRequestorPackageName(@Nullable final String packageName) {
2375 mCaps.setRequestorPackageName(packageName);
2376 return this;
2377 }
2378
2379 /**
2380 * Builds the instance of the capabilities.
2381 *
2382 * @return the built instance of NetworkCapabilities.
2383 */
2384 @NonNull
2385 public NetworkCapabilities build() {
2386 if (mCaps.getOwnerUid() != Process.INVALID_UID) {
2387 if (!ArrayUtils.contains(mCaps.getAdministratorUids(), mCaps.getOwnerUid())) {
2388 throw new IllegalStateException("The owner UID must be included in "
2389 + " administrator UIDs.");
2390 }
2391 }
2392 return new NetworkCapabilities(mCaps);
2393 }
2394 }
Robert Greenwalt1448f052014-04-08 13:41:39 -07002395}