• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.net;
18 
19 import static android.app.ActivityManager.procStateToString;
20 import static android.content.pm.PackageManager.GET_SIGNATURES;
21 
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.annotation.RequiresPermission;
26 import android.annotation.SystemApi;
27 import android.annotation.SystemService;
28 import android.annotation.TestApi;
29 import android.app.ActivityManager;
30 import android.app.ActivityManager.ProcessCapability;
31 import android.compat.annotation.UnsupportedAppUsage;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.pm.PackageManager;
35 import android.content.pm.PackageManager.NameNotFoundException;
36 import android.content.pm.Signature;
37 import android.net.wifi.WifiConfiguration;
38 import android.net.wifi.WifiInfo;
39 import android.os.Build;
40 import android.os.Process;
41 import android.os.RemoteException;
42 import android.telephony.Annotation;
43 import android.telephony.SubscriptionPlan;
44 import android.util.DebugUtils;
45 import android.util.Pair;
46 import android.util.Range;
47 
48 import com.android.internal.util.function.pooled.PooledLambda;
49 
50 import com.google.android.collect.Sets;
51 
52 import java.lang.annotation.Retention;
53 import java.lang.annotation.RetentionPolicy;
54 import java.time.ZonedDateTime;
55 import java.util.HashSet;
56 import java.util.Iterator;
57 import java.util.Map;
58 import java.util.concurrent.ConcurrentHashMap;
59 import java.util.concurrent.Executor;
60 
61 /**
62  * Manager for creating and modifying network policy rules.
63  *
64  * @hide
65  */
66 @TestApi
67 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
68 @SystemService(Context.NETWORK_POLICY_SERVICE)
69 public class NetworkPolicyManager {
70 
71     /* POLICY_* are masks and can be ORed, although currently they are not.*/
72     /**
73      * No specific network policy, use system default.
74      * @hide
75      */
76     public static final int POLICY_NONE = 0x0;
77     /**
78      * Reject network usage on metered networks when application in background.
79      * @hide
80      */
81     public static final int POLICY_REJECT_METERED_BACKGROUND = 0x1;
82     /**
83      * Allow metered network use in the background even when in data usage save mode.
84      * @hide
85      */
86     public static final int POLICY_ALLOW_METERED_BACKGROUND = 0x4;
87 
88     /*
89      * Rules defining whether an uid has access to a network given its type (metered / non-metered).
90      *
91      * These rules are bits and can be used in bitmask operations; in particular:
92      * - rule & RULE_MASK_METERED: returns the metered-networks status.
93      * - rule & RULE_MASK_ALL: returns the all-networks status.
94      *
95      * The RULE_xxx_ALL rules applies to all networks (metered or non-metered), but on
96      * metered networks, the RULE_xxx_METERED rules should be checked first. For example,
97      * if the device is on Battery Saver Mode and Data Saver Mode simulatenously, and a uid
98      * is allowlisted for the former but not the latter, its status would be
99      * RULE_REJECT_METERED | RULE_ALLOW_ALL, meaning it could have access to non-metered
100      * networks but not to metered networks.
101      *
102      * See network-policy-restrictions.md for more info.
103      */
104 
105     /**
106      * No specific rule was set
107      * @hide
108      */
109     public static final int RULE_NONE = 0;
110     /**
111      * Allow traffic on metered networks.
112      * @hide
113      */
114     public static final int RULE_ALLOW_METERED = 1 << 0;
115     /**
116      * Temporarily allow traffic on metered networks because app is on foreground.
117      * @hide
118      */
119     public static final int RULE_TEMPORARY_ALLOW_METERED = 1 << 1;
120     /**
121      * Reject traffic on metered networks.
122      * @hide
123      */
124     public static final int RULE_REJECT_METERED = 1 << 2;
125     /**
126      * Network traffic should be allowed on all networks (metered or non-metered), although
127      * metered-network restrictions could still apply.
128      * @hide
129      */
130     public static final int RULE_ALLOW_ALL = 1 << 5;
131     /**
132      * Reject traffic on all networks.
133      * @hide
134      */
135     public static final int RULE_REJECT_ALL = 1 << 6;
136     /**
137      * Reject traffic on all networks for restricted networking mode.
138      * @hide
139      */
140     public static final int RULE_REJECT_RESTRICTED_MODE = 1 << 10;
141 
142     /**
143      * Mask used to get the {@code RULE_xxx_METERED} rules
144      * @hide
145      */
146     public static final int MASK_METERED_NETWORKS = 0b000000001111;
147     /**
148      * Mask used to get the {@code RULE_xxx_ALL} rules
149      * @hide
150      */
151     public static final int MASK_ALL_NETWORKS     = 0b000011110000;
152     /**
153      * Mask used to get the {@code RULE_xxx_RESTRICTED_MODE} rules
154      * @hide
155      */
156     public static final int MASK_RESTRICTED_MODE_NETWORKS     = 0b111100000000;
157 
158     /** @hide */
159     public static final int FIREWALL_RULE_DEFAULT = 0;
160     /** @hide */
161     public static final String FIREWALL_CHAIN_NAME_NONE = "none";
162     /** @hide */
163     public static final String FIREWALL_CHAIN_NAME_DOZABLE = "dozable";
164     /** @hide */
165     public static final String FIREWALL_CHAIN_NAME_STANDBY = "standby";
166     /** @hide */
167     public static final String FIREWALL_CHAIN_NAME_POWERSAVE = "powersave";
168     /** @hide */
169     public static final String FIREWALL_CHAIN_NAME_RESTRICTED = "restricted";
170     /** @hide */
171     public static final String FIREWALL_CHAIN_NAME_LOW_POWER_STANDBY = "low_power_standby";
172 
173     private static final boolean ALLOW_PLATFORM_APP_POLICY = true;
174 
175     /** @hide */
176     public static final int FOREGROUND_THRESHOLD_STATE =
177             ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
178 
179     /** @hide */
180     public static final int TOP_THRESHOLD_STATE = ActivityManager.PROCESS_STATE_BOUND_TOP;
181 
182     /**
183      * {@link Intent} extra that indicates which {@link NetworkTemplate} rule it
184      * applies to.
185      * @hide
186      */
187     public static final String EXTRA_NETWORK_TEMPLATE = "android.net.NETWORK_TEMPLATE";
188 
189     /**
190      * Mask used to check if an override value is marked as unmetered.
191      * @hide
192      */
193     public static final int SUBSCRIPTION_OVERRIDE_UNMETERED = 1 << 0;
194 
195     /**
196      * Mask used to check if an override value is marked as congested.
197      * @hide
198      */
199     public static final int SUBSCRIPTION_OVERRIDE_CONGESTED = 1 << 1;
200 
201     /**
202      * @hide
203      */
204     @Retention(RetentionPolicy.SOURCE)
205     @IntDef(flag = true, prefix = { "SUBSCRIPTION_OVERRIDE_" }, value = {
206         SUBSCRIPTION_OVERRIDE_UNMETERED,
207         SUBSCRIPTION_OVERRIDE_CONGESTED
208     })
209     public @interface SubscriptionOverrideMask {}
210 
211     /**
212      * Flag to indicate that app is not exempt from any network restrictions.
213      *
214      * @hide
215      */
216     public static final int ALLOWED_REASON_NONE = 0;
217     /**
218      * Flag to indicate that app is exempt from certain network restrictions because of it being a
219      * system component.
220      *
221      * @hide
222      */
223     public static final int ALLOWED_REASON_SYSTEM = 1 << 0;
224     /**
225      * Flag to indicate that app is exempt from certain network restrictions because of it being
226      * in the foreground.
227      *
228      * @hide
229      */
230     public static final int ALLOWED_REASON_FOREGROUND = 1 << 1;
231     /**
232      * Flag to indicate that app is exempt from certain network restrictions because of it being
233      * in the {@code allow-in-power-save} list.
234      *
235      * @hide
236      */
237     public static final int ALLOWED_REASON_POWER_SAVE_ALLOWLIST = 1 << 2;
238     /**
239      * Flag to indicate that app is exempt from certain network restrictions because of it being
240      * in the {@code allow-in-power-save-except-idle} list.
241      *
242      * @hide
243      */
244     public static final int ALLOWED_REASON_POWER_SAVE_EXCEPT_IDLE_ALLOWLIST = 1 << 3;
245     /**
246      * Flag to indicate that app is exempt from certain network restrictions because of it holding
247      * certain privileged permissions.
248      *
249      * @hide
250      */
251     public static final int ALLOWED_REASON_RESTRICTED_MODE_PERMISSIONS = 1 << 4;
252     /**
253      * Flag to indicate that app is exempt from certain network restrictions because of it being
254      * in the bound top or top procstate.
255      *
256      * @hide
257      */
258     public static final int ALLOWED_REASON_TOP = 1 << 5;
259     /**
260      * Flag to indicate that app is exempt from low power standby restrictions because of it being
261      * allowlisted.
262      *
263      * @hide
264      */
265     public static final int ALLOWED_REASON_LOW_POWER_STANDBY_ALLOWLIST = 1 << 6;
266     /**
267      * Flag to indicate that app is exempt from certain metered network restrictions because user
268      * explicitly exempted it.
269      *
270      * @hide
271      */
272     public static final int ALLOWED_METERED_REASON_USER_EXEMPTED = 1 << 16;
273     /**
274      * Flag to indicate that app is exempt from certain metered network restrictions because of it
275      * being a system component.
276      *
277      * @hide
278      */
279     public static final int ALLOWED_METERED_REASON_SYSTEM = 1 << 17;
280     /**
281      * Flag to indicate that app is exempt from certain metered network restrictions because of it
282      * being in the foreground.
283      *
284      * @hide
285      */
286     public static final int ALLOWED_METERED_REASON_FOREGROUND = 1 << 18;
287 
288     /** @hide */
289     public static final int ALLOWED_METERED_REASON_MASK = 0xffff0000;
290 
291     private final Context mContext;
292     @UnsupportedAppUsage
293     private INetworkPolicyManager mService;
294 
295     private final Map<SubscriptionCallback, SubscriptionCallbackProxy>
296             mSubscriptionCallbackMap = new ConcurrentHashMap<>();
297     private final Map<NetworkPolicyCallback, NetworkPolicyCallbackProxy>
298             mNetworkPolicyCallbackMap = new ConcurrentHashMap<>();
299 
300     /** @hide */
NetworkPolicyManager(Context context, INetworkPolicyManager service)301     public NetworkPolicyManager(Context context, INetworkPolicyManager service) {
302         if (service == null) {
303             throw new IllegalArgumentException("missing INetworkPolicyManager");
304         }
305         mContext = context;
306         mService = service;
307     }
308 
309     /** @hide */
310     @UnsupportedAppUsage
from(Context context)311     public static NetworkPolicyManager from(Context context) {
312         return (NetworkPolicyManager) context.getSystemService(Context.NETWORK_POLICY_SERVICE);
313     }
314 
315     /**
316      * Set policy flags for specific UID.
317      *
318      * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
319      *     although it is not validated.
320      * @hide
321      */
322     @UnsupportedAppUsage
setUidPolicy(int uid, int policy)323     public void setUidPolicy(int uid, int policy) {
324         try {
325             mService.setUidPolicy(uid, policy);
326         } catch (RemoteException e) {
327             throw e.rethrowFromSystemServer();
328         }
329     }
330 
331     /**
332      * Add policy flags for specific UID.
333      *
334      * <p>The given policy bits will be set for the uid.
335      *
336      * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
337      *     although it is not validated.
338      * @hide
339      */
addUidPolicy(int uid, int policy)340     public void addUidPolicy(int uid, int policy) {
341         try {
342             mService.addUidPolicy(uid, policy);
343         } catch (RemoteException e) {
344             throw e.rethrowFromSystemServer();
345         }
346     }
347 
348     /**
349      * Clear/remove policy flags for specific UID.
350      *
351      * <p>The given policy bits will be set for the uid.
352      *
353      * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
354      *     although it is not validated.
355      * @hide
356      */
removeUidPolicy(int uid, int policy)357     public void removeUidPolicy(int uid, int policy) {
358         try {
359             mService.removeUidPolicy(uid, policy);
360         } catch (RemoteException e) {
361             throw e.rethrowFromSystemServer();
362         }
363     }
364 
365     /** @hide */
366     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getUidPolicy(int uid)367     public int getUidPolicy(int uid) {
368         try {
369             return mService.getUidPolicy(uid);
370         } catch (RemoteException e) {
371             throw e.rethrowFromSystemServer();
372         }
373     }
374 
375     /** @hide */
376     @UnsupportedAppUsage
getUidsWithPolicy(int policy)377     public int[] getUidsWithPolicy(int policy) {
378         try {
379             return mService.getUidsWithPolicy(policy);
380         } catch (RemoteException e) {
381             throw e.rethrowFromSystemServer();
382         }
383     }
384 
385     /** @hide */
386     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
registerListener(INetworkPolicyListener listener)387     public void registerListener(INetworkPolicyListener listener) {
388         try {
389             mService.registerListener(listener);
390         } catch (RemoteException e) {
391             throw e.rethrowFromSystemServer();
392         }
393     }
394 
395     /** @hide */
396     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
unregisterListener(INetworkPolicyListener listener)397     public void unregisterListener(INetworkPolicyListener listener) {
398         try {
399             mService.unregisterListener(listener);
400         } catch (RemoteException e) {
401             throw e.rethrowFromSystemServer();
402         }
403     }
404 
405     /** @hide */
406     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
registerSubscriptionCallback(@onNull SubscriptionCallback callback)407     public void registerSubscriptionCallback(@NonNull SubscriptionCallback callback) {
408         if (callback == null) {
409             throw new NullPointerException("Callback cannot be null.");
410         }
411 
412         final SubscriptionCallbackProxy callbackProxy = new SubscriptionCallbackProxy(callback);
413         if (null != mSubscriptionCallbackMap.putIfAbsent(callback, callbackProxy)) {
414             throw new IllegalArgumentException("Callback is already registered.");
415         }
416         registerListener(callbackProxy);
417     }
418 
419     /** @hide */
420     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
unregisterSubscriptionCallback(@onNull SubscriptionCallback callback)421     public void unregisterSubscriptionCallback(@NonNull SubscriptionCallback callback) {
422         if (callback == null) {
423             throw new NullPointerException("Callback cannot be null.");
424         }
425 
426         final SubscriptionCallbackProxy callbackProxy = mSubscriptionCallbackMap.remove(callback);
427         if (callbackProxy == null) return;
428 
429         unregisterListener(callbackProxy);
430     }
431 
432     /** @hide */
setNetworkPolicies(NetworkPolicy[] policies)433     public void setNetworkPolicies(NetworkPolicy[] policies) {
434         try {
435             mService.setNetworkPolicies(policies);
436         } catch (RemoteException e) {
437             throw e.rethrowFromSystemServer();
438         }
439     }
440 
441     /** @hide */
442     @UnsupportedAppUsage
getNetworkPolicies()443     public NetworkPolicy[] getNetworkPolicies() {
444         try {
445             return mService.getNetworkPolicies(mContext.getOpPackageName());
446         } catch (RemoteException e) {
447             throw e.rethrowFromSystemServer();
448         }
449     }
450 
451     /** @hide */
452     @TestApi
453     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setRestrictBackground(boolean restrictBackground)454     public void setRestrictBackground(boolean restrictBackground) {
455         try {
456             mService.setRestrictBackground(restrictBackground);
457         } catch (RemoteException e) {
458             throw e.rethrowFromSystemServer();
459         }
460     }
461 
462     /** @hide */
463     @TestApi
464     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getRestrictBackground()465     public boolean getRestrictBackground() {
466         try {
467             return mService.getRestrictBackground();
468         } catch (RemoteException e) {
469             throw e.rethrowFromSystemServer();
470         }
471     }
472 
473     /**
474      * Determines if an UID is subject to metered network restrictions while running in background.
475      *
476      * @param uid The UID whose status needs to be checked.
477      * @return {@link ConnectivityManager#RESTRICT_BACKGROUND_STATUS_DISABLED},
478      *         {@link ConnectivityManager##RESTRICT_BACKGROUND_STATUS_ENABLED},
479      *         or {@link ConnectivityManager##RESTRICT_BACKGROUND_STATUS_WHITELISTED} to denote
480      *         the current status of the UID.
481      * @hide
482      */
483     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
484     @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
getRestrictBackgroundStatus(int uid)485     public int getRestrictBackgroundStatus(int uid) {
486         try {
487             return mService.getRestrictBackgroundStatus(uid);
488         } catch (RemoteException e) {
489             throw e.rethrowFromSystemServer();
490         }
491     }
492 
493     /**
494      * Override connections to be temporarily marked as either unmetered or congested,
495      * along with automatic timeouts if desired.
496      *
497      * @param subId the subscriber ID this override applies to.
498      * @param overrideMask the bitmask that specifies which of the overrides is being
499      *            set or cleared.
500      * @param overrideValue the override values to set or clear.
501      * @param networkTypes the network types this override applies to. If no
502      *            network types are specified, override values will be ignored.
503      *            {@see TelephonyManager#getAllNetworkTypes()}
504      * @param expirationDurationMillis the duration after which the requested override
505      *            will be automatically cleared, or {@code 0} to leave in the
506      *            requested state until explicitly cleared, or the next reboot,
507      *            whichever happens first
508      * @param callingPackage the name of the package making the call.
509      * @hide
510      */
setSubscriptionOverride(int subId, @SubscriptionOverrideMask int overrideMask, @SubscriptionOverrideMask int overrideValue, @NonNull @Annotation.NetworkType int[] networkTypes, long expirationDurationMillis, @NonNull String callingPackage)511     public void setSubscriptionOverride(int subId, @SubscriptionOverrideMask int overrideMask,
512             @SubscriptionOverrideMask int overrideValue,
513             @NonNull @Annotation.NetworkType int[] networkTypes, long expirationDurationMillis,
514             @NonNull String callingPackage) {
515         try {
516             mService.setSubscriptionOverride(subId, overrideMask, overrideValue, networkTypes,
517                     expirationDurationMillis, callingPackage);
518         } catch (RemoteException e) {
519             throw e.rethrowFromSystemServer();
520         }
521     }
522 
523     /**
524      * Set the subscription plans for a specific subscriber.
525      *
526      * @param subId the subscriber this relationship applies to.
527      * @param plans the list of plans.
528      * @param expirationDurationMillis the duration after which the subscription plans
529      *            will be automatically cleared, or {@code 0} to leave the plans until
530      *            explicitly cleared, or the next reboot, whichever happens first
531      * @param callingPackage the name of the package making the call
532      * @hide
533      */
setSubscriptionPlans(int subId, @NonNull SubscriptionPlan[] plans, long expirationDurationMillis, @NonNull String callingPackage)534     public void setSubscriptionPlans(int subId, @NonNull SubscriptionPlan[] plans,
535             long expirationDurationMillis, @NonNull String callingPackage) {
536         try {
537             mService.setSubscriptionPlans(subId, plans, expirationDurationMillis, callingPackage);
538         } catch (RemoteException e) {
539             throw e.rethrowFromSystemServer();
540         }
541     }
542 
543     /**
544      * Get subscription plans for the given subscription id.
545      *
546      * @param subId the subscriber to get the subscription plans for.
547      * @param callingPackage the name of the package making the call.
548      * @return the active {@link SubscriptionPlan}s for the given subscription id, or
549      *         {@code null} if not found.
550      * @hide
551      */
552     @Nullable
getSubscriptionPlans(int subId, @NonNull String callingPackage)553     public SubscriptionPlan[] getSubscriptionPlans(int subId, @NonNull String callingPackage) {
554         try {
555             return mService.getSubscriptionPlans(subId, callingPackage);
556         } catch (RemoteException e) {
557             throw e.rethrowFromSystemServer();
558         }
559     }
560 
561     /**
562      * Get subscription plan for the given networkTemplate.
563      *
564      * @param template the networkTemplate to get the subscription plan for.
565      * @return the active {@link SubscriptionPlan}s for the given template, or
566      *         {@code null} if not found.
567      * @hide
568      */
569     @Nullable
570     @RequiresPermission(anyOf = {
571             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
572             android.Manifest.permission.NETWORK_STACK})
573     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getSubscriptionPlan(@onNull NetworkTemplate template)574     public SubscriptionPlan getSubscriptionPlan(@NonNull NetworkTemplate template) {
575         try {
576             return mService.getSubscriptionPlan(template);
577         } catch (RemoteException e) {
578             throw e.rethrowFromSystemServer();
579         }
580     }
581 
582     /**
583      * Notifies that the specified {@link NetworkStatsProvider} has reached its warning threshold
584      * which was set through {@link NetworkStatsProvider#onSetWarningAndLimit(String, long, long)}.
585      *
586      * @hide
587      */
588     @RequiresPermission(anyOf = {
589             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
590             android.Manifest.permission.NETWORK_STACK})
591     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
notifyStatsProviderWarningReached()592     public void notifyStatsProviderWarningReached() {
593         try {
594             mService.notifyStatsProviderWarningOrLimitReached();
595         } catch (RemoteException e) {
596             throw e.rethrowFromSystemServer();
597         }
598     }
599 
600     /**
601      * Notifies that the specified {@link NetworkStatsProvider} has reached its quota
602      * which was set through {@link NetworkStatsProvider#onSetLimit(String, long)} or
603      * {@link NetworkStatsProvider#onSetWarningAndLimit(String, long, long)}.
604      *
605      * @hide
606      */
607     @RequiresPermission(anyOf = {
608             NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
609             android.Manifest.permission.NETWORK_STACK})
610     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
notifyStatsProviderLimitReached()611     public void notifyStatsProviderLimitReached() {
612         try {
613             mService.notifyStatsProviderWarningOrLimitReached();
614         } catch (RemoteException e) {
615             throw e.rethrowFromSystemServer();
616         }
617     }
618 
619     /**
620      * Resets network policy settings back to factory defaults.
621      *
622      * @hide
623      */
factoryReset(String subscriber)624     public void factoryReset(String subscriber) {
625         try {
626             mService.factoryReset(subscriber);
627         } catch (RemoteException e) {
628             throw e.rethrowFromSystemServer();
629         }
630     }
631 
632     /**
633      * Check that networking is blocked for the given uid.
634      *
635      * @param uid The target uid.
636      * @param meteredNetwork True if the network is metered.
637      * @return true if networking is blocked for the given uid according to current networking
638      *         policies.
639      */
640     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
isUidNetworkingBlocked(int uid, boolean meteredNetwork)641     public boolean isUidNetworkingBlocked(int uid, boolean meteredNetwork) {
642         try {
643             return mService.isUidNetworkingBlocked(uid, meteredNetwork);
644         } catch (RemoteException e) {
645             throw e.rethrowFromSystemServer();
646         }
647     }
648 
649     /**
650      * Check that the given uid is restricted from doing networking on metered networks.
651      *
652      * @param uid The target uid.
653      * @return true if the given uid is restricted from doing networking on metered networks.
654      */
655     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
isUidRestrictedOnMeteredNetworks(int uid)656     public boolean isUidRestrictedOnMeteredNetworks(int uid) {
657         try {
658             return mService.isUidRestrictedOnMeteredNetworks(uid);
659         } catch (RemoteException e) {
660             throw e.rethrowFromSystemServer();
661         }
662     }
663 
664     /**
665      * Gets a hint on whether it is desirable to use multipath data transfer on the given network.
666      *
667      * @return One of the ConnectivityManager.MULTIPATH_PREFERENCE_* constants.
668      *
669      * @hide
670      */
671     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
672     @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
getMultipathPreference(@onNull Network network)673     public int getMultipathPreference(@NonNull Network network) {
674         try {
675             return mService.getMultipathPreference(network);
676         } catch (RemoteException e) {
677             throw e.rethrowFromSystemServer();
678         }
679     }
680 
681     /** {@hide} */
682     @Deprecated
cycleIterator(NetworkPolicy policy)683     public static Iterator<Pair<ZonedDateTime, ZonedDateTime>> cycleIterator(NetworkPolicy policy) {
684         final Iterator<Range<ZonedDateTime>> it = policy.cycleIterator();
685         return new Iterator<Pair<ZonedDateTime, ZonedDateTime>>() {
686             @Override
687             public boolean hasNext() {
688                 return it.hasNext();
689             }
690 
691             @Override
692             public Pair<ZonedDateTime, ZonedDateTime> next() {
693                 if (hasNext()) {
694                     final Range<ZonedDateTime> r = it.next();
695                     return Pair.create(r.getLower(), r.getUpper());
696                 } else {
697                     return Pair.create(null, null);
698                 }
699             }
700         };
701     }
702 
703     /**
704      * Check if given UID can have a {@link #setUidPolicy(int, int)} defined,
705      * usually to protect critical system services.
706      * @hide
707      */
708     @Deprecated
709     public static boolean isUidValidForPolicy(Context context, int uid) {
710         // first, quick-reject non-applications
711         if (!Process.isApplicationUid(uid)) {
712             return false;
713         }
714 
715         if (!ALLOW_PLATFORM_APP_POLICY) {
716             final PackageManager pm = context.getPackageManager();
717             final HashSet<Signature> systemSignature;
718             try {
719                 systemSignature = Sets.newHashSet(
720                         pm.getPackageInfo("android", GET_SIGNATURES).signatures);
721             } catch (NameNotFoundException e) {
722                 throw new RuntimeException("problem finding system signature", e);
723             }
724 
725             try {
726                 // reject apps signed with platform cert
727                 for (String packageName : pm.getPackagesForUid(uid)) {
728                     final HashSet<Signature> packageSignature = Sets.newHashSet(
729                             pm.getPackageInfo(packageName, GET_SIGNATURES).signatures);
730                     if (packageSignature.containsAll(systemSignature)) {
731                         return false;
732                     }
733                 }
734             } catch (NameNotFoundException e) {
735             }
736         }
737 
738         // nothing found above; we can apply policy to UID
739         return true;
740     }
741 
742     /**
743      * @hide
744      */
745     public static String uidRulesToString(int uidRules) {
746         final StringBuilder string = new StringBuilder().append(uidRules).append(" (");
747         if (uidRules == RULE_NONE) {
748             string.append("NONE");
749         } else {
750             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class, "RULE_", uidRules));
751         }
752         string.append(")");
753         return string.toString();
754     }
755 
756     /**
757      * @hide
758      */
759     public static String uidPoliciesToString(int uidPolicies) {
760         final StringBuilder string = new StringBuilder().append(uidPolicies).append(" (");
761         if (uidPolicies == POLICY_NONE) {
762             string.append("NONE");
763         } else {
764             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class,
765                     "POLICY_", uidPolicies));
766         }
767         string.append(")");
768         return string.toString();
769     }
770 
771     /**
772      * Returns true if {@param procState} is considered foreground and as such will be allowed
773      * to access network when the device is idle or in battery saver mode. Otherwise, false.
774      * @hide
775      */
776     public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(@Nullable UidState uidState) {
777         if (uidState == null) {
778             return false;
779         }
780         return isProcStateAllowedWhileIdleOrPowerSaveMode(uidState.procState, uidState.capability);
781     }
782 
783     /** @hide */
784     public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(
785             int procState, @ProcessCapability int capability) {
786         return procState <= FOREGROUND_THRESHOLD_STATE
787                 || (capability & ActivityManager.PROCESS_CAPABILITY_NETWORK) != 0;
788     }
789 
790     /** @hide */
791     public static boolean isProcStateAllowedWhileInLowPowerStandby(@Nullable UidState uidState) {
792         if (uidState == null) {
793             return false;
794         }
795         return uidState.procState <= TOP_THRESHOLD_STATE;
796     }
797 
798     /**
799      * Returns true if {@param procState} is considered foreground and as such will be allowed
800      * to access network when the device is in data saver mode. Otherwise, false.
801      * @hide
802      */
803     public static boolean isProcStateAllowedWhileOnRestrictBackground(@Nullable UidState uidState) {
804         if (uidState == null) {
805             return false;
806         }
807         return isProcStateAllowedWhileOnRestrictBackground(uidState.procState);
808     }
809 
810     /** @hide */
811     public static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
812         // Data saver and bg policy restrictions will only take procstate into account.
813         return procState <= FOREGROUND_THRESHOLD_STATE;
814     }
815 
816     /** @hide */
817     public static final class UidState {
818         public int uid;
819         public int procState;
820         public long procStateSeq;
821         public int capability;
822 
823         public UidState(int uid, int procState, long procStateSeq, int capability) {
824             this.uid = uid;
825             this.procState = procState;
826             this.procStateSeq = procStateSeq;
827             this.capability = capability;
828         }
829 
830         @Override
831         public String toString() {
832             final StringBuilder sb = new StringBuilder();
833             sb.append("{procState=");
834             sb.append(procStateToString(procState));
835             sb.append(",seq=");
836             sb.append(procStateSeq);
837             sb.append(",cap=");
838             ActivityManager.printCapabilitiesSummary(sb, capability);
839             sb.append("}");
840             return sb.toString();
841         }
842     }
843 
844     /** @hide */
845     @TestApi
846     @NonNull
847     public static String resolveNetworkId(@NonNull WifiConfiguration config) {
848         return WifiInfo.sanitizeSsid(config.isPasspoint()
849                 ? config.providerFriendlyName : config.SSID);
850     }
851 
852     /** @hide */
853     public static String resolveNetworkId(String ssid) {
854         return WifiInfo.sanitizeSsid(ssid);
855     }
856 
857     /**
858      * Returns the {@code string} representation of {@code blockedReasons} argument.
859      *
860      * @param blockedReasons Value indicating the reasons for why the network access of an UID is
861      *                       blocked.
862      * @hide
863      */
864     @NonNull
865     public static String blockedReasonsToString(int blockedReasons) {
866         return DebugUtils.flagsToString(ConnectivityManager.class, "BLOCKED_", blockedReasons);
867     }
868 
869     /** @hide */
870     @NonNull
871     public static String allowedReasonsToString(int allowedReasons) {
872         return DebugUtils.flagsToString(NetworkPolicyManager.class, "ALLOWED_", allowedReasons);
873     }
874 
875     /**
876      * Register a {@link NetworkPolicyCallback} to listen for changes to network blocked status
877      * of apps.
878      *
879      * Note that when a caller tries to register a new callback, it might replace a previously
880      * registered callback if it is considered equal to the new one, based on the
881      * {@link Object#equals(Object)} check.
882      *
883      * @param executor The {@link Executor} to run the callback on.
884      * @param callback The {@link NetworkPolicyCallback} to be registered.
885      * @hide
886      */
887     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
888     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
889     public void registerNetworkPolicyCallback(@Nullable Executor executor,
890             @NonNull NetworkPolicyCallback callback) {
891         if (callback == null) {
892             throw new NullPointerException("Callback cannot be null.");
893         }
894 
895         final NetworkPolicyCallbackProxy callbackProxy = new NetworkPolicyCallbackProxy(
896                 executor, callback);
897         registerListener(callbackProxy);
898         mNetworkPolicyCallbackMap.put(callback, callbackProxy);
899     }
900 
901     /**
902      * Unregister a previously registered {@link NetworkPolicyCallback}.
903      *
904      * @param callback The {@link NetworkPolicyCallback} to be unregistered.
905      * @hide
906      */
907     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
908     @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
909     public void unregisterNetworkPolicyCallback(@NonNull NetworkPolicyCallback callback) {
910         if (callback == null) {
911             throw new NullPointerException("Callback cannot be null.");
912         }
913 
914         final NetworkPolicyCallbackProxy callbackProxy = mNetworkPolicyCallbackMap.remove(callback);
915         if (callbackProxy == null) return;
916         unregisterListener(callbackProxy);
917     }
918 
919     /**
920      * Interface for the callback to listen for changes to network blocked status of apps.
921      *
922      * @hide
923      */
924     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
925     public interface NetworkPolicyCallback {
926         /**
927          * Called when the reason for why the network access of an UID is blocked changes.
928          *
929          * @param uid The UID for which the blocked status changed.
930          * @param blockedReasons Value indicating the reasons for why the network access of an
931          *                       UID is blocked.
932          * @hide
933          */
934         @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
935         default void onUidBlockedReasonChanged(int uid, int blockedReasons) {}
936     }
937 
938     /** @hide */
939     public static class NetworkPolicyCallbackProxy extends Listener {
940         private final Executor mExecutor;
941         private final NetworkPolicyCallback mCallback;
942 
943         NetworkPolicyCallbackProxy(@Nullable Executor executor,
944                 @NonNull NetworkPolicyCallback callback) {
945             mExecutor = executor;
946             mCallback = callback;
947         }
948 
949         @Override
950         public void onBlockedReasonChanged(int uid, int oldBlockedReasons, int newBlockedReasons) {
951             if (oldBlockedReasons != newBlockedReasons) {
952                 dispatchOnUidBlockedReasonChanged(mExecutor, mCallback, uid, newBlockedReasons);
953             }
954         }
955     }
956 
957     private static void dispatchOnUidBlockedReasonChanged(@Nullable Executor executor,
958             @NonNull NetworkPolicyCallback callback, int uid, int blockedReasons) {
959         if (executor == null) {
960             callback.onUidBlockedReasonChanged(uid, blockedReasons);
961         } else {
962             executor.execute(PooledLambda.obtainRunnable(
963                     NetworkPolicyCallback::onUidBlockedReasonChanged,
964                     callback, uid, blockedReasons).recycleOnUse());
965         }
966     }
967 
968     /** @hide */
969     public static class SubscriptionCallback {
970         /**
971          * Notify clients of a new override about a given subscription.
972          *
973          * @param subId the subscriber this override applies to.
974          * @param overrideMask a bitmask that specifies which of the overrides is set.
975          * @param overrideValue a bitmask that specifies the override values.
976          * @param networkTypes the network types this override applies to.
977          */
978         public void onSubscriptionOverride(int subId, @SubscriptionOverrideMask int overrideMask,
979                 @SubscriptionOverrideMask int overrideValue, int[] networkTypes) {}
980 
981         /**
982          * Notify of subscription plans change about a given subscription.
983          *
984          * @param subId the subscriber id that got subscription plans change.
985          * @param plans the list of subscription plans.
986          */
987         public void onSubscriptionPlansChanged(int subId, @NonNull SubscriptionPlan[] plans) {}
988     }
989 
990     /**
991      * SubscriptionCallback proxy for SubscriptionCallback object.
992      * @hide
993      */
994     public class SubscriptionCallbackProxy extends Listener {
995         private final SubscriptionCallback mCallback;
996 
997         SubscriptionCallbackProxy(SubscriptionCallback callback) {
998             mCallback = callback;
999         }
1000 
1001         @Override
1002         public void onSubscriptionOverride(int subId, @SubscriptionOverrideMask int overrideMask,
1003                 @SubscriptionOverrideMask int overrideValue, int[] networkTypes) {
1004             mCallback.onSubscriptionOverride(subId, overrideMask, overrideValue, networkTypes);
1005         }
1006 
1007         @Override
1008         public void onSubscriptionPlansChanged(int subId, SubscriptionPlan[] plans) {
1009             mCallback.onSubscriptionPlansChanged(subId, plans);
1010         }
1011     }
1012 
1013     /** {@hide} */
1014     public static class Listener extends INetworkPolicyListener.Stub {
1015         @Override public void onUidRulesChanged(int uid, int uidRules) { }
1016         @Override public void onMeteredIfacesChanged(String[] meteredIfaces) { }
1017         @Override public void onRestrictBackgroundChanged(boolean restrictBackground) { }
1018         @Override public void onUidPoliciesChanged(int uid, int uidPolicies) { }
1019         @Override public void onSubscriptionOverride(int subId, int overrideMask,
1020                 int overrideValue, int[] networkTypes) { }
1021         @Override public void onSubscriptionPlansChanged(int subId, SubscriptionPlan[] plans) { }
1022         @Override public void onBlockedReasonChanged(int uid,
1023                 int oldBlockedReasons, int newBlockedReasons) { }
1024     }
1025 }
1026