Debian Codegraph @

core/java/android/app/admin/PreferentialNetworkServiceConfig.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.app.admin;
18
19 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20 import static org.xmlpull.v1.XmlPullParser.END_TAG;
21 import static org.xmlpull.v1.XmlPullParser.TEXT;
22
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.SuppressLint;
26 import android.os.Parcel;
27 import android.os.Parcelable;
28 import android.util.IndentingPrintWriter;
29 import android.util.Log;
30 import android.util.TypedXmlPullParser;
31 import android.util.TypedXmlSerializer;
32
33 import org.xmlpull.v1.XmlPullParserException;
34
35 import java.io.IOException;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.List;
42 import java.util.Objects;
43 import java.util.stream.Collectors;
44
45 /**
46 * Network configuration to be set for the user profile
47 * {@see DevicePolicyManager#setPreferentialNetworkServiceConfigs}.
48 */
49 public final class PreferentialNetworkServiceConfig implements Parcelable {
50 final boolean mIsEnabled;
51 final int mNetworkId;
52 final boolean mAllowFallbackToDefaultConnection;
53 final boolean mShouldBlockNonMatchingNetworks;
54 final int[] mIncludedUids;
55 final int[] mExcludedUids;
56
57 private static final String LOG_TAG = "PreferentialNetworkServiceConfig";
58 private static final String TAG_PREFERENTIAL_NETWORK_SERVICE_CONFIG =
59 "preferential_network_service_config";
60 private static final String TAG_CONFIG_ENABLED =
61 "preferential_network_service_config_enabled";
62 private static final String TAG_UID = "uid";
63 private static final String TAG_NETWORK_ID =
64 "preferential_network_service_network_id";
65 private static final String TAG_ALLOW_FALLBACK_TO_DEFAULT_CONNECTION =
66 "allow_fallback_to_default_connection";
67 private static final String TAG_BLOCK_NON_MATCHING_NETWORKS =
68 "block_non_matching_networks";
69 private static final String TAG_INCLUDED_UIDS = "included_uids";
70 private static final String TAG_EXCLUDED_UIDS = "excluded_uids";
71 private static final String ATTR_VALUE = "value";
72
73 /** @hide */
74 public static final PreferentialNetworkServiceConfig DEFAULT =
75 (new PreferentialNetworkServiceConfig.Builder()).build();
76
77 /**
78 * Preferential network identifier 1.
79 */
80 public static final int PREFERENTIAL_NETWORK_ID_1 = 1;
81
82 /**
83 * Preferential network identifier 2.
84 */
85 public static final int PREFERENTIAL_NETWORK_ID_2 = 2;
86
87 /**
88 * Preferential network identifier 3.
89 */
90 public static final int PREFERENTIAL_NETWORK_ID_3 = 3;
91
92 /**
93 * Preferential network identifier 4.
94 */
95 public static final int PREFERENTIAL_NETWORK_ID_4 = 4;
96
97 /**
98 * Preferential network identifier 5.
99 */
100 public static final int PREFERENTIAL_NETWORK_ID_5 = 5;
101
102 /** @hide */
103 @Retention(RetentionPolicy.SOURCE)
104 @IntDef(prefix = { "PREFERENTIAL_NETWORK_ID_" }, value = {
105 PREFERENTIAL_NETWORK_ID_1,
106 PREFERENTIAL_NETWORK_ID_2,
107 PREFERENTIAL_NETWORK_ID_3,
108 PREFERENTIAL_NETWORK_ID_4,
109 PREFERENTIAL_NETWORK_ID_5,
110 })
111
112 public @interface PreferentialNetworkPreferenceId {
113 }
114
115 private PreferentialNetworkServiceConfig(boolean isEnabled,
116 boolean allowFallbackToDefaultConnection, boolean shouldBlockNonMatchingNetworks,
117 int[] includedUids,
118 int[] excludedUids, @PreferentialNetworkPreferenceId int networkId) {
119 mIsEnabled = isEnabled;
120 mAllowFallbackToDefaultConnection = allowFallbackToDefaultConnection;
121 mShouldBlockNonMatchingNetworks = shouldBlockNonMatchingNetworks;
122 mIncludedUids = includedUids;
123 mExcludedUids = excludedUids;
124 mNetworkId = networkId;
125 }
126
127 private PreferentialNetworkServiceConfig(Parcel in) {
128 mIsEnabled = in.readBoolean();
129 mAllowFallbackToDefaultConnection = in.readBoolean();
130 mShouldBlockNonMatchingNetworks = in.readBoolean();
131 mNetworkId = in.readInt();
132 mIncludedUids = in.createIntArray();
133 mExcludedUids = in.createIntArray();
134 }
135
136 /**
137 * Is the preferential network enabled.
138 * @return true if enabled else false
139 */
140 public boolean isEnabled() {
141 return mIsEnabled;
142 }
143
144 /**
145 * Whether fallback to the device-wide default network is allowed.
146 *
147 * This boolean configures whether the default connection (e.g. general cell network or wifi)
148 * should be used if no preferential network service connection is available. If true, the
149 * default connection will be used when no preferential service is available. If false, the
150 * UIDs subject to this configuration will have no default network.
151 * Note that while this boolean determines whether the UIDs subject to this configuration have
152 * a default network in the absence of a preferential service, apps can still explicitly decide
153 * to use another network than their default network by requesting them from the system. This
154 * boolean does not determine whether the UIDs are blocked from using such other networks.
155 * See {@link #shouldBlockNonMatchingNetworks()} for that configuration.
156 *
157 * @return true if fallback is allowed, else false.
158 */
159 public boolean isFallbackToDefaultConnectionAllowed() {
160 return mAllowFallbackToDefaultConnection;
161 }
162
163 /**
164 * Whether to block UIDs from using other networks than the preferential service.
165 *
166 * Apps can inspect the list of available networks on the device and choose to use multiple
167 * of them concurrently for performance, privacy or other reasons.
168 * This boolean configures whether the concerned UIDs should be blocked from using
169 * networks that do not match the configured preferential network service even if these
170 * networks are otherwise open to all apps.
171 *
172 * @return true if UIDs should be blocked from using the other networks, else false.
173 */
174 public boolean shouldBlockNonMatchingNetworks() {
175 return mShouldBlockNonMatchingNetworks;
176 }
177
178 /**
179 * Get the array of uids that are applicable for the profile preference.
180 *
181 * {@see #getExcludedUids()}
182 * Included UIDs and Excluded UIDs can't both be non-empty.
183 * if both are empty, it means this request applies to all uids in the user profile.
184 * if included is not empty, then only included UIDs are applied.
185 * if excluded is not empty, then it is all uids in the user profile except these UIDs.
186 * @return Array of uids applicable for the profile preference.
187 * Empty array would mean that this request applies to all uids in the profile.
188 */
189 public @NonNull int[] getIncludedUids() {
190 return mIncludedUids;
191 }
192
193 /**
194 * Get the array of uids that are excluded for the profile preference.
195 *
196 * {@see #getIncludedUids()}
197 * Included UIDs and Excluded UIDs can't both be non-empty.
198 * if both are empty, it means this request applies to all uids in the user profile.
199 * if included is not empty, then only included UIDs are applied.
200 * if excluded is not empty, then it is all uids in the user profile except these UIDs.
201 * @return Array of uids that are excluded for the profile preference.
202 * Empty array would mean that this request applies to all uids in the profile.
203 */
204 public @NonNull int[] getExcludedUids() {
205 return mExcludedUids;
206 }
207
208 /**
209 * @return preference enterprise identifier.
210 * preference identifier is applicable only if preference network service is enabled
211 *
212 */
213 public @PreferentialNetworkPreferenceId int getNetworkId() {
214 return mNetworkId;
215 }
216
217 @Override
218 public String toString() {
219 return "PreferentialNetworkServiceConfig{"
220 + "mIsEnabled=" + isEnabled()
221 + "mAllowFallbackToDefaultConnection=" + isFallbackToDefaultConnectionAllowed()
222 + "mBlockNonMatchingNetworks=" + shouldBlockNonMatchingNetworks()
223 + "mIncludedUids=" + Arrays.toString(mIncludedUids)
224 + "mExcludedUids=" + Arrays.toString(mExcludedUids)
225 + "mNetworkId=" + mNetworkId
226 + '}';
227 }
228
229 @Override
230 public boolean equals(Object o) {
231 if (this == o) return true;
232 if (o == null || getClass() != o.getClass()) return false;
233 final PreferentialNetworkServiceConfig that = (PreferentialNetworkServiceConfig) o;
234 return mIsEnabled == that.mIsEnabled
235 && mAllowFallbackToDefaultConnection == that.mAllowFallbackToDefaultConnection
236 && mShouldBlockNonMatchingNetworks == that.mShouldBlockNonMatchingNetworks
237 && mNetworkId == that.mNetworkId
238 && Arrays.equals(mIncludedUids, that.mIncludedUids)
239 && Arrays.equals(mExcludedUids, that.mExcludedUids);
240 }
241
242 @Override
243 public int hashCode() {
244 return Objects.hash(mIsEnabled, mAllowFallbackToDefaultConnection,
245 mShouldBlockNonMatchingNetworks, Arrays.hashCode(mIncludedUids),
246 Arrays.hashCode(mExcludedUids), mNetworkId);
247 }
248
249 /**
250 * Builder used to create {@link PreferentialNetworkServiceConfig} objects.
251 * Specify the preferred Network preference
252 */
253 public static final class Builder {
254 boolean mIsEnabled = false;
255 int mNetworkId = 0;
256 boolean mAllowFallbackToDefaultConnection = true;
257 boolean mShouldBlockNonMatchingNetworks = false;
258 int[] mIncludedUids = new int[0];
259 int[] mExcludedUids = new int[0];
260
261 /**
262 * Constructs an empty Builder with preferential network disabled by default.
263 */
264 public Builder() {}
265
266 /**
267 * Set the preferential network service enabled state.
268 * Default value is false.
269 * @param isEnabled the desired network preference to use, true to enable else false
270 * @return The builder to facilitate chaining.
271 */
272 @NonNull
273 public PreferentialNetworkServiceConfig.Builder setEnabled(boolean isEnabled) {
274 mIsEnabled = isEnabled;
275 return this;
276 }
277
278 /**
279 * Set whether fallback to the device-wide default network is allowed.
280 *
281 * This boolean configures whether the default connection (e.g. general cell network or
282 * wifi) should be used if no preferential network service connection is available. If true,
283 * the default connection will be used when no preferential service is available. If false,
284 * the UIDs subject to this configuration will have no default network.
285 * Note that while this boolean determines whether the UIDs subject to this configuration
286 * have a default network in the absence of a preferential service, apps can still
287 * explicitly decide to use another network than their default network by requesting them
288 * from the system. This boolean does not determine whether the UIDs are blocked from using
289 * such other networks.
290 * Use {@link #setShouldBlockNonMatchingNetworks(boolean)} to specify this.
291 *
292 * The default value is true.
293 *
294 * @param allowFallbackToDefaultConnection true if fallback is allowed else false
295 * @return The builder to facilitate chaining.
296 */
297 @NonNull
298 @SuppressLint("MissingGetterMatchingBuilder")
299 public PreferentialNetworkServiceConfig.Builder setFallbackToDefaultConnectionAllowed(
300 boolean allowFallbackToDefaultConnection) {
301 mAllowFallbackToDefaultConnection = allowFallbackToDefaultConnection;
302 return this;
303 }
304
305 /**
306 * Set whether to block UIDs from using other networks than the preferential service.
307 *
308 * Apps can inspect the list of available networks on the device and choose to use multiple
309 * of them concurrently for performance, privacy or other reasons.
310 * This boolean configures whether the concerned UIDs should be blocked from using
311 * networks that do not match the configured preferential network service even if these
312 * networks are otherwise open to all apps.
313 *
314 * The default value is false. This value can only be set to {@code true} if
315 * {@link #setFallbackToDefaultConnectionAllowed(boolean)} is set to {@code false}, because
316 * allowing fallback but blocking it does not make sense. Failure to comply with this
317 * constraint will throw when building the object.
318 *
319 * @param blockNonMatchingNetworks true if UIDs should be blocked from using non-matching
320 * networks.
321 * @return The builder to facilitate chaining.
322 */
323 @NonNull
324 public PreferentialNetworkServiceConfig.Builder setShouldBlockNonMatchingNetworks(
325 boolean blockNonMatchingNetworks) {
326 mShouldBlockNonMatchingNetworks = blockNonMatchingNetworks;
327 return this;
328 }
329
330 /**
331 * Set the array of uids whose network access will go through this preferential
332 * network service.
333 * {@see #setExcludedUids(int[])}
334 * Included UIDs and Excluded UIDs can't both be non-empty.
335 * if both are empty, it means this request applies to all uids in the user profile.
336 * if included is not empty, then only included UIDs are applied.
337 * if excluded is not empty, then it is all uids in the user profile except these UIDs.
338 * @param uids array of included uids
339 * @return The builder to facilitate chaining.
340 */
341 @NonNull
342 public PreferentialNetworkServiceConfig.Builder setIncludedUids(
343 @NonNull int[] uids) {
344 Objects.requireNonNull(uids);
345 mIncludedUids = uids;
346 return this;
347 }
348
349 /**
350 * Set the array of uids who are not allowed through this preferential
351 * network service.
352 * {@see #setIncludedUids(int[])}
353 * Included UIDs and Excluded UIDs can't both be non-empty.
354 * if both are empty, it means this request applies to all uids in the user profile.
355 * if included is not empty, then only included UIDs are applied.
356 * if excluded is not empty, then it is all uids in the user profile except these UIDs.
357 * @param uids array of excluded uids
358 * @return The builder to facilitate chaining.
359 */
360 @NonNull
361 public PreferentialNetworkServiceConfig.Builder setExcludedUids(
362 @NonNull int[] uids) {
363 Objects.requireNonNull(uids);
364 mExcludedUids = uids;
365 return this;
366 }
367
368 /**
369 * Returns an instance of {@link PreferentialNetworkServiceConfig} created from the
370 * fields set on this builder.
371 */
372 @NonNull
373 public PreferentialNetworkServiceConfig build() {
374 if (mIncludedUids.length > 0 && mExcludedUids.length > 0) {
375 throw new IllegalStateException("Both includedUids and excludedUids "
376 + "cannot be nonempty");
377 }
378 if (mShouldBlockNonMatchingNetworks && mAllowFallbackToDefaultConnection) {
379 throw new IllegalStateException("A config cannot both allow fallback and "
380 + "block non-matching networks");
381 }
382 return new PreferentialNetworkServiceConfig(mIsEnabled,
383 mAllowFallbackToDefaultConnection, mShouldBlockNonMatchingNetworks,
384 mIncludedUids, mExcludedUids, mNetworkId);
385 }
386
387 /**
388 * Set the preferential network identifier.
389 * preference identifier is applicable only if preferential network service is enabled.
390 * @param preferenceId preference Id
391 * @return The builder to facilitate chaining.
392 */
393 @NonNull
394 public PreferentialNetworkServiceConfig.Builder setNetworkId(
395 @PreferentialNetworkPreferenceId int preferenceId) {
396 if ((preferenceId < PREFERENTIAL_NETWORK_ID_1)
397 || (preferenceId > PREFERENTIAL_NETWORK_ID_5)) {
398 throw new IllegalArgumentException("Invalid preference identifier");
399 }
400 mNetworkId = preferenceId;
401 return this;
402 }
403 }
404
405 @Override
406 public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
407 dest.writeBoolean(mIsEnabled);
408 dest.writeBoolean(mAllowFallbackToDefaultConnection);
409 dest.writeBoolean(mShouldBlockNonMatchingNetworks);
410 dest.writeInt(mNetworkId);
411 dest.writeIntArray(mIncludedUids);
412 dest.writeIntArray(mExcludedUids);
413 }
414
415 private void writeAttributeValueToXml(TypedXmlSerializer out, String tag, int value)
416 throws IOException {
417 out.startTag(null, tag);
418 out.attributeInt(null, ATTR_VALUE, value);
419 out.endTag(null, tag);
420 }
421
422 private void writeAttributeValueToXml(TypedXmlSerializer out, String tag, boolean value)
423 throws IOException {
424 out.startTag(null, tag);
425 out.attributeBoolean(null, ATTR_VALUE, value);
426 out.endTag(null, tag);
427 }
428
429 private void writeAttributeValuesToXml(TypedXmlSerializer out, String outerTag, String innerTag,
430 @NonNull Collection<String> values) throws IOException {
431 out.startTag(null, outerTag);
432 for (String value : values) {
433 out.startTag(null, innerTag);
434 out.attribute(null, ATTR_VALUE, value);
435 out.endTag(null, innerTag);
436 }
437 out.endTag(null, outerTag);
438 }
439
440 private static void readAttributeValues(
441 TypedXmlPullParser parser, String tag, Collection<String> result)
442 throws XmlPullParserException, IOException {
443 result.clear();
444 int outerDepthDAM = parser.getDepth();
445 int typeDAM;
446 while ((typeDAM = parser.next()) != END_DOCUMENT
447 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
448 if (typeDAM == END_TAG || typeDAM == TEXT) {
449 continue;
450 }
451 String tagDAM = parser.getName();
452 if (tag.equals(tagDAM)) {
453 result.add(parser.getAttributeValue(null, ATTR_VALUE));
454 } else {
455 Log.e(LOG_TAG, "Expected tag " + tag + " but found " + tagDAM);
456 }
457 }
458 }
459
460 private List<String> intArrayToStringList(int[] array) {
461 return Arrays.stream(array).mapToObj(String::valueOf).collect(Collectors.toList());
462 }
463
464 private static int[] readStringListToIntArray(TypedXmlPullParser parser, String tag)
465 throws XmlPullParserException, IOException {
466 List<String> stringList = new ArrayList<>();
467 readAttributeValues(parser, tag, stringList);
468 int[] intArray = stringList.stream()
469 .map(s -> Integer.parseInt(s))
470 .mapToInt(Integer::intValue)
471 .toArray();
472 return intArray;
473 }
474
475 /**
476 * @hide
477 */
478 public static PreferentialNetworkServiceConfig getPreferentialNetworkServiceConfig(
479 TypedXmlPullParser parser, String tag) throws XmlPullParserException, IOException {
480 int outerDepthDAM = parser.getDepth();
481 int typeDAM;
482 PreferentialNetworkServiceConfig.Builder resultBuilder =
483 new PreferentialNetworkServiceConfig.Builder();
484 while ((typeDAM = parser.next()) != END_DOCUMENT
485 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
486 if (typeDAM == END_TAG || typeDAM == TEXT) {
487 continue;
488 }
489 String tagDAM = parser.getName();
490 if (TAG_CONFIG_ENABLED.equals(tagDAM)) {
491 resultBuilder.setEnabled(parser.getAttributeBoolean(null, ATTR_VALUE,
492 DevicePolicyManager.PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT));
493 } else if (TAG_NETWORK_ID.equals(tagDAM)) {
494 int val = parser.getAttributeInt(null, ATTR_VALUE, 0);
495 if (val != 0) {
496 resultBuilder.setNetworkId(val);
497 }
498 } else if (TAG_ALLOW_FALLBACK_TO_DEFAULT_CONNECTION.equals(tagDAM)) {
499 resultBuilder.setFallbackToDefaultConnectionAllowed(parser.getAttributeBoolean(
500 null, ATTR_VALUE, true));
501 } else if (TAG_BLOCK_NON_MATCHING_NETWORKS.equals(tagDAM)) {
502 resultBuilder.setShouldBlockNonMatchingNetworks(parser.getAttributeBoolean(
503 null, ATTR_VALUE, false));
504 } else if (TAG_INCLUDED_UIDS.equals(tagDAM)) {
505 resultBuilder.setIncludedUids(readStringListToIntArray(parser, TAG_UID));
506 } else if (TAG_EXCLUDED_UIDS.equals(tagDAM)) {
507 resultBuilder.setExcludedUids(readStringListToIntArray(parser, TAG_UID));
508 } else {
509 Log.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
510 }
511 }
512 return resultBuilder.build();
513 }
514
515 /**
516 * @hide
517 */
518 public void writeToXml(@NonNull TypedXmlSerializer out) throws IOException {
519 out.startTag(null, TAG_PREFERENTIAL_NETWORK_SERVICE_CONFIG);
520 writeAttributeValueToXml(out, TAG_CONFIG_ENABLED, isEnabled());
521 writeAttributeValueToXml(out, TAG_NETWORK_ID, getNetworkId());
522 writeAttributeValueToXml(out, TAG_ALLOW_FALLBACK_TO_DEFAULT_CONNECTION,
523 isFallbackToDefaultConnectionAllowed());
524 writeAttributeValueToXml(out, TAG_BLOCK_NON_MATCHING_NETWORKS,
525 shouldBlockNonMatchingNetworks());
526 writeAttributeValuesToXml(out, TAG_INCLUDED_UIDS, TAG_UID,
527 intArrayToStringList(getIncludedUids()));
528 writeAttributeValuesToXml(out, TAG_EXCLUDED_UIDS, TAG_UID,
529 intArrayToStringList(getExcludedUids()));
530 out.endTag(null, TAG_PREFERENTIAL_NETWORK_SERVICE_CONFIG);
531 }
532
533 /**
534 * @hide
535 */
536 public void dump(IndentingPrintWriter pw) {
537 pw.print("networkId=");
538 pw.println(mNetworkId);
539 pw.print("isEnabled=");
540 pw.println(mIsEnabled);
541 pw.print("allowFallbackToDefaultConnection=");
542 pw.println(mAllowFallbackToDefaultConnection);
543 pw.print("blockNonMatchingNetworks=");
544 pw.println(mShouldBlockNonMatchingNetworks);
545 pw.print("includedUids=");
546 pw.println(mIncludedUids);
547 pw.print("excludedUids=");
548 pw.println(mExcludedUids);
549 }
550
551 @Override
552 public int describeContents() {
553 return 0;
554 }
555
556 @NonNull
557 public static final Creator<PreferentialNetworkServiceConfig> CREATOR =
558 new Creator<PreferentialNetworkServiceConfig>() {
559 @Override
560 public PreferentialNetworkServiceConfig[] newArray(int size) {
561 return new PreferentialNetworkServiceConfig[size];
562 }
563
564 @Override
565 public PreferentialNetworkServiceConfig createFromParcel(
566 @NonNull android.os.Parcel in) {
567 return new PreferentialNetworkServiceConfig(in);
568 }
569 };
570 }