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