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