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