blob: 327b685fba9b9c4eb8d97be03c8b81f242319015 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
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
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
paulhu59148b72019-08-12 16:25:11 +080023import static android.Manifest.permission.NETWORK_SETTINGS;
24import static android.Manifest.permission.NETWORK_STACK;
25import static android.Manifest.permission.OBSERVE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070026import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070027import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070028import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070029import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070031import static android.content.Intent.ACTION_USER_ADDED;
32import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070033import static android.content.Intent.EXTRA_UID;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070034import static android.content.pm.PackageManager.MATCH_ANY_USER;
35import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
36import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
37import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
38import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
paulhu59148b72019-08-12 16:25:11 +080039import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Erik Klinef851d6d2015-04-20 16:03:48 +090040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080041import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
42import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
43import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060044import static android.net.ConnectivityManager.TYPE_MOBILE;
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +090045import static android.net.INetd.FIREWALL_CHAIN_DOZABLE;
46import static android.net.INetd.FIREWALL_CHAIN_POWERSAVE;
47import static android.net.INetd.FIREWALL_CHAIN_STANDBY;
48import static android.net.INetd.FIREWALL_RULE_ALLOW;
49import static android.net.INetd.FIREWALL_RULE_DENY;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060050import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090051import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey9252b342018-01-19 07:58:35 +090052import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070053import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070054import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070055import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070056import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeydc988062015-09-14 10:09:47 -070057import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060058import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
59import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070060import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070061import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070062import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070063import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070064import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070065import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070066import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070067import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070068import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080069import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
70import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060071import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070072import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070073import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070074import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070075import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070076import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080077import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey00072392018-04-12 14:26:32 -060078import static android.os.Trace.TRACE_TAG_NETWORK;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060079import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
80import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
81import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
82import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
83import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
84import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070085import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070086import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060087import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey0a5570d2018-04-10 12:38:29 -060088import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_NOTIFICATION_BOOL;
89import static android.telephony.CarrierConfigManager.KEY_DATA_RAPID_NOTIFICATION_BOOL;
90import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_NOTIFICATION_BOOL;
Jeff Sharkey9252b342018-01-19 07:58:35 +090091import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080092
Jeff Sharkey854b2b12012-04-13 16:03:40 -070093import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070094import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070095import static com.android.internal.util.XmlUtils.readBooleanAttribute;
96import static com.android.internal.util.XmlUtils.readIntAttribute;
97import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060098import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070099import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
100import static com.android.internal.util.XmlUtils.writeIntAttribute;
101import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600102import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -0700103import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700104import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
junyulai05986c62018-08-07 19:50:45 +0800106import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_SYSTEM;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700107import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
108import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
109import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
110import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
111import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600113
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800115import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700116import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700118import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700119import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900120import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700121import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700122import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800123import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700124import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700125import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700126import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700127import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700128import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700129import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700130import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700131import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700132import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700133import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600134import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700135import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.content.Intent;
137import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700138import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700139import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700140import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700141import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700142import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700143import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700144import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600145import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700146import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700147import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700148import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700149import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700150import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700151import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600152import android.net.Network;
153import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700154import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700155import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600156import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700157import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600158import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900159import android.net.NetworkSpecifier;
paulhu59148b72019-08-12 16:25:11 +0800160import android.net.NetworkStack;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700162import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700163import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900164import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600165import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700166import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700167import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700168import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700169import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.os.Environment;
171import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700172import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700173import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700174import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700175import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700176import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700177import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700178import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700179import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700180import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600181import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800182import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700183import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700184import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600185import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700186import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700187import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700188import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600189import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700190import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700191import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700192import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700193import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100194import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700195import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600196import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800197import android.telephony.SubscriptionManager;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600198import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600199import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700200import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400201import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700202import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700203import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700204import android.util.ArrayMap;
205import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700206import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900207import android.util.DataUnit;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600208import android.util.IntArray;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700209import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700210import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600211import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600212import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700213import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600214import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700215import android.util.SparseBooleanArray;
216import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900217import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700219
Jeff Sharkey497e4432011-06-14 17:27:29 -0700220import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700221import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800222import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400223import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500224import com.android.internal.notification.SystemNotificationChannels;
Heemin Seogb9820d42019-05-21 16:17:43 -0700225import com.android.internal.os.RoSystemProperties;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700226import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800227import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800228import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600229import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700231import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600232import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700233import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700234import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700235import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700236import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800237import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600238
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600239import libcore.io.IoUtils;
240
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242import org.xmlpull.v1.XmlSerializer;
243
244import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700245import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246import java.io.FileInputStream;
247import java.io.FileNotFoundException;
248import java.io.FileOutputStream;
249import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700250import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700251import java.lang.annotation.Retention;
252import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100253import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700254import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900255import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600256import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700257import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600258import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900259import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700260import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600261import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700262import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600263import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400264import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800265import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800266import java.util.concurrent.CountDownLatch;
267import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700269/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700270 * Service that maintains low-level network policy rules, using
271 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700272 * <p>
273 * Derives active rules by combining a given policy with other system status,
274 * and delivers to listeners, such as {@link ConnectivityManager}, for
275 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700276 *
277 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700278 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700279 * <ul>
280 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
281 * rules).
282 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
283 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700284 * </ul>
285 *
286 * <p>
287 * As such, methods that require synchronization have the following prefixes:
288 * <ul>
289 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
290 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000291 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
292 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700293 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700294 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700295public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700296 static final String TAG = NetworkPolicyLogger.TAG;
297 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
298 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700299
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900300 /**
301 * No opportunistic quota could be calculated from user data plan or data settings.
302 */
303 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
304
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700305 private static final int VERSION_INIT = 1;
306 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700307 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800308 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800309 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800310 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700311 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700312 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700313 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700314 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600315 private static final int VERSION_ADDED_CYCLE = 11;
316 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400319 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800320 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400321 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800322 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400323 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900324 @VisibleForTesting
325 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700326
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 private static final String TAG_POLICY_LIST = "policy-list";
328 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600329 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700331 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800332 private static final String TAG_WHITELIST = "whitelist";
333 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800334 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335
336 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700337 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700338 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
339 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700340 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600341 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
342 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
343 private static final String ATTR_CYCLE_START = "cycleStart";
344 private static final String ATTR_CYCLE_END = "cycleEnd";
345 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346 private static final String ATTR_WARNING_BYTES = "warningBytes";
347 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700348 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800349 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
350 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800351 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700352 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700354 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700355 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600356 private static final String ATTR_SUB_ID = "subId";
357 private static final String ATTR_TITLE = "title";
358 private static final String ATTR_SUMMARY = "summary";
359 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
360 private static final String ATTR_USAGE_BYTES = "usageBytes";
361 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600362 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700363
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800364 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800365 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800366 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800367 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700368 private static final String ACTION_SNOOZE_RAPID =
369 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700370
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800371 /**
372 * Indicates the maximum wait time for admin data to be available;
373 */
374 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
375
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600376 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
377 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
378 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
379 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
380
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700381 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700382 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800383 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800384 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700385 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700386 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
387 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700388 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700389 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900390 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800391 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700392 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700393
Makoto Onuki8e777332017-03-28 11:25:47 -0700394 private static final int UID_MSG_STATE_CHANGED = 100;
395 private static final int UID_MSG_GONE = 101;
396
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600397 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
398
Jeff Sharkey75279902011-05-24 18:39:45 -0700399 private final Context mContext;
400 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700401 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700402 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700403 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700404 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700405 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700406 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407
408 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700409 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700410 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800411 @GuardedBy("mUidRulesFirstLock")
412 private PowerSaveState mRestrictBackgroundPowerState;
413
414 // Store the status of restrict background before turning on battery saver.
415 // Used to restore mRestrictBackground when battery saver is turned off.
416 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700417
Sudheer Shanka543339f2017-07-28 15:18:07 -0700418 // Denotes the status of restrict background read from disk.
419 private boolean mLoadedRestrictBackground;
420
Felipe Lemef0823852016-06-08 13:43:08 -0700421 // See main javadoc for instructions on how to use these locks.
422 final Object mUidRulesFirstLock = new Object();
423 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700424
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700425 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
426 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700427
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
429 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
430 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800431 // Store whether user flipped restrict background in battery saver mode
432 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700433
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700434 private final boolean mSuppressDefaultPolicy;
435
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800436 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
437
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700438 private volatile boolean mNetworkManagerReady;
439
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700440 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600441 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700443
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600445 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600446 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600447 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600448 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600449 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600450
Jeff Sharkey9252b342018-01-19 07:58:35 +0900451 /** Map from subId to daily opportunistic quota. */
452 @GuardedBy("mNetworkPoliciesSecondLock")
453 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
454
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700455 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700456 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700457 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700459
Felipe Lemef0823852016-06-08 13:43:08 -0700460 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700461 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700462 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700463 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800465 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700466
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700467 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700468 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700469 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
470
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800471 // "Power save mode" is the concept used in the DeviceIdleController that includes various
472 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
473 // and "battery saver" are not equivalent.
474
Jeff Sharkey32566012014-12-02 18:30:14 -0800475 /**
476 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700477 * in power save mode, except device idle (doze) still applies.
478 * TODO: An int array might be sufficient
479 */
Felipe Lemef0823852016-06-08 13:43:08 -0700480 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700481 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
482
483 /**
484 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800485 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700486 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800487 */
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700489 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700490
Felipe Lemef0823852016-06-08 13:43:08 -0700491 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700492 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
493
Felipe Lemeb85a6372016-01-14 16:16:16 -0800494 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800495 * UIDs that have been white-listed temporarily to be able to have network access despite being
496 * idle. Other power saving restrictions still apply.
497 */
498 @GuardedBy("mUidRulesFirstLock")
499 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
500
501 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800502 * UIDs that have been initially white-listed by system to avoid restricted background.
503 */
Felipe Lemef0823852016-06-08 13:43:08 -0700504 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800505 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
506 new SparseBooleanArray();
507
508 /**
509 * UIDs that have been initially white-listed by system to avoid restricted background,
510 * but later revoked by user.
511 */
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800513 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
514 new SparseBooleanArray();
515
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700516 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700517 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800518 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700519 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700520 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800521 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700522
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700523 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700524 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400525 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700526
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700527 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700528 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800529 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700530
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600531 /** Map from network ID to last observed meteredness state */
532 @GuardedBy("mNetworkPoliciesSecondLock")
533 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900534 /** Map from network ID to last observed roaming state */
535 @GuardedBy("mNetworkPoliciesSecondLock")
536 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
537
Jeff Sharkey9252b342018-01-19 07:58:35 +0900538 /** Map from netId to subId as of last update */
539 @GuardedBy("mNetworkPoliciesSecondLock")
540 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
541
Jeff Sharkey146bb332018-04-18 15:42:57 -0600542 /** Map from subId to subscriberId as of last update */
543 @GuardedBy("mNetworkPoliciesSecondLock")
544 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
545 /** Set of all merged subscriberId as of last update */
546 @GuardedBy("mNetworkPoliciesSecondLock")
Malcolm Chen07fcb5b2019-07-02 22:29:35 -0700547 private List<String[]> mMergedSubscriberIds = new ArrayList<>();
Jeff Sharkey146bb332018-04-18 15:42:57 -0600548
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800549 /**
550 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
551 * userId to restricted uids which belong to that user.
552 */
553 @GuardedBy("mUidRulesFirstLock")
554 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
555
Jeff Sharkey32566012014-12-02 18:30:14 -0800556 private final RemoteCallbackList<INetworkPolicyListener>
557 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700558
Dianne Hackborn497175b2014-07-01 12:56:08 -0700559 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700560 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800561 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700562
563 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700564
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700565 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700566 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700567
Svet Ganov16a16892015-04-16 10:32:04 -0700568 private final AppOpsManager mAppOps;
569
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800570 private final IPackageManager mIPm;
571
Sudheer Shankae7361852017-03-07 11:51:46 -0800572 private ActivityManagerInternal mActivityManagerInternal;
573
Sudheer Shanka352dc572017-09-22 17:09:38 -0700574 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800575
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700576 // TODO: keep whitelist of system-critical services that should never have
577 // rules enforced, such as system, phone, and radio UIDs.
578
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700579 // TODO: migrate notifications to SystemUI
580
Makoto Onuki49392d32018-04-11 13:51:02 -0700581
582 interface Stats {
583 int UPDATE_NETWORK_ENABLED = 0;
584 int IS_UID_NETWORKING_BLOCKED = 1;
585
586 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
587 }
588
589 public final StatLogger mStatLogger = new StatLogger(new String[] {
590 "updateNetworkEnabledNL()",
591 "isUidNetworkingBlocked()",
592 });
593
Jeff Sharkey75279902011-05-24 18:39:45 -0700594 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700595 INetworkManagementService networkManagement) {
596 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
597 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598 }
599
Jeff Sharkey9911a282018-02-14 22:29:11 -0700600 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700601 return new File(Environment.getDataDirectory(), "system");
602 }
603
Jeff Sharkey9911a282018-02-14 22:29:11 -0700604 private static @NonNull Clock getDefaultClock() {
605 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
606 Clock.systemUTC());
607 }
608
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700609 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700610 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
611 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700612 mContext = checkNotNull(context, "missing context");
613 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700614 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700615 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700616 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700617 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700618 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700619 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700620 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700621
Amith Yamasani450a16b2013-09-18 16:28:50 -0700622 HandlerThread thread = new HandlerThread(TAG);
623 thread.start();
624 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700625
Makoto Onuki8e777332017-03-28 11:25:47 -0700626 // We create another thread for the UID events, which are more time-critical.
627 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
628 /*allowIo=*/ false);
629 mUidEventThread.start();
630 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
631
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700632 mSuppressDefaultPolicy = suppressDefaultPolicy;
633
Dianne Hackborne17b4452018-01-10 13:15:40 -0800634 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700635
636 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800637
Felipe Lemed17fda42016-04-29 11:12:45 -0700638 // Expose private service for system components to use.
639 LocalServices.addService(NetworkPolicyManagerInternal.class,
640 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700641 }
642
643 public void bindConnectivityManager(IConnectivityManager connManager) {
644 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700645 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700646
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700647 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700648 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700649 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700650 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
651 mPowerSaveWhitelistExceptIdleAppIds.clear();
652 if (whitelist != null) {
653 for (int uid : whitelist) {
654 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
655 }
656 }
657 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700658 mPowerSaveWhitelistAppIds.clear();
659 if (whitelist != null) {
660 for (int uid : whitelist) {
661 mPowerSaveWhitelistAppIds.put(uid, true);
662 }
663 }
664 } catch (RemoteException e) {
665 }
666 }
667
Felipe Lemea9505cc2016-02-26 10:28:41 -0800668 /**
669 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
670 * revoke the whitelist.
671 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700672 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800673 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700674 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700675 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800676 final List<UserInfo> users = mUserManager.getUsers();
677 final int numberUsers = users.size();
678
Felipe Lemea110eec2016-04-29 09:58:06 -0700679 boolean changed = false;
680 for (int i = 0; i < numberUsers; i++) {
681 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700682 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700683 }
684 return changed;
685 }
686
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700687 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700688 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700689 final SystemConfig sysConfig = SystemConfig.getInstance();
690 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800691 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
692 boolean changed = false;
693 for (int i = 0; i < allowDataUsage.size(); i++) {
694 final String pkg = allowDataUsage.valueAt(i);
695 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700696 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
697 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800698 final ApplicationInfo app;
699 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700700 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800701 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700702 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
703 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 continue;
705 }
706 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700707 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
708 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800709 continue;
710 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700711 final int uid = UserHandle.getUid(userId, app.uid);
712 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
713 if (LOGD)
714 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
715 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800716 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700717 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700718 if (LOGD)
719 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
720 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700721 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700722 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800723 }
724 }
725 return changed;
726 }
727
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800728 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700729 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800730 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800732 // Boost thread's priority during system server init
733 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 if (!isBandwidthControlEnabled()) {
735 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
736 return;
737 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700738
Felipe Leme873a83a2016-09-07 11:34:10 -0700739 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700740 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700741
Felipe Leme873a83a2016-09-07 11:34:10 -0700742 synchronized (mUidRulesFirstLock) {
743 synchronized (mNetworkPoliciesSecondLock) {
744 updatePowerSaveWhitelistUL();
745 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
746 mPowerManagerInternal.registerLowPowerModeObserver(
747 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800748 @Override
749 public int getServiceType() {
750 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700751 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800752
753 @Override
754 public void onLowPowerModeChanged(PowerSaveState result) {
755 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800756 if (LOGD) {
757 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
758 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800759 synchronized (mUidRulesFirstLock) {
760 if (mRestrictPower != enabled) {
761 mRestrictPower = enabled;
762 updateRulesForRestrictPowerUL();
763 }
764 }
765 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800766 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800767 mRestrictPower = mPowerManagerInternal.getLowPowerState(
768 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700769
770 mSystemReady = true;
771
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800772 waitForAdminData();
773
Felipe Leme873a83a2016-09-07 11:34:10 -0700774 // read policy from disk
775 readPolicyAL();
776
jackqdyulei29c82ab2017-03-10 14:09:16 -0800777 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700778 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800779 mRestrictBackgroundPowerState = mPowerManagerInternal
780 .getLowPowerState(ServiceType.DATA_SAVER);
781 final boolean localRestrictBackground =
782 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700783 if (localRestrictBackground && !mLoadedRestrictBackground) {
784 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800785 }
786 mPowerManagerInternal.registerLowPowerModeObserver(
787 new PowerManagerInternal.LowPowerModeListener() {
788 @Override
789 public int getServiceType() {
790 return ServiceType.DATA_SAVER;
791 }
792
793 @Override
794 public void onLowPowerModeChanged(PowerSaveState result) {
795 synchronized (mUidRulesFirstLock) {
796 updateRestrictBackgroundByLowPowerModeUL(result);
797 }
798 }
799 });
800
Felipe Leme873a83a2016-09-07 11:34:10 -0700801 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
802 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700803 }
Felipe Lemef0823852016-06-08 13:43:08 -0700804
Sudheer Shanka543339f2017-07-28 15:18:07 -0700805 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700806 updateRulesForGlobalChangeAL(false);
807 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700808 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800809 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700810
Sudheer Shankae7361852017-03-07 11:51:46 -0800811 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 try {
813 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000814 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700815 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700816 mNetworkManager.registerObserver(mAlertObserver);
817 } catch (RemoteException e) {
818 // ignored; both services live in system_server
819 }
820
821 // listen for changes to power save whitelist
822 final IntentFilter whitelistFilter = new IntentFilter(
823 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
824 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
825
Felipe Leme873a83a2016-09-07 11:34:10 -0700826 // watch for network interfaces to be claimed
827 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
paulhu59148b72019-08-12 16:25:11 +0800828 mContext.registerReceiver(mConnReceiver, connFilter, NETWORK_STACK, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700829
830 // listen for package changes to update policy
831 final IntentFilter packageFilter = new IntentFilter();
832 packageFilter.addAction(ACTION_PACKAGE_ADDED);
833 packageFilter.addDataScheme("package");
834 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
835
836 // listen for UID changes to update policy
837 mContext.registerReceiver(
838 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
839
840 // listen for user changes to update policy
841 final IntentFilter userFilter = new IntentFilter();
842 userFilter.addAction(ACTION_USER_ADDED);
843 userFilter.addAction(ACTION_USER_REMOVED);
844 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
845
846 // listen for stats update events
847 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
848 mContext.registerReceiver(
849 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
850
851 // listen for restrict background changes from notifications
852 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
853 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
854
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700855 // Listen for snooze from notifications
856 mContext.registerReceiver(mSnoozeReceiver,
857 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
858 mContext.registerReceiver(mSnoozeReceiver,
859 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700860
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600861 // listen for configured wifi networks to be loaded
862 final IntentFilter wifiFilter =
863 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
864 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700865
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700866 // listen for carrier config changes to update data cycle information
867 final IntentFilter carrierConfigFilter = new IntentFilter(
868 ACTION_CARRIER_CONFIG_CHANGED);
869 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
870
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600871 // listen for meteredness changes
872 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
873 new NetworkRequest.Builder().build(), mNetworkCallback);
874
Felipe Leme873a83a2016-09-07 11:34:10 -0700875 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600876
877 // Listen for subscriber changes
878 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
879 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
880 @Override
881 public void onSubscriptionsChanged() {
882 updateNetworksInternal();
883 }
884 });
885
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800886 // tell systemReady() that the service has been initialized
887 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700888 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800889 // Restore the default priority after init is done
890 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700891 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700892 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700893 }
894
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800895 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700896 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800897 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
898 mHandler.post(() -> initService(initCompleteSignal));
899 return initCompleteSignal;
900 }
901
902 public void systemReady(CountDownLatch initCompleteSignal) {
903 // wait for initService to complete
904 try {
905 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
906 throw new IllegalStateException("Service " + TAG +" init timeout");
907 }
908 } catch (InterruptedException e) {
909 Thread.currentThread().interrupt();
910 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
911 }
912 }
913
Sudheer Shankac9d94072017-02-22 22:13:55 +0000914 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700915 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700916 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
917 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700918 }
919
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700920 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700921 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700922 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700923
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700924 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700925 }
926
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700927 @Override public void onUidIdle(int uid, boolean disabled) {
928 }
929
930 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700931 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700932 };
933
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700934 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700935 @Override
936 public void onReceive(Context context, Intent intent) {
937 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700938 synchronized (mUidRulesFirstLock) {
939 updatePowerSaveWhitelistUL();
940 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700941 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700942 }
943 }
944 };
945
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700946 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700947 @Override
948 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700949 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700950
951 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700952 final int uid = intent.getIntExtra(EXTRA_UID, -1);
953 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700954
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700955 if (ACTION_PACKAGE_ADDED.equals(action)) {
956 // update rules for UID, since it might be subject to
957 // global background data policy
958 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700959 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700960 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700961 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700962 }
963 }
964 };
965
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700966 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700967 @Override
968 public void onReceive(Context context, Intent intent) {
969 // on background handler thread, and UID_REMOVED is protected
970
971 final int uid = intent.getIntExtra(EXTRA_UID, -1);
972 if (uid == -1) return;
973
974 // remove any policy and update rules to clean up
975 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700976 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700977 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700978 synchronized (mNetworkPoliciesSecondLock) {
979 writePolicyAL();
980 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700981 }
982 }
983 };
984
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700985 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700986 @Override
987 public void onReceive(Context context, Intent intent) {
988 // on background handler thread, and USER_ADDED and USER_REMOVED
989 // broadcasts are protected
990
991 final String action = intent.getAction();
992 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
993 if (userId == -1) return;
994
Amith Yamasani15e472352015-04-24 19:06:07 -0700995 switch (action) {
996 case ACTION_USER_REMOVED:
997 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700998 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800999 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -07001000 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -07001001 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001002 // Removing outside removeUserStateUL since that can also be called when
1003 // user resets app preferences.
1004 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001005 if (action == ACTION_USER_ADDED) {
1006 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001007 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001008 }
1009 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001010 synchronized (mNetworkPoliciesSecondLock) {
1011 updateRulesForGlobalChangeAL(true);
1012 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001013 }
1014 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001015 }
1016 }
1017 };
1018
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001019 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 * Receiver that watches for {@link INetworkStatsService} updates, which we
1021 * use to check against {@link NetworkPolicy#warningBytes}.
1022 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001023 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024 @Override
1025 public void onReceive(Context context, Intent intent) {
1026 // on background handler thread, and verified
1027 // READ_NETWORK_USAGE_HISTORY permission above.
1028
Felipe Lemef0823852016-06-08 13:43:08 -07001029 synchronized (mNetworkPoliciesSecondLock) {
1030 updateNetworkEnabledNL();
1031 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001032 }
1033 }
1034 };
1035
1036 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001037 * Receiver that watches for {@link Notification} control of
1038 * {@link #mRestrictBackground}.
1039 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001040 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001041 @Override
1042 public void onReceive(Context context, Intent intent) {
1043 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1044 // permission above.
1045
1046 setRestrictBackground(false);
1047 }
1048 };
1049
1050 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 * Receiver that watches for {@link Notification} control of
1052 * {@link NetworkPolicy#lastWarningSnooze}.
1053 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001054 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001055 @Override
1056 public void onReceive(Context context, Intent intent) {
1057 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1058 // permission above.
1059
1060 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001061 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1062 performSnooze(template, TYPE_WARNING);
1063 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1064 performSnooze(template, TYPE_RAPID);
1065 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001066 }
1067 };
1068
1069 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001070 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001071 * we can perform upgrade logic. After initial upgrade logic, it updates
1072 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001073 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001074 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001075 @Override
1076 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001077 synchronized (mUidRulesFirstLock) {
1078 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001079 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001080 }
1081 }
1082 // Only need to perform upgrade logic once
1083 mContext.unregisterReceiver(this);
1084 }
1085 };
1086
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001087 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1088 Network network) {
1089 final boolean lastValue = lastValues.get(network.netId, false);
1090 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1091 if (changed) {
1092 lastValues.put(network.netId, newValue);
1093 }
1094 return changed;
1095 }
1096
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001097 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1098 @Override
1099 public void onCapabilitiesChanged(Network network,
1100 NetworkCapabilities networkCapabilities) {
1101 if (network == null || networkCapabilities == null) return;
1102
1103 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001104 final boolean newMetered = !networkCapabilities
1105 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001106 final boolean meteredChanged = updateCapabilityChange(
1107 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001108
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001109 final boolean newRoaming = !networkCapabilities
1110 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1111 final boolean roamingChanged = updateCapabilityChange(
1112 mNetworkRoaming, newRoaming, network);
1113
1114 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001115 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001116 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001117 }
1118 }
1119 }
1120 };
1121
1122 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 * Observer that watches for {@link INetworkManagementService} alerts.
1124 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001125 final private INetworkManagementEventObserver mAlertObserver
1126 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 @Override
1128 public void limitReached(String limitName, String iface) {
1129 // only someone like NMS should be calling us
paulhu59148b72019-08-12 16:25:11 +08001130 NetworkStack.checkNetworkStackPermission(mContext);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001132 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1133 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001134 }
1135 }
1136 };
1137
1138 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001139 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1140 * to show visible notifications as needed.
1141 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001142 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001143 void updateNotificationsNL() {
1144 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001145 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001148 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001149 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150
1151 // TODO: when switching to kernel notifications, compute next future
1152 // cycle boundary to recompute notifications.
1153
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001154 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001155 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001156 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1157 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001158 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001159
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001160 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001161 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001162 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163
Jeff Sharkey53313d72017-07-13 16:47:32 -06001164 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1165 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001166 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1167 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1168 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001169
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001170 // Carrier might want to manage notifications themselves
1171 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001172 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1173 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1174 // Don't show notifications until we confirm that the loaded config is from an
1175 // identified carrier, which may want to manage their own notifications. This method
1176 // should be called every time the carrier config changes anyways, and there's no
1177 // reason to alert if there isn't a carrier.
1178 return;
1179 }
1180
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001181 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1182 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1183 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1184 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1185 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1186 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1187
1188 // Notify when data usage is over warning
1189 if (notifyWarning) {
1190 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1191 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1192 if (!snoozedThisCycle) {
1193 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1194 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001196 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001198 // Notify when data usage is over limit
1199 if (notifyLimit) {
1200 if (policy.isOverLimit(totalBytes)) {
1201 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1202 if (snoozedThisCycle) {
1203 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1204 } else {
1205 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1206 notifyOverLimitNL(policy.template);
1207 }
1208 } else {
1209 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001210 }
1211 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001212
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001213 // Warn if average usage over last 4 days is on track to blow pretty
1214 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001215 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001216 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001217 final long recentStart = now - recentDuration;
1218 final long recentEnd = now;
1219 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001220
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001221 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001222 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001223 final long alertBytes = (policy.limitBytes * 3) / 2;
1224
1225 if (LOGD) {
1226 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1227 + projectedBytes + " alert " + alertBytes);
1228 }
1229
1230 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1231 - DateUtils.DAY_IN_MILLIS;
1232 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001233 enqueueNotification(policy, TYPE_RAPID, 0,
1234 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001235 }
1236 }
1237 }
1238
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001240 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001241 final NotificationId notificationId = beforeNotifs.valueAt(i);
1242 if (!mActiveNotifs.contains(notificationId)) {
1243 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001244 }
1245 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001246
1247 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001248 }
1249
1250 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001251 * Attempt to find a specific app to blame for rapid data usage during the
1252 * given time period.
1253 */
1254 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1255 long start, long end) {
1256 long totalBytes = 0;
1257 long maxBytes = 0;
1258 int maxUid = 0;
1259
1260 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1261 NetworkStats.Entry entry = null;
1262 for (int i = 0; i < stats.size(); i++) {
1263 entry = stats.getValues(i, entry);
1264 final long bytes = entry.rxBytes + entry.txBytes;
1265 totalBytes += bytes;
1266 if (bytes > maxBytes) {
1267 maxBytes = bytes;
1268 maxUid = entry.uid;
1269 }
1270 }
1271
1272 // Only point blame if the majority of usage was done by a single app.
1273 // TODO: support shared UIDs
1274 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1275 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001276 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001277 try {
1278 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1279 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1280 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1281 } catch (NameNotFoundException ignored) {
1282 }
1283 }
1284 }
1285
1286 return null;
1287 }
1288
1289 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001290 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001291 * current device state, such as when
1292 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1293 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001294 *
1295 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1296 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001297 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001298 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001299 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001300 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001301 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1302 final int subId = mSubIdToSubscriberId.keyAt(i);
1303 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001304 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1305 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1306 true);
1307 if (template.matches(probeIdent)) {
1308 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001309 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001310 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001311 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001312 }
1313
1314 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 * Notify that given {@link NetworkTemplate} is over
1316 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1317 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001318 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001319 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001320 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001321 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001322 mOverLimitNotified.add(template);
1323 }
1324 }
1325
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001326 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001327 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001328 mOverLimitNotified.remove(template);
1329 }
1330
1331 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001332 * Show notification for combined {@link NetworkPolicy} and specific type,
1333 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1334 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001335 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1336 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001337 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001338 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001339 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001340 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001341 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001342 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001343 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001344
1345 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001346 final CharSequence title;
1347 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348 switch (type) {
1349 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001350 title = res.getText(R.string.data_usage_warning_title);
1351 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001352 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001353
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001354 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001355
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001356 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1357 builder.setDeleteIntent(PendingIntent.getBroadcast(
1358 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1359
Wei Liu546cb772016-07-21 16:19:01 -07001360 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001361 // TODO: Resolve to single code path.
1362 if (isHeadlessSystemUserBuild()) {
1363 builder.setContentIntent(PendingIntent.getActivityAsUser(
1364 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1365 /* options= */ null, UserHandle.CURRENT));
1366 } else {
1367 builder.setContentIntent(PendingIntent.getActivity(
1368 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1369 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001370 break;
1371 }
1372 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001373 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001374 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001375 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001376 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001377 case MATCH_WIFI:
1378 title = res.getText(R.string.data_usage_wifi_limit_title);
1379 break;
1380 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001381 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001382 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001383 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001384
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001385 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001386 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001387
Wei Liu546cb772016-07-21 16:19:01 -07001388 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001389 // TODO: Resolve to single code path.
1390 if (isHeadlessSystemUserBuild()) {
1391 builder.setContentIntent(PendingIntent.getActivityAsUser(
1392 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1393 /* options= */ null, UserHandle.CURRENT));
1394 } else {
1395 builder.setContentIntent(PendingIntent.getActivity(
1396 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1397 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001398 break;
1399 }
1400 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001401 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001402 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001403 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1404 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001405 case MATCH_WIFI:
1406 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1407 break;
1408 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001409 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001410 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001411 final long overBytes = totalBytes - policy.limitBytes;
1412 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001413 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001414
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001415 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001416 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001417 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001418
Wei Liu546cb772016-07-21 16:19:01 -07001419 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001420 // TODO: Resolve to single code path.
1421 if (isHeadlessSystemUserBuild()) {
1422 builder.setContentIntent(PendingIntent.getActivityAsUser(
1423 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1424 /* options= */ null, UserHandle.CURRENT));
1425 } else {
1426 builder.setContentIntent(PendingIntent.getActivity(
1427 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1428 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001429 break;
1430 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001431 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001432 title = res.getText(R.string.data_usage_rapid_title);
1433 if (rapidBlame != null) {
1434 body = res.getString(R.string.data_usage_rapid_app_body,
1435 rapidBlame.loadLabel(mContext.getPackageManager()));
1436 } else {
1437 body = res.getString(R.string.data_usage_rapid_body);
1438 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001439
Jeff Sharkey2e471452018-01-19 18:02:47 +09001440 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001441
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001442 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1443 builder.setDeleteIntent(PendingIntent.getBroadcast(
1444 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1445
1446 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001447 // TODO: Resolve to single code path.
1448 if (isHeadlessSystemUserBuild()) {
1449 builder.setContentIntent(PendingIntent.getActivityAsUser(
1450 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1451 /* options= */ null, UserHandle.CURRENT));
1452 } else {
1453 builder.setContentIntent(PendingIntent.getActivity(
1454 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1455 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001456 break;
1457 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001458 default: {
1459 return;
1460 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001461 }
1462
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001463 builder.setTicker(title);
1464 builder.setContentTitle(title);
1465 builder.setContentText(body);
1466 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001467
1468 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1469 notificationId.getId(), builder.build(), UserHandle.ALL);
1470 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001471 }
1472
Chris Wren193ae6b2017-03-31 15:17:11 -04001473 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001474 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1475 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001476 }
1477
1478 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001479 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001480 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001481 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001482 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483 @Override
1484 public void onReceive(Context context, Intent intent) {
paulhu59148b72019-08-12 16:25:11 +08001485 // on background handler thread, and verified NETWORK_STACK
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001487 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001488 }
1489 };
1490
Jeff Sharkey146bb332018-04-18 15:42:57 -06001491 private void updateNetworksInternal() {
1492 // Get all of our cross-process communication with telephony out of
1493 // the way before we acquire internal locks.
1494 updateSubscriptions();
1495
1496 synchronized (mUidRulesFirstLock) {
1497 synchronized (mNetworkPoliciesSecondLock) {
1498 ensureActiveMobilePolicyAL();
1499 normalizePoliciesNL();
1500 updateNetworkEnabledNL();
1501 updateNetworkRulesNL();
1502 updateNotificationsNL();
1503 }
1504 }
1505 }
1506
Jeff Sharkey2e471452018-01-19 18:02:47 +09001507 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001508 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001509 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001510 final CountDownLatch latch = new CountDownLatch(1);
1511 mHandler.post(() -> {
1512 latch.countDown();
1513 });
1514 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001515 }
1516
Sudheer Shanka2d1ab902019-10-12 15:01:44 -07001517 @VisibleForTesting
1518 Handler getHandlerForTesting() {
1519 return mHandler;
1520 }
1521
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001523 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1524 * if necessary.
1525 *
1526 * @param subId that has its associated NetworkPolicy updated if necessary
1527 * @return if any policies were updated
1528 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001529 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001530 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001531 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001532
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001533 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001534 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001535 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001536 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001537 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1538 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1539 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001540 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1541 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001542 }
1543 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001544 return policyUpdated;
1545 }
1546
1547 /**
1548 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1549 *
1550 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1551 * to do so, it returns the fallback value.
1552 *
1553 * @param config The CarrierConfig to read the value from.
1554 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1555 * @return cycleDay to use in the mobile NetworkPolicy.
1556 */
1557 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001558 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001559 int fallbackCycleDay) {
1560 if (config == null) {
1561 return fallbackCycleDay;
1562 }
1563 int cycleDay =
1564 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1565 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1566 return fallbackCycleDay;
1567 }
1568 // validate cycleDay value
1569 final Calendar cal = Calendar.getInstance();
1570 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1571 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1572 Slog.e(TAG, "Invalid date in "
1573 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1574 return fallbackCycleDay;
1575 }
1576 return cycleDay;
1577 }
1578
1579 /**
1580 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1581 *
1582 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1583 * to do so, it returns the fallback value.
1584 *
1585 * @param config The CarrierConfig to read the value from.
1586 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1587 * @return warningBytes to use in the mobile NetworkPolicy.
1588 */
1589 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001590 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001591 long fallbackWarningBytes) {
1592 if (config == null) {
1593 return fallbackWarningBytes;
1594 }
1595 long warningBytes =
1596 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1597
1598 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1599 return WARNING_DISABLED;
1600 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1601 return getPlatformDefaultWarningBytes();
1602 } else if (warningBytes < 0) {
1603 Slog.e(TAG, "Invalid value in "
1604 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1605 + "non-negative value but got: " + warningBytes);
1606 return fallbackWarningBytes;
1607 }
1608
1609 return warningBytes;
1610 }
1611
1612 /**
1613 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1614 *
1615 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1616 * to do so, it returns the fallback value.
1617 *
1618 * @param config The CarrierConfig to read the value from.
1619 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1620 * @return limitBytes to use in the mobile NetworkPolicy.
1621 */
1622 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001623 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001624 long fallbackLimitBytes) {
1625 if (config == null) {
1626 return fallbackLimitBytes;
1627 }
1628 long limitBytes =
1629 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1630
1631 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1632 return LIMIT_DISABLED;
1633 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1634 return getPlatformDefaultLimitBytes();
1635 } else if (limitBytes < 0) {
1636 Slog.e(TAG, "Invalid value in "
1637 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1638 + "non-negative value but got: " + limitBytes);
1639 return fallbackLimitBytes;
1640 }
1641 return limitBytes;
1642 }
1643
1644 /**
1645 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1646 */
1647 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1648 @Override
1649 public void onReceive(Context context, Intent intent) {
1650 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1651 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1652
1653 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1654 return;
1655 }
1656 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001657
1658 // Get all of our cross-process communication with telephony out of
1659 // the way before we acquire internal locks.
1660 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001661
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001662 synchronized (mUidRulesFirstLock) {
1663 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001664 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1665 if (subscriberId != null) {
1666 ensureActiveMobilePolicyAL(subId, subscriberId);
1667 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1668 } else {
1669 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1670 }
1671
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001672 // update network and notification rules, as the data cycle changed and it's
1673 // possible that we should be triggering warnings/limits now
1674 handleNetworkPoliciesUpdateAL(true);
1675 }
1676 }
1677 }
1678 };
1679
1680 /**
1681 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1682 * one has been updated.
1683 *
1684 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1685 * update.
1686 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001687 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001688 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1689 if (shouldNormalizePolicies) {
1690 normalizePoliciesNL();
1691 }
1692 updateNetworkEnabledNL();
1693 updateNetworkRulesNL();
1694 updateNotificationsNL();
1695 writePolicyAL();
1696 }
1697
1698 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001699 * Proactively control network data connections when they exceed
1700 * {@link NetworkPolicy#limitBytes}.
1701 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001702 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001703 void updateNetworkEnabledNL() {
1704 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001705 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001706
1707 // TODO: reset any policy-disabled networks when any policy is removed
1708 // completely, which is currently rare case.
1709
Makoto Onuki49392d32018-04-11 13:51:02 -07001710 final long startTime = mStatLogger.getTime();
1711
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001712 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1713 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001714 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001715 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001716 setNetworkTemplateEnabled(policy.template, true);
1717 continue;
1718 }
1719
Jeff Sharkey53313d72017-07-13 16:47:32 -06001720 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1721 .cycleIterator(policy).next();
1722 final long start = cycle.first.toInstant().toEpochMilli();
1723 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001724 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001725
1726 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001727 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1728 && policy.lastLimitSnooze < start;
1729 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001730
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001731 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001732 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001733
1734 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001735 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001736 }
1737
1738 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001739 * Proactively disable networks that match the given
1740 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001741 */
1742 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001743 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1744 // held. Call it via the handler.
1745 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1746 .sendToTarget();
1747 }
1748
1749 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001750 // TODO: reach into ConnectivityManager to proactively disable bringing
1751 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001752
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001753 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001754 // If mobile data usage hits the limit or if the user resumes the data, we need to
1755 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001756
Jeff Sharkey146bb332018-04-18 15:42:57 -06001757 final IntArray matchingSubIds = new IntArray();
1758 synchronized (mNetworkPoliciesSecondLock) {
1759 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1760 final int subId = mSubIdToSubscriberId.keyAt(i);
1761 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1762
1763 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1764 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1765 true);
1766 // Template is matched when subscriber id matches.
1767 if (template.matches(probeIdent)) {
1768 matchingSubIds.add(subId);
1769 }
Jack Yu8781b682016-07-08 14:28:51 -07001770 }
1771 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001772
1773 // Only talk with telephony outside of locks
1774 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1775 for (int i = 0; i < matchingSubIds.size(); i++) {
1776 final int subId = matchingSubIds.get(i);
1777 tm.setPolicyDataEnabled(enabled, subId);
1778 }
Jack Yu8781b682016-07-08 14:28:51 -07001779 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001780 }
1781
1782 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001783 * Collect all ifaces from a {@link NetworkState} into the given set.
1784 */
1785 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1786 final String baseIface = state.linkProperties.getInterfaceName();
1787 if (baseIface != null) {
1788 ifaces.add(baseIface);
1789 }
1790 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1791 final String stackedIface = stackedLink.getInterfaceName();
1792 if (stackedIface != null) {
1793 ifaces.add(stackedIface);
1794 }
1795 }
1796 }
1797
1798 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001799 * Examine all currently active subscriptions from
1800 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1801 * internal data structures.
1802 * <p>
1803 * Callers <em>must not</em> hold any locks when this method called.
1804 */
1805 void updateSubscriptions() {
1806 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1807 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1808
1809 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1810 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1811
1812 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001813 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001814
1815 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1816 for (int subId : subIds) {
1817 final String subscriberId = tm.getSubscriberId(subId);
1818 if (!TextUtils.isEmpty(subscriberId)) {
1819 subIdToSubscriberId.put(subId, subscriberId);
1820 } else {
1821 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1822 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001823
1824 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1825 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1826 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001827 }
1828
1829 synchronized (mNetworkPoliciesSecondLock) {
1830 mSubIdToSubscriberId.clear();
1831 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1832 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1833 subIdToSubscriberId.valueAt(i));
1834 }
1835
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001836 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001837 }
1838
1839 Trace.traceEnd(TRACE_TAG_NETWORK);
1840 }
1841
1842 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001843 * Examine all connected {@link NetworkState}, looking for
1844 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1845 * remaining quota based on usage cycle and historical stats.
1846 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001847 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001848 void updateNetworkRulesNL() {
1849 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001850 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851
1852 final NetworkState[] states;
1853 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001854 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001855 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001856 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001857 return;
1858 }
1859
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001860 // First, generate identities of all connected networks so we can
1861 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001862 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001863 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001864 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001865 if (state.network != null) {
1866 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1867 }
Wei Liub8eaf452016-01-25 10:32:27 -08001868 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001869 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1870 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001871 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001872 }
1873 }
1874
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001875 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001876 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001877
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001878 // For every well-defined policy, compute remaining data based on
1879 // current cycle and historical stats, and push to kernel.
1880 final ArraySet<String> matchingIfaces = new ArraySet<>();
1881 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1882 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1883
1884 // Collect all ifaces that match this policy
1885 matchingIfaces.clear();
1886 for (int j = identified.size() - 1; j >= 0; j--) {
1887 if (policy.template.matches(identified.valueAt(j))) {
1888 collectIfaces(matchingIfaces, identified.keyAt(j));
1889 }
1890 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001891
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001892 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001893 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001894 }
1895
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001896 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001897 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001898 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001899 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001900 if (hasLimit && policy.hasCycle()) {
1901 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1902 .cycleIterator(policy).next();
1903 final long start = cycle.first.toInstant().toEpochMilli();
1904 final long end = cycle.second.toInstant().toEpochMilli();
1905 final long totalBytes = getTotalBytes(policy.template, start, end);
1906
1907 if (policy.lastLimitSnooze >= start) {
1908 // snoozing past quota, but we still need to restrict apps,
1909 // so push really high quota.
1910 quotaBytes = Long.MAX_VALUE;
1911 } else {
1912 // remaining "quota" bytes are based on total usage in
1913 // current cycle. kernel doesn't like 0-byte rules, so we
1914 // set 1-byte quota and disable the radio later.
1915 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1916 }
1917 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001918 // metered network, but no policy limit; we still need to
1919 // restrict apps, so push really high quota.
1920 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001921 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001922
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001923 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001924 // TODO: switch to shared quota once NMS supports
1925 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001926 }
1927
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001928 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1929 final String iface = matchingIfaces.valueAt(j);
1930 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001931 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001932 }
1933 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001934
1935 // keep track of lowest warning or limit of active policies
1936 if (hasWarning && policy.warningBytes < lowestRule) {
1937 lowestRule = policy.warningBytes;
1938 }
1939 if (hasLimit && policy.limitBytes < lowestRule) {
1940 lowestRule = policy.limitBytes;
1941 }
1942 }
1943
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001944 // One final pass to catch any metered ifaces that don't have explicitly
1945 // defined policies; typically Wi-Fi networks.
1946 for (NetworkState state : states) {
1947 if (state.networkInfo != null && state.networkInfo.isConnected()
1948 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1949 matchingIfaces.clear();
1950 collectIfaces(matchingIfaces, state);
1951 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1952 final String iface = matchingIfaces.valueAt(j);
1953 if (!newMeteredIfaces.contains(iface)) {
1954 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1955 newMeteredIfaces.add(iface);
1956 }
1957 }
1958 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001959 }
1960
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001961 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001962 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1963 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001964 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001965 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001966 }
1967 }
1968 mMeteredIfaces = newMeteredIfaces;
1969
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001970 final ContentResolver cr = mContext.getContentResolver();
1971 final boolean quotaEnabled = Settings.Global.getInt(cr,
1972 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1973 final long quotaUnlimited = Settings.Global.getLong(cr,
1974 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1975 final float quotaLimited = Settings.Global.getFloat(cr,
1976 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1977
Jeff Sharkey9252b342018-01-19 07:58:35 +09001978 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001979 mSubscriptionOpportunisticQuota.clear();
1980 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001981 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001982 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001983 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001984 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001985 if (plan == null) continue;
1986
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001987 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001988 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001989 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1990 // Clamp to 0 when roaming
1991 quotaBytes = 0;
1992 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001993 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001994 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001995 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001996 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001997 } else {
1998 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001999 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
2000 final long start = cycle.getLower().toInstant().toEpochMilli();
2001 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002002 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06002003 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002004 .truncatedTo(ChronoUnit.DAYS)
2005 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09002006 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002007 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
2008 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09002009 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002010 // Number of remaining days including current day
2011 final long remainingDays =
2012 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002013
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002014 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002015 }
2016
2017 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2018 }
2019
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002020 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002021 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002022
2023 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002024
2025 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002026 }
2027
2028 /**
2029 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2030 * have at least a default mobile policy defined.
2031 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002032 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002033 private void ensureActiveMobilePolicyAL() {
2034 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002035 if (mSuppressDefaultPolicy) return;
2036
Jeff Sharkey146bb332018-04-18 15:42:57 -06002037 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2038 final int subId = mSubIdToSubscriberId.keyAt(i);
2039 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002040
Hugo Benichi446c9c92017-04-10 09:41:10 +09002041 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002042 }
2043 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002044
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002045 /**
2046 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2047 * have at least a default mobile policy defined.
2048 *
2049 * @param subId to build a default policy for
2050 * @param subscriberId that we check for an existing policy
2051 * @return true if a mobile network policy was added, or false one already existed.
2052 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002053 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002054 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002055 // Poke around to see if we already have a policy
2056 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002057 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002058 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2059 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2060 if (template.matches(probeIdent)) {
2061 if (LOGD) {
2062 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2063 + NetworkIdentity.scrubSubscriberId(subscriberId));
2064 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002065 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002066 }
2067 }
2068
Jeff Sharkey32566012014-12-02 18:30:14 -08002069 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2070 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002071 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002072 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002073 return true;
2074 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002075
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002076 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002077 final int dataWarningConfig = mContext.getResources().getInteger(
2078 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002079 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002080 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002081 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002082 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002083 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002084 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002085
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002086 private long getPlatformDefaultLimitBytes() {
2087 return LIMIT_DISABLED;
2088 }
2089
2090 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002091 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002092 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002093 final RecurrenceRule cycleRule = NetworkPolicy
2094 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002095 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002096 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2097 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2098 synchronized (mUidRulesFirstLock) {
2099 synchronized (mNetworkPoliciesSecondLock) {
2100 updateDefaultMobilePolicyAL(subId, policy);
2101 }
2102 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002103 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002104 }
2105
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002106 /**
2107 * Update the given {@link NetworkPolicy} based on any carrier-provided
2108 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2109 * Leaves policy untouched if the user has modified it.
2110 *
2111 * @return if the policy was modified
2112 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002113 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002114 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2115 if (!policy.inferred) {
2116 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2117 return false;
2118 }
2119
2120 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2121 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2122 policy.lastLimitSnooze, policy.metered, policy.inferred);
2123
2124 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2125 if (!ArrayUtils.isEmpty(plans)) {
2126 final SubscriptionPlan plan = plans[0];
2127 policy.cycleRule = plan.getCycleRule();
2128 final long planLimitBytes = plan.getDataLimitBytes();
2129 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2130 policy.warningBytes = getPlatformDefaultWarningBytes();
2131 policy.limitBytes = getPlatformDefaultLimitBytes();
2132 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2133 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2134 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2135 } else {
2136 policy.warningBytes = (planLimitBytes * 9) / 10;
2137 switch (plan.getDataLimitBehavior()) {
2138 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2139 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2140 policy.limitBytes = planLimitBytes;
2141 break;
2142 default:
2143 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2144 break;
2145 }
2146 }
2147 } else {
2148 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2149 final int currentCycleDay;
2150 if (policy.cycleRule.isMonthly()) {
2151 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2152 } else {
2153 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2154 }
2155 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2156 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2157 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2158 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2159 }
2160
2161 if (policy.equals(original)) {
2162 return false;
2163 } else {
2164 Slog.d(TAG, "Updated " + original + " to " + policy);
2165 return true;
2166 }
2167 }
2168
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002169 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002170 private void readPolicyAL() {
2171 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002172
2173 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002174 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002175 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002176 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002177 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002178
2179 FileInputStream fis = null;
2180 try {
2181 fis = mPolicyFile.openRead();
2182 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002183 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184
Felipe Leme46b451f2016-08-19 08:46:17 -07002185 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2186 // to skip UIDs that were explicitly blacklisted.
2187 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2188
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002189 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002190 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002191 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002192 while ((type = in.next()) != END_DOCUMENT) {
2193 final String tag = in.getName();
2194 if (type == START_TAG) {
2195 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002196 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002197 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002198 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2199 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002200 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2201 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2202 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002203 final String networkId;
2204 if (version >= VERSION_ADDED_NETWORK_ID) {
2205 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2206 } else {
2207 networkId = null;
2208 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002209 final RecurrenceRule cycleRule;
2210 if (version >= VERSION_ADDED_CYCLE) {
2211 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2212 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2213 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2214 cycleRule = new RecurrenceRule(
2215 RecurrenceRule.convertZonedDateTime(start),
2216 RecurrenceRule.convertZonedDateTime(end),
2217 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002218 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002219 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2220 final String cycleTimezone;
2221 if (version >= VERSION_ADDED_TIMEZONE) {
2222 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2223 } else {
2224 cycleTimezone = "UTC";
2225 }
2226 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002227 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002228 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2229 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002230 final long lastLimitSnooze;
2231 if (version >= VERSION_SPLIT_SNOOZE) {
2232 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2233 } else if (version >= VERSION_ADDED_SNOOZE) {
2234 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002235 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002236 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002237 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002238 final boolean metered;
2239 if (version >= VERSION_ADDED_METERED) {
2240 metered = readBooleanAttribute(in, ATTR_METERED);
2241 } else {
2242 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002243 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002244 metered = true;
2245 break;
2246 default:
2247 metered = false;
2248 }
2249 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002250 final long lastWarningSnooze;
2251 if (version >= VERSION_SPLIT_SNOOZE) {
2252 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2253 } else {
2254 lastWarningSnooze = SNOOZE_NEVER;
2255 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002256 final boolean inferred;
2257 if (version >= VERSION_ADDED_INFERRED) {
2258 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2259 } else {
2260 inferred = false;
2261 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002262
Jeff Sharkey32566012014-12-02 18:30:14 -08002263 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2264 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002265 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002266 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2267 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002268 lastLimitSnooze, metered, inferred));
2269 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002270
2271 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2272 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2273 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2274 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2275 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2276 RecurrenceRule.convertZonedDateTime(start),
2277 RecurrenceRule.convertZonedDateTime(end),
2278 RecurrenceRule.convertPeriod(period));
2279 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2280 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2281
2282 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2283 SubscriptionPlan.BYTES_UNKNOWN);
2284 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2285 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2286 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2287 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2288 builder.setDataLimit(limitBytes, limitBehavior);
2289 }
2290
2291 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2292 SubscriptionPlan.BYTES_UNKNOWN);
2293 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2294 SubscriptionPlan.TIME_UNKNOWN);
2295 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2296 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2297 builder.setDataUsage(usageBytes, usageTime);
2298 }
2299
2300 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2301 final SubscriptionPlan plan = builder.build();
2302 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2303 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2304
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002305 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2306 mSubscriptionPlansOwner.put(subId, ownerPackage);
2307
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002308 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002309 final int uid = readIntAttribute(in, ATTR_UID);
2310 final int policy = readIntAttribute(in, ATTR_POLICY);
2311
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002312 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002313 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002314 } else {
2315 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2316 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002318 final int appId = readIntAttribute(in, ATTR_APP_ID);
2319 final int policy = readIntAttribute(in, ATTR_POLICY);
2320
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002321 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002322 // app policy is deprecated so this is only used in pre system user split.
2323 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002324 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002325 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002326 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002327 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002328 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002329 } else if (TAG_WHITELIST.equals(tag)) {
2330 insideWhitelist = true;
2331 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2332 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002333 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002334 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2335 final int uid = readIntAttribute(in, ATTR_UID);
2336 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002337 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002338 } else if (type == END_TAG) {
2339 if (TAG_WHITELIST.equals(tag)) {
2340 insideWhitelist = false;
2341 }
2342
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002343 }
2344 }
2345
Felipe Leme46b451f2016-08-19 08:46:17 -07002346 final int size = whitelistedRestrictBackground.size();
2347 for (int i = 0; i < size; i++) {
2348 final int uid = whitelistedRestrictBackground.keyAt(i);
2349 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2350 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2351 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2352 + " because its policy is " + uidPoliciesToString(policy));
2353 continue;
2354 }
2355 if (UserHandle.isApp(uid)) {
2356 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2357 if (LOGV)
2358 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2359 setUidPolicyUncheckedUL(uid, newPolicy, false);
2360 } else {
2361 Slog.w(TAG, "unable to update policy on UID " + uid);
2362 }
2363 }
2364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 } catch (FileNotFoundException e) {
2366 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002367 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002368 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002369 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002370 } finally {
2371 IoUtils.closeQuietly(fis);
2372 }
2373 }
2374
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002375 /**
2376 * Upgrade legacy background data flags, notifying listeners of one last
2377 * change to always-true.
2378 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002379 private void upgradeDefaultBackgroundDataUL() {
2380 // This method is only called when we're unable to find the network policy flag, which
2381 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002382
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002383 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002384 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002385 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2386
2387 // NOTE: We used to read the legacy setting here :
2388 //
2389 // final int legacyFlagValue = Settings.Secure.getInt(
2390 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2391 //
2392 // This is no longer necessary because we will never upgrade directly from Gingerbread
2393 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2394 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002395 }
2396
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002397 /**
2398 * Perform upgrade step of moving any user-defined meterness overrides over
2399 * into {@link WifiConfiguration}.
2400 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002401 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002402 private void upgradeWifiMeteredOverrideAL() {
2403 boolean modified = false;
2404 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2405 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2406 for (int i = 0; i < mNetworkPolicy.size(); ) {
2407 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2408 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2409 && !policy.inferred) {
2410 mNetworkPolicy.removeAt(i);
2411 modified = true;
2412
2413 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2414 for (WifiConfiguration config : configs) {
2415 if (Objects.equals(resolveNetworkId(config), networkId)) {
2416 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2417 config.meteredOverride = policy.metered
2418 ? WifiConfiguration.METERED_OVERRIDE_METERED
2419 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2420 wm.updateNetwork(config);
2421 }
2422 }
2423 } else {
2424 i++;
2425 }
2426 }
2427 if (modified) {
2428 writePolicyAL();
2429 }
2430 }
2431
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002432 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002433 void writePolicyAL() {
2434 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002435
2436 FileOutputStream fos = null;
2437 try {
2438 fos = mPolicyFile.startWrite();
2439
2440 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002441 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002442 out.startDocument(null, true);
2443
2444 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002445 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002446 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002447
2448 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002449 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2450 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002451 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002452 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002453
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002454 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002455 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2456 final String subscriberId = template.getSubscriberId();
2457 if (subscriberId != null) {
2458 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002459 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002460 final String networkId = template.getNetworkId();
2461 if (networkId != null) {
2462 out.attribute(null, ATTR_NETWORK_ID, networkId);
2463 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002464 writeStringAttribute(out, ATTR_CYCLE_START,
2465 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2466 writeStringAttribute(out, ATTR_CYCLE_END,
2467 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2468 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2469 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002470 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2471 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002472 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2473 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002474 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002475 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002476 out.endTag(null, TAG_NETWORK_POLICY);
2477 }
2478
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002479 // write all known subscription plans
2480 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2481 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002482 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002483 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2484 if (ArrayUtils.isEmpty(plans)) continue;
2485
2486 for (SubscriptionPlan plan : plans) {
2487 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2488 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002489 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002490 final RecurrenceRule cycleRule = plan.getCycleRule();
2491 writeStringAttribute(out, ATTR_CYCLE_START,
2492 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2493 writeStringAttribute(out, ATTR_CYCLE_END,
2494 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2495 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2496 RecurrenceRule.convertPeriod(cycleRule.period));
2497 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2498 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2499 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2500 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2501 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2502 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2503 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2504 }
2505 }
2506
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002508 for (int i = 0; i < mUidPolicy.size(); i++) {
2509 final int uid = mUidPolicy.keyAt(i);
2510 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002511
Jeff Sharkey497e4432011-06-14 17:27:29 -07002512 // skip writing empty policies
2513 if (policy == POLICY_NONE) continue;
2514
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002515 out.startTag(null, TAG_UID_POLICY);
2516 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002517 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002518 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002519 }
2520
2521 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002522
2523 // write all whitelists
2524 out.startTag(null, TAG_WHITELIST);
2525
Felipe Lemea9505cc2016-02-26 10:28:41 -08002526 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002527 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002528 for (int i = 0; i < size; i++) {
2529 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2530 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2531 writeIntAttribute(out, ATTR_UID, uid);
2532 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2533 }
2534
Felipe Lemeb85a6372016-01-14 16:16:16 -08002535 out.endTag(null, TAG_WHITELIST);
2536
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002537 out.endDocument();
2538
2539 mPolicyFile.finishWrite(fos);
2540 } catch (IOException e) {
2541 if (fos != null) {
2542 mPolicyFile.failWrite(fos);
2543 }
2544 }
2545 }
2546
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002547 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002548 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002550
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002551 if (!UserHandle.isApp(uid)) {
2552 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002553 }
Felipe Lemef0823852016-06-08 13:43:08 -07002554 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002555 final long token = Binder.clearCallingIdentity();
2556 try {
2557 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2558 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002559 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002560 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002561 }
2562 } finally {
2563 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002564 }
2565 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002566 }
2567
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002568 @Override
2569 public void addUidPolicy(int uid, int policy) {
2570 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002571
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002572 if (!UserHandle.isApp(uid)) {
2573 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2574 }
2575
Felipe Lemef0823852016-06-08 13:43:08 -07002576 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002577 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2578 policy |= oldPolicy;
2579 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002580 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002581 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002582 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002583 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002584 }
2585
2586 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002587 public void removeUidPolicy(int uid, int policy) {
2588 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2589
2590 if (!UserHandle.isApp(uid)) {
2591 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2592 }
2593
Felipe Lemef0823852016-06-08 13:43:08 -07002594 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002595 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2596 policy = oldPolicy & ~policy;
2597 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002598 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002599 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002600 }
2601 }
2602 }
2603
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002604 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002605 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002606 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002607
Felipe Leme57e3d312016-08-23 14:42:52 -07002608 final boolean notifyApp;
2609 if (!isUidValidForWhitelistRules(uid)) {
2610 notifyApp = false;
2611 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002612 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2613 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2614 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2615 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002616 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2617 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002618 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2619 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2620 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2621 if (LOGD)
2622 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2623 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2624 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002625 notifyApp = wasBlocked != isBlocked;
2626 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002627 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2628 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002629 if (persist) {
2630 synchronized (mNetworkPoliciesSecondLock) {
2631 writePolicyAL();
2632 }
2633 }
Felipe Leme923845f2016-03-02 13:42:48 -08002634 }
2635
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002636 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002637 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002638 if (policy == POLICY_NONE) {
2639 mUidPolicy.delete(uid);
2640 } else {
2641 mUidPolicy.put(uid, policy);
2642 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002643
2644 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002645 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002646 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002647 synchronized (mNetworkPoliciesSecondLock) {
2648 writePolicyAL();
2649 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002650 }
2651 }
2652
2653 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002654 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002655 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2656
Felipe Lemef0823852016-06-08 13:43:08 -07002657 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002658 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002659 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002660 }
2661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002662 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002663 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002664 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2665
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002666 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002667 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002668 for (int i = 0; i < mUidPolicy.size(); i++) {
2669 final int uid = mUidPolicy.keyAt(i);
2670 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002671 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2672 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002673 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002674 }
2675 }
2676 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002677 return uids;
2678 }
2679
2680 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002681 * Removes any persistable state associated with given {@link UserHandle}, persisting
2682 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002683 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002684 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002685 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002686
Sudheer Shanka352dc572017-09-22 17:09:38 -07002687 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002688 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002689
Felipe Lemea110eec2016-04-29 09:58:06 -07002690 // Remove entries from revoked default restricted background UID whitelist
2691 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2692 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2693 if (UserHandle.getUserId(uid) == userId) {
2694 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002695 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002696 }
2697 }
2698
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002699 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002700 int[] uids = new int[0];
2701 for (int i = 0; i < mUidPolicy.size(); i++) {
2702 final int uid = mUidPolicy.keyAt(i);
2703 if (UserHandle.getUserId(uid) == userId) {
2704 uids = appendInt(uids, uid);
2705 }
2706 }
2707
2708 if (uids.length > 0) {
2709 for (int uid : uids) {
2710 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002711 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002712 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002713 }
Felipe Lemef0823852016-06-08 13:43:08 -07002714 synchronized (mNetworkPoliciesSecondLock) {
2715 updateRulesForGlobalChangeAL(true);
2716 if (writePolicy && changed) {
2717 writePolicyAL();
2718 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002719 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002720 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002721 }
2722
paulhu59148b72019-08-12 16:25:11 +08002723 private boolean checkAnyPermissionOf(String... permissions) {
2724 for (String permission : permissions) {
2725 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
2726 return true;
2727 }
2728 }
2729 return false;
2730 }
2731
2732 private void enforceAnyPermissionOf(String... permissions) {
2733 if (!checkAnyPermissionOf(permissions)) {
2734 throw new SecurityException("Requires one of the following permissions: "
2735 + String.join(", ", permissions) + ".");
2736 }
2737 }
2738
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002739 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002740 public void registerListener(INetworkPolicyListener listener) {
paulhu59148b72019-08-12 16:25:11 +08002741 // TODO: Remove CONNECTIVITY_INTERNAL and the *AnyPermissionOf methods above after all apps
2742 // have declared OBSERVE_NETWORK_POLICY.
2743 enforceAnyPermissionOf(CONNECTIVITY_INTERNAL, OBSERVE_NETWORK_POLICY);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002744 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002745 }
2746
2747 @Override
2748 public void unregisterListener(INetworkPolicyListener listener) {
paulhu59148b72019-08-12 16:25:11 +08002749 // TODO: Remove CONNECTIVITY_INTERNAL and the *AnyPermissionOf methods above after all apps
2750 // have declared OBSERVE_NETWORK_POLICY.
2751 enforceAnyPermissionOf(CONNECTIVITY_INTERNAL, OBSERVE_NETWORK_POLICY);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002752 mListeners.unregister(listener);
2753 }
2754
Jeff Sharkey1b861272011-05-22 00:34:52 -07002755 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002756 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002757 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2758
Felipe Leme6a05eee2016-02-19 14:43:51 -08002759 final long token = Binder.clearCallingIdentity();
2760 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002761 synchronized (mUidRulesFirstLock) {
2762 synchronized (mNetworkPoliciesSecondLock) {
2763 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002764 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002765 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002766 }
2767 } finally {
2768 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002769 }
2770 }
2771
Hugo Benichi446c9c92017-04-10 09:41:10 +09002772 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002773 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002774 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2775 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002776 }
2777
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002778 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002779 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002780 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002781 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002782 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2783 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2784 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002785 } catch (SecurityException e) {
2786 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002787
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002788 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2789 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2790 return new NetworkPolicy[0];
2791 }
Svet Ganov16a16892015-04-16 10:32:04 -07002792 }
2793
Felipe Lemef0823852016-06-08 13:43:08 -07002794 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002795 final int size = mNetworkPolicy.size();
2796 final NetworkPolicy[] policies = new NetworkPolicy[size];
2797 for (int i = 0; i < size; i++) {
2798 policies[i] = mNetworkPolicy.valueAt(i);
2799 }
2800 return policies;
2801 }
2802 }
2803
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002804 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002805 private void normalizePoliciesNL() {
2806 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002807 }
2808
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002809 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002810 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002811 mNetworkPolicy.clear();
2812 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002813 if (policy == null) {
2814 continue;
2815 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002816 // When two normalized templates conflict, prefer the most
2817 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002818 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002819 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2820 if (existing == null || existing.compareTo(policy) > 0) {
2821 if (existing != null) {
2822 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2823 }
2824 mNetworkPolicy.put(policy.template, policy);
2825 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002826 }
2827 }
2828
2829 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002830 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002831 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002832
2833 final long token = Binder.clearCallingIdentity();
2834 try {
2835 performSnooze(template, TYPE_LIMIT);
2836 } finally {
2837 Binder.restoreCallingIdentity(token);
2838 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002839 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002840
Dianne Hackborn497175b2014-07-01 12:56:08 -07002841 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002842 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002843 synchronized (mUidRulesFirstLock) {
2844 synchronized (mNetworkPoliciesSecondLock) {
2845 // find and snooze local policy that matches
2846 final NetworkPolicy policy = mNetworkPolicy.get(template);
2847 if (policy == null) {
2848 throw new IllegalArgumentException("unable to find policy for " + template);
2849 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002850
Felipe Lemef0823852016-06-08 13:43:08 -07002851 switch (type) {
2852 case TYPE_WARNING:
2853 policy.lastWarningSnooze = currentTime;
2854 break;
2855 case TYPE_LIMIT:
2856 policy.lastLimitSnooze = currentTime;
2857 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002858 case TYPE_RAPID:
2859 policy.lastRapidSnooze = currentTime;
2860 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002861 default:
2862 throw new IllegalArgumentException("unexpected type");
2863 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002864
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002865 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002866 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002867 }
2868 }
2869
2870 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002871 public void onTetheringChanged(String iface, boolean tethering) {
2872 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002873 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002874 if (mRestrictBackground && tethering) {
2875 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2876 setRestrictBackground(false);
2877 }
2878 }
2879 }
2880
2881 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002882 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002883 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002884 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002885 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2886 final long token = Binder.clearCallingIdentity();
2887 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002888 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002889 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002890 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002891 } finally {
2892 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002893 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002894 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002895 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002896 }
2897 }
2898
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002899 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002900 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002901 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002902 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002903 if (restrictBackground == mRestrictBackground) {
2904 // Ideally, UI should never allow this scenario...
2905 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002906 return;
2907 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002908 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2909 final boolean oldRestrictBackground = mRestrictBackground;
2910 mRestrictBackground = restrictBackground;
2911 // Must whitelist foreground apps before turning data saver mode on.
2912 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2913 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2914 updateRulesForRestrictBackgroundUL();
2915 try {
2916 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2917 Slog.e(TAG,
2918 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2919 mRestrictBackground = oldRestrictBackground;
2920 // TODO: if it knew the foreground apps (see TODO above), it could call
2921 // updateRulesForRestrictBackgroundUL() again to restore state.
2922 return;
2923 }
2924 } catch (RemoteException e) {
2925 // ignored; service lives in system_server
2926 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002927
Sudheer Shanka543339f2017-07-28 15:18:07 -07002928 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002929 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002930
2931 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2932 mRestrictBackgroundChangedInBsm = true;
2933 }
2934 synchronized (mNetworkPoliciesSecondLock) {
2935 updateNotificationsNL();
2936 writePolicyAL();
2937 }
2938 } finally {
2939 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002940 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002941 }
2942
2943 private void sendRestrictBackgroundChangedMsg() {
2944 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2945 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2946 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002947 }
2948
Felipe Lemeb85a6372016-01-14 16:16:16 -08002949 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002950 public int getRestrictBackgroundByCaller() {
2951 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2952 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002953
Felipe Lemef0823852016-06-08 13:43:08 -07002954 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002955 // Must clear identity because getUidPolicy() is restricted to system.
2956 final long token = Binder.clearCallingIdentity();
2957 final int policy;
2958 try {
2959 policy = getUidPolicy(uid);
2960 } finally {
2961 Binder.restoreCallingIdentity(token);
2962 }
2963 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2964 // App is blacklisted.
2965 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2966 }
Felipe Leme1b103232016-01-22 09:44:57 -08002967 if (!mRestrictBackground) {
2968 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2969 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002970 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002971 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2972 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2973 }
2974 }
2975
2976 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002977 public boolean getRestrictBackground() {
2978 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2979
Felipe Lemef0823852016-06-08 13:43:08 -07002980 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002981 return mRestrictBackground;
2982 }
2983 }
2984
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002985 @Override
2986 public void setDeviceIdleMode(boolean enabled) {
2987 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002988 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2989 try {
2990 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002991 if (mDeviceIdleMode == enabled) {
2992 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002993 }
Felipe Lemeea014392016-09-06 13:59:54 -07002994 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002995 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002996 if (mSystemReady) {
2997 // Device idle change means we need to rebuild rules for all
2998 // known apps, so do a global refresh.
2999 updateRulesForRestrictPowerUL();
3000 }
3001 }
3002 if (enabled) {
3003 EventLogTags.writeDeviceIdleOnPhase("net");
3004 } else {
3005 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003006 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003007 } finally {
3008 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003009 }
3010 }
3011
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003012 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003013 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
3014 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003015 final long token = Binder.clearCallingIdentity();
3016 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003017 final WifiManager wm = mContext.getSystemService(WifiManager.class);
3018 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
3019 for (WifiConfiguration config : configs) {
3020 if (Objects.equals(resolveNetworkId(config), networkId)) {
3021 config.meteredOverride = meteredOverride;
3022 wm.updateNetwork(config);
3023 }
3024 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003025 } finally {
3026 Binder.restoreCallingIdentity(token);
3027 }
3028 }
3029
Jeff Sharkey46645002011-07-27 21:11:21 -07003030 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003031 @Deprecated
3032 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3033 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3034 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3035 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003036 }
3037
Jeff Sharkey53313d72017-07-13 16:47:32 -06003038 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3039 // Verify they're not lying about package name
3040 mAppOps.checkPackage(callingUid, callingPackage);
3041
Jeff Sharkey53313d72017-07-13 16:47:32 -06003042 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003043 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003044 final long token = Binder.clearCallingIdentity();
3045 try {
3046 si = mContext.getSystemService(SubscriptionManager.class)
3047 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003048 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003049 } finally {
3050 Binder.restoreCallingIdentity(token);
3051 }
3052
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003053 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003054 if (si != null) {
3055 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3056 return;
3057 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003058 }
3059
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003060 // Second check: has the CarrierService delegated access?
3061 if (config != null) {
3062 final String overridePackage = config
3063 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3064 if (!TextUtils.isEmpty(overridePackage)
3065 && Objects.equals(overridePackage, callingPackage)) {
3066 return;
3067 }
3068 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003069
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003070 // Third check: is caller the fallback/default CarrierService?
3071 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3072 if (!TextUtils.isEmpty(defaultPackage)
3073 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003074 return;
3075 }
3076
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003077 // Fourth check: is caller a testing app?
3078 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3079 if (!TextUtils.isEmpty(testPackage)
3080 && Objects.equals(testPackage, callingPackage)) {
3081 return;
3082 }
3083
3084 // Fifth check: is caller a legacy testing app?
3085 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3086 if (!TextUtils.isEmpty(legacyTestPackage)
3087 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003088 return;
3089 }
3090
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003091 // Final check: does the caller hold a permission?
3092 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003093 }
3094
3095 @Override
3096 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3097 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3098
Jeff Sharkey53313d72017-07-13 16:47:32 -06003099 final String fake = SystemProperties.get("fw.fake_plan");
3100 if (!TextUtils.isEmpty(fake)) {
3101 final List<SubscriptionPlan> plans = new ArrayList<>();
3102 if ("month_hard".equals(fake)) {
3103 plans.add(SubscriptionPlan.Builder
3104 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3105 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003106 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3107 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3108 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3109 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3110 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003111 plans.add(SubscriptionPlan.Builder
3112 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3113 .setTitle("G-Mobile Happy")
3114 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3115 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3116 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3117 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3118 .build());
3119 plans.add(SubscriptionPlan.Builder
3120 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3121 .setTitle("G-Mobile, Charged after limit")
3122 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3123 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3124 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3125 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3126 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003127 } else if ("month_soft".equals(fake)) {
3128 plans.add(SubscriptionPlan.Builder
3129 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3130 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3131 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3132 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003133 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3134 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3135 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3136 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3137 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003138 plans.add(SubscriptionPlan.Builder
3139 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3140 .setTitle("G-Mobile, Throttled after limit")
3141 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3142 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3143 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3144 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3145 .build());
3146 plans.add(SubscriptionPlan.Builder
3147 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3148 .setTitle("G-Mobile, No data connection after limit")
3149 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3150 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3151 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3152 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3153 .build());
3154
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003155 } else if ("month_over".equals(fake)) {
3156 plans.add(SubscriptionPlan.Builder
3157 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3158 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3159 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3160 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3161 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3162 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3163 .build());
3164 plans.add(SubscriptionPlan.Builder
3165 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3166 .setTitle("G-Mobile, Throttled after limit")
3167 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3168 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3169 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3170 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3171 .build());
3172 plans.add(SubscriptionPlan.Builder
3173 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3174 .setTitle("G-Mobile, No data connection after limit")
3175 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3176 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3177 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3178 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3179 .build());
3180
Jeff Sharkey53313d72017-07-13 16:47:32 -06003181 } else if ("month_none".equals(fake)) {
3182 plans.add(SubscriptionPlan.Builder
3183 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3184 .setTitle("G-Mobile")
3185 .build());
3186 } else if ("prepaid".equals(fake)) {
3187 plans.add(SubscriptionPlan.Builder
3188 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3189 ZonedDateTime.now().plusDays(10))
3190 .setTitle("G-Mobile")
3191 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3192 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3193 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3194 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3195 .build());
3196 } else if ("prepaid_crazy".equals(fake)) {
3197 plans.add(SubscriptionPlan.Builder
3198 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3199 ZonedDateTime.now().plusDays(10))
3200 .setTitle("G-Mobile Anytime")
3201 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3202 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3203 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3204 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3205 .build());
3206 plans.add(SubscriptionPlan.Builder
3207 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3208 ZonedDateTime.now().plusDays(20))
3209 .setTitle("G-Mobile Nickel Nights")
3210 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003211 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3212 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003213 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3214 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3215 .build());
3216 plans.add(SubscriptionPlan.Builder
3217 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3218 ZonedDateTime.now().plusDays(20))
3219 .setTitle("G-Mobile Bonus 3G")
3220 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003221 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003222 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3223 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3224 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3225 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003226 } else if ("unlimited".equals(fake)) {
3227 plans.add(SubscriptionPlan.Builder
3228 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3229 ZonedDateTime.now().plusDays(10))
3230 .setTitle("G-Mobile Awesome")
3231 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3232 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3233 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3234 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3235 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003236 }
3237 return plans.toArray(new SubscriptionPlan[plans.size()]);
3238 }
3239
Jeff Sharkey4635f102017-09-01 11:27:13 -06003240 synchronized (mNetworkPoliciesSecondLock) {
3241 // Only give out plan details to the package that defined them,
3242 // so that we don't risk leaking plans between apps. We always
3243 // let in core system components (like the Settings app).
3244 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3245 if (Objects.equals(ownerPackage, callingPackage)
3246 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3247 return mSubscriptionPlans.get(subId);
3248 } else {
3249 Log.w(TAG, "Not returning plans because caller " + callingPackage
3250 + " doesn't match owner " + ownerPackage);
3251 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003252 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003253 }
3254 }
3255
3256 @Override
3257 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3258 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3259
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003260 for (SubscriptionPlan plan : plans) {
3261 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003262 }
3263
3264 final long token = Binder.clearCallingIdentity();
3265 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003266 synchronized (mUidRulesFirstLock) {
3267 synchronized (mNetworkPoliciesSecondLock) {
3268 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003269 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003270
Jeff Sharkey146bb332018-04-18 15:42:57 -06003271 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3272 if (subscriberId != null) {
3273 ensureActiveMobilePolicyAL(subId, subscriberId);
3274 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3275 } else {
3276 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3277 }
3278
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003279 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003280 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003281 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003282
3283 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3284 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3285 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3286 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003287 } finally {
3288 Binder.restoreCallingIdentity(token);
3289 }
3290 }
3291
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003292 /**
3293 * Only visible for testing purposes. This doesn't give any access to
3294 * existing plans; it simply lets the debug package define new plans.
3295 */
3296 void setSubscriptionPlansOwner(int subId, String packageName) {
3297 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3298 }
3299
Jeff Sharkey53313d72017-07-13 16:47:32 -06003300 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003301 public String getSubscriptionPlansOwner(int subId) {
3302 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3303 throw new SecurityException();
3304 }
3305
3306 synchronized (mNetworkPoliciesSecondLock) {
3307 return mSubscriptionPlansOwner.get(subId);
3308 }
3309 }
3310
3311 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003312 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3313 long timeoutMillis, String callingPackage) {
3314 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3315
3316 // We can only override when carrier told us about plans
3317 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003318 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3319 if (plan == null
3320 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003321 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003322 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003323 }
3324 }
3325
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003326 // Only allow overrides when feature is enabled. However, we always
3327 // allow disabling of overrides for safety reasons.
3328 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3329 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3330 if (overrideEnabled || overrideValue == 0) {
3331 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3332 overrideMask, overrideValue, subId));
3333 if (timeoutMillis > 0) {
3334 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3335 overrideMask, 0, subId), timeoutMillis);
3336 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003337 }
3338 }
3339
3340 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003341 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003342 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003343
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003344 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3345
Dianne Hackborn497175b2014-07-01 12:56:08 -07003346 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003347 for (String arg : args) {
3348 argSet.add(arg);
3349 }
3350
Felipe Lemef0823852016-06-08 13:43:08 -07003351 synchronized (mUidRulesFirstLock) {
3352 synchronized (mNetworkPoliciesSecondLock) {
3353 if (argSet.contains("--unsnooze")) {
3354 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3355 mNetworkPolicy.valueAt(i).clearSnooze();
3356 }
3357
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003358 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003359
3360 fout.println("Cleared snooze timestamps");
3361 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003362 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003363
Felipe Lemef0823852016-06-08 13:43:08 -07003364 fout.print("System ready: "); fout.println(mSystemReady);
3365 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3366 fout.print("Restrict power: "); fout.println(mRestrictPower);
3367 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003368 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3369
3370 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003371 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003372 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003373 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3374 fout.println(mNetworkPolicy.valueAt(i).toString());
3375 }
3376 fout.decreaseIndent();
3377
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003378 fout.println();
3379 fout.println("Subscription plans:");
3380 fout.increaseIndent();
3381 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3382 final int subId = mSubscriptionPlans.keyAt(i);
3383 fout.println("Subscriber ID " + subId + ":");
3384 fout.increaseIndent();
3385 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3386 if (!ArrayUtils.isEmpty(plans)) {
3387 for (SubscriptionPlan plan : plans) {
3388 fout.println(plan);
3389 }
3390 }
3391 fout.decreaseIndent();
3392 }
3393 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003394
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003395 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003396 fout.println("Active subscriptions:");
3397 fout.increaseIndent();
3398 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3399 final int subId = mSubIdToSubscriberId.keyAt(i);
3400 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3401
3402 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3403 }
3404 fout.decreaseIndent();
3405
3406 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003407 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3408 fout.println("Merged subscriptions: " + Arrays.toString(
3409 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3410 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003411
3412 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003413 fout.println("Policy for UIDs:");
3414 fout.increaseIndent();
3415 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003416 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003417 final int uid = mUidPolicy.keyAt(i);
3418 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003419 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003420 fout.print(uid);
3421 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003422 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003423 fout.println();
3424 }
3425 fout.decreaseIndent();
3426
3427 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3428 if (size > 0) {
3429 fout.println("Power save whitelist (except idle) app ids:");
3430 fout.increaseIndent();
3431 for (int i = 0; i < size; i++) {
3432 fout.print("UID=");
3433 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3434 fout.print(": ");
3435 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3436 fout.println();
3437 }
3438 fout.decreaseIndent();
3439 }
3440
3441 size = mPowerSaveWhitelistAppIds.size();
3442 if (size > 0) {
3443 fout.println("Power save whitelist app ids:");
3444 fout.increaseIndent();
3445 for (int i = 0; i < size; i++) {
3446 fout.print("UID=");
3447 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3448 fout.print(": ");
3449 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3450 fout.println();
3451 }
3452 fout.decreaseIndent();
3453 }
3454
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003455 size = mAppIdleTempWhitelistAppIds.size();
3456 if (size > 0) {
3457 fout.println("App idle whitelist app ids:");
3458 fout.increaseIndent();
3459 for (int i = 0; i < size; i++) {
3460 fout.print("UID=");
3461 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3462 fout.print(": ");
3463 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3464 fout.println();
3465 }
3466 fout.decreaseIndent();
3467 }
3468
Felipe Lemef0823852016-06-08 13:43:08 -07003469 size = mDefaultRestrictBackgroundWhitelistUids.size();
3470 if (size > 0) {
3471 fout.println("Default restrict background whitelist uids:");
3472 fout.increaseIndent();
3473 for (int i = 0; i < size; i++) {
3474 fout.print("UID=");
3475 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3476 fout.println();
3477 }
3478 fout.decreaseIndent();
3479 }
3480
3481 size = mRestrictBackgroundWhitelistRevokedUids.size();
3482 if (size > 0) {
3483 fout.println("Default restrict background whitelist uids revoked by users:");
3484 fout.increaseIndent();
3485 for (int i = 0; i < size; i++) {
3486 fout.print("UID=");
3487 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3488 fout.println();
3489 }
3490 fout.decreaseIndent();
3491 }
3492
3493 final SparseBooleanArray knownUids = new SparseBooleanArray();
3494 collectKeys(mUidState, knownUids);
3495 collectKeys(mUidRules, knownUids);
3496
3497 fout.println("Status for all known UIDs:");
3498 fout.increaseIndent();
3499 size = knownUids.size();
3500 for (int i = 0; i < size; i++) {
3501 final int uid = knownUids.keyAt(i);
3502 fout.print("UID=");
3503 fout.print(uid);
3504
3505 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3506 fout.print(" state=");
3507 fout.print(state);
3508 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3509 fout.print(" (fg)");
3510 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003511 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003512 ? " (fg svc)" : " (bg)");
3513 }
3514
3515 final int uidRules = mUidRules.get(uid, RULE_NONE);
3516 fout.print(" rules=");
3517 fout.print(uidRulesToString(uidRules));
3518 fout.println();
3519 }
3520 fout.decreaseIndent();
3521
3522 fout.println("Status for just UIDs with rules:");
3523 fout.increaseIndent();
3524 size = mUidRules.size();
3525 for (int i = 0; i < size; i++) {
3526 final int uid = mUidRules.keyAt(i);
3527 fout.print("UID=");
3528 fout.print(uid);
3529 final int uidRules = mUidRules.get(uid, RULE_NONE);
3530 fout.print(" rules=");
3531 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003532 fout.println();
3533 }
3534 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003535
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003536 fout.println("Admin restricted uids for metered data:");
3537 fout.increaseIndent();
3538 size = mMeteredRestrictedUids.size();
3539 for (int i = 0; i < size; ++i) {
3540 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3541 fout.println(mMeteredRestrictedUids.valueAt(i));
3542 }
3543 fout.decreaseIndent();
3544
Makoto Onuki49392d32018-04-11 13:51:02 -07003545 fout.println();
3546 mStatLogger.dump(fout);
3547
Sudheer Shanka352dc572017-09-22 17:09:38 -07003548 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003549 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003550 }
3551 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003552
3553 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003554 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003555 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003556 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003557 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003558 }
3559
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003560 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003561 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003562 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003563 return isUidStateForeground(
3564 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003565 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003566 }
3567
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003568 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003569 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003570 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003571 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003572 }
3573
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003574 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003575 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003576 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3577 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3578 }
3579
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003580 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003581 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003582 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003583 }
3584
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003585 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003586 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003587 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003588 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003589 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003590 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003591 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003592 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3593 try {
3594 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3595 if (oldUidState != uidState) {
3596 // state changed, push updated rules
3597 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003598 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3599 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3600 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003601 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003602 if (mDeviceIdleMode) {
3603 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003604 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003605 if (mRestrictPower) {
3606 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003607 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003608 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003609 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003610 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003611 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003612 } finally {
3613 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003614 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003615 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003616 }
3617
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003618 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003619 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003620 final int index = mUidState.indexOfKey(uid);
3621 if (index >= 0) {
3622 final int oldUidState = mUidState.valueAt(index);
3623 mUidState.removeAt(index);
3624 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003625 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003626 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003627 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003628 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003629 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003630 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003631 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003632 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003633 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003634 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003635 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003636 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003637 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003638 }
3639
Felipe Lemef28983d2016-03-25 12:18:23 -07003640 // adjust stats accounting based on foreground status
3641 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003642 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3643 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3644 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3645 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003646 try {
3647 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003648 } finally {
3649 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003650 }
3651 }
3652
Sudheer Shankac9d94072017-02-22 22:13:55 +00003653 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3654 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003655 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003656 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003657 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003658 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003659 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003660 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003661 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003662 }
3663
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003664 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003665 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003666 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3667 try {
3668 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3669 mUidFirewallPowerSaveRules);
3670 } finally {
3671 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3672 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003673 }
3674
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003675 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003676 void updateRuleForRestrictPowerUL(int uid) {
3677 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003678 }
3679
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003680 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003681 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003682 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3683 try {
3684 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3685 mUidFirewallDozableRules);
3686 } finally {
3687 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3688 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003689 }
3690
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003691 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003692 void updateRuleForDeviceIdleUL(int uid) {
3693 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003694 }
3695
Felipe Lemef28983d2016-03-25 12:18:23 -07003696 // NOTE: since both fw_dozable and fw_powersave uses the same map
3697 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003698 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003699 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003700 SparseIntArray rules) {
3701 if (enabled) {
3702 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003703 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003704 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003705 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003706 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003707 for (int ui = users.size() - 1; ui >= 0; ui--) {
3708 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003709 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3710 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3711 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3712 updateRulesForWhitelistedAppIds(uidRules,
3713 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003714 }
3715 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003716 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003717 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003718 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3719 }
3720 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003721 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003722 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003723 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003724 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003725 }
3726
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003727 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3728 final SparseBooleanArray whitelistedAppIds, int userId) {
3729 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3730 if (whitelistedAppIds.valueAt(i)) {
3731 final int appId = whitelistedAppIds.keyAt(i);
3732 final int uid = UserHandle.getUid(userId, appId);
3733 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3734 }
3735 }
3736 }
3737
3738 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003739 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3740 * mode, and app idle).
3741 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003742 * @param deviceIdleMode if true then we don't consider
3743 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3744 * whitelisted.
3745 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003746 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003747 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003748 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003749 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3750 || mPowerSaveWhitelistAppIds.get(appId);
3751 if (!deviceIdleMode) {
3752 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3753 }
3754 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003755 }
3756
Felipe Lemef28983d2016-03-25 12:18:23 -07003757 // NOTE: since both fw_dozable and fw_powersave uses the same map
3758 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003759 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003760 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003761 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003762 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003763 chain == FIREWALL_CHAIN_DOZABLE);
3764 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003765 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003766 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003767 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003768 }
3769 }
3770 }
3771
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003772 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003773 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003774 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3775 try {
3776 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3777 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003778
Felipe Leme873a83a2016-09-07 11:34:10 -07003779 // Fully update the app idle firewall chain.
3780 final List<UserInfo> users = mUserManager.getUsers();
3781 for (int ui = users.size() - 1; ui >= 0; ui--) {
3782 UserInfo user = users.get(ui);
3783 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3784 for (int uid : idleUids) {
3785 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3786 // quick check: if this uid doesn't have INTERNET permission, it
3787 // doesn't have network access anyway, so it is a waste to mess
3788 // with it here.
3789 if (hasInternetPermissions(uid)) {
3790 uidRules.put(uid, FIREWALL_RULE_DENY);
3791 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003792 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003793 }
3794 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003795
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003796 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003797 } finally {
3798 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3799 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003800 }
3801
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003802 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003803 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003804 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003805
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003806 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3807 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3808 }
3809 try {
3810 int appId = UserHandle.getAppId(uid);
3811 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3812 && !isUidForegroundOnRestrictPowerUL(uid)) {
3813 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003814 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003815 } else {
3816 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003817 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003818 }
3819 } finally {
3820 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003821 }
3822 }
3823
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003824 /**
3825 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3826 * changed.
3827 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003828 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003829 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003830 boolean paroled = mUsageStats.isAppIdleParoleOn();
3831 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003832 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003833
3834 int ruleCount = mUidFirewallStandbyRules.size();
3835 for (int i = 0; i < ruleCount; i++) {
3836 int uid = mUidFirewallStandbyRules.keyAt(i);
3837 int oldRules = mUidRules.get(uid);
3838 if (enableChain) {
3839 // Chain wasn't enabled before and the other power-related
3840 // chains are whitelists, so we can clear the
3841 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3842 // the effective rules result in blocking network access.
3843 oldRules &= MASK_METERED_NETWORKS;
3844 } else {
3845 // Skip if it had no restrictions to begin with
3846 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3847 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003848 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3849 if (newUidRules == RULE_NONE) {
3850 mUidRules.delete(uid);
3851 } else {
3852 mUidRules.put(uid, newUidRules);
3853 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003854 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003855 }
3856
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003857 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003858 * Update rules that might be changed by {@link #mRestrictBackground},
3859 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003860 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003861 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003862 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003863 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3864 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3865 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3866 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003867 try {
Felipe Leme09700462016-09-08 09:33:48 -07003868 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003869 updateRulesForRestrictPowerUL();
3870 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003871
Felipe Leme873a83a2016-09-07 11:34:10 -07003872 // If the set of restricted networks may have changed, re-evaluate those.
3873 if (restrictedNetworksChanged) {
3874 normalizePoliciesNL();
3875 updateNetworkRulesNL();
3876 }
3877 } finally {
3878 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003879 }
3880 }
3881
Felipe Leme09700462016-09-08 09:33:48 -07003882 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003883 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003884 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003885 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3886 try {
3887 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003888 updateRulesForPowerSaveUL();
3889 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3890 } finally {
3891 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3892 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003893 }
3894
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003895 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003896 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003897 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3898 try {
3899 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3900 } finally {
3901 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3902 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003903 }
3904
3905 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3906 private static final int TYPE_RESTRICT_POWER = 2;
3907 @Retention(RetentionPolicy.SOURCE)
3908 @IntDef(flag = false, value = {
3909 TYPE_RESTRICT_BACKGROUND,
3910 TYPE_RESTRICT_POWER,
3911 })
3912 public @interface RestrictType {
3913 }
3914
3915 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003916 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003917 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003918 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3919 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3920 }
3921 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003922 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003923
3924 final PackageManager pm = mContext.getPackageManager();
3925 final List<UserInfo> users;
3926 final List<ApplicationInfo> apps;
3927
3928 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3929 try {
3930 users = mUserManager.getUsers();
3931 } finally {
3932 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3933 }
3934 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3935 try {
3936 apps = pm.getInstalledApplications(
3937 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3938 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3939 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3940 } finally {
3941 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3942 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003943
Felipe Leme873a83a2016-09-07 11:34:10 -07003944 final int usersSize = users.size();
3945 final int appsSize = apps.size();
3946 for (int i = 0; i < usersSize; i++) {
3947 final UserInfo user = users.get(i);
3948 for (int j = 0; j < appsSize; j++) {
3949 final ApplicationInfo app = apps.get(j);
3950 final int uid = UserHandle.getUid(user.id, app.uid);
3951 switch (type) {
3952 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003953 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003954 break;
3955 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003956 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003957 break;
3958 default:
3959 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3960 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003961 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003962 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003963 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003964 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003965 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003966 }
3967
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003968 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003969 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003970 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003971 final int numUsers = users.size();
3972 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003973 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003974 int uid = UserHandle.getUid(user.id, appId);
3975 // Update external firewall rules.
3976 updateRuleForAppIdleUL(uid);
3977 updateRuleForDeviceIdleUL(uid);
3978 updateRuleForRestrictPowerUL(uid);
3979 // Update internal rules.
3980 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003981 }
3982 }
3983
Felipe Leme70c57c22016-03-29 10:45:13 -07003984 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3985 // methods below could be merged into a isUidValidForRules() method.
3986 private boolean isUidValidForBlacklistRules(int uid) {
3987 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003988 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003989 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003990 return true;
3991 }
3992
3993 return false;
3994 }
3995
Felipe Leme70c57c22016-03-29 10:45:13 -07003996 private boolean isUidValidForWhitelistRules(int uid) {
3997 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3998 }
3999
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004000 /**
4001 * Set whether or not an app should be whitelisted for network access while in app idle. Other
4002 * power saving restrictions may still apply.
4003 */
4004 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004005 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08004006 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4007
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004008 synchronized (mUidRulesFirstLock) {
4009 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
4010 // No change.
4011 return;
4012 }
4013
4014 final long token = Binder.clearCallingIdentity();
4015 try {
4016 mLogger.appIdleWlChanged(uid, shouldWhitelist);
4017 if (shouldWhitelist) {
4018 mAppIdleTempWhitelistAppIds.put(uid, true);
4019 } else {
4020 mAppIdleTempWhitelistAppIds.delete(uid);
4021 }
4022 updateRuleForAppIdleUL(uid);
4023 updateRulesForPowerRestrictionsUL(uid);
4024 } finally {
4025 Binder.restoreCallingIdentity(token);
4026 }
4027 }
4028 }
4029
4030 /** Return the list of UIDs currently in the app idle whitelist. */
4031 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004032 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004033 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4034
4035 synchronized (mUidRulesFirstLock) {
4036 final int len = mAppIdleTempWhitelistAppIds.size();
4037 int[] uids = new int[len];
4038 for (int i = 0; i < len; ++i) {
4039 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4040 }
4041 return uids;
4042 }
4043 }
4044
4045 /** Returns if the UID is currently considered idle. */
4046 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004047 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004048 synchronized (mUidRulesFirstLock) {
4049 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4050 // UID is temporarily whitelisted.
4051 return false;
4052 }
4053 }
4054
Amith Yamasani15e472352015-04-24 19:06:07 -07004055 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4056 final int userId = UserHandle.getUserId(uid);
4057
songjinshi0655edd2016-05-18 19:55:32 +08004058 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004059 for (String packageName : packages) {
4060 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4061 return false;
4062 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004063 }
4064 }
4065 return true;
4066 }
4067
4068 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004069 * Checks if an uid has INTERNET permissions.
4070 * <p>
4071 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004072 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004073 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004074 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004075 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004076 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004077 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004078 }
4079 } catch (RemoteException e) {
4080 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004081 return true;
4082 }
4083
4084 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004085 * Clears all state - internal and external - associated with an UID.
4086 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004087 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004088 private void onUidDeletedUL(int uid) {
4089 // First cleanup in-memory state synchronously...
4090 mUidRules.delete(uid);
4091 mUidPolicy.delete(uid);
4092 mUidFirewallStandbyRules.delete(uid);
4093 mUidFirewallDozableRules.delete(uid);
4094 mUidFirewallPowerSaveRules.delete(uid);
4095 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4096 mPowerSaveWhitelistAppIds.delete(uid);
4097 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004098 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004099
4100 // ...then update iptables asynchronously.
4101 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4102 }
4103
4104 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004105 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004106 *
Felipe Leme781ba142016-05-09 16:24:48 -07004107 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004108 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004109 * <li>Doze mode
4110 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004111 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004112 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004113 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004114 *
4115 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004116 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004117 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004118 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004119 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004120 updateRuleForDeviceIdleUL(uid);
4121 updateRuleForAppIdleUL(uid);
4122 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004123
4124 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004125 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004126
4127 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004128 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004129 }
4130
Felipe Leme70c57c22016-03-29 10:45:13 -07004131 /**
4132 * Applies network rules to bandwidth controllers based on process state and user-defined
4133 * restrictions (blacklist / whitelist).
4134 *
4135 * <p>
4136 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4137 * networks:
4138 * <ul>
4139 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4140 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4141 * also blacklisted.
4142 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004143 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004144 * <ul>
4145 *
4146 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4147 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4148 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4149 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004150 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004151 * {@link INetworkManagementService}, but this method should also be called in events (like
4152 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4153 * following rules should also be applied:
4154 *
4155 * <ul>
4156 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4157 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4158 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4159 * {@code bw_penalty_box}.
4160 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4161 * </ul>
4162 *
4163 * <p>For optimization, the rules are only applied on user apps that have internet access
4164 * permission, since there is no need to change the {@code iptables} rule if the app does not
4165 * have permission to use the internet.
4166 *
4167 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004168 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004169 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004170 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004171 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4172 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4173 "updateRulesForDataUsageRestrictionsUL: " + uid);
4174 }
4175 try {
4176 updateRulesForDataUsageRestrictionsULInner(uid);
4177 } finally {
4178 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4179 }
4180 }
4181
4182 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004183 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004184 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004185 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004186 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004187
Dianne Hackborn497175b2014-07-01 12:56:08 -07004188 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004189 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004190 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004191 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004192
Felipe Leme781ba142016-05-09 16:24:48 -07004193 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004194 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004195 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4196 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004197
Felipe Leme70c57c22016-03-29 10:45:13 -07004198 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004199 if (isRestrictedByAdmin) {
4200 newRule = RULE_REJECT_METERED;
4201 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004202 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4203 newRule = RULE_TEMPORARY_ALLOW_METERED;
4204 } else if (isWhitelisted) {
4205 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004206 }
4207 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004208 if (isBlacklisted) {
4209 newRule = RULE_REJECT_METERED;
4210 } else if (mRestrictBackground && isWhitelisted) {
4211 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004212 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004213 }
Felipe Leme781ba142016-05-09 16:24:48 -07004214 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004215
Felipe Lemef28983d2016-03-25 12:18:23 -07004216 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004217 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004218 + ": isForeground=" +isForeground
4219 + ", isBlacklisted=" + isBlacklisted
4220 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004221 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004222 + ", oldRule=" + uidRulesToString(oldRule)
4223 + ", newRule=" + uidRulesToString(newRule)
4224 + ", newUidRules=" + uidRulesToString(newUidRules)
4225 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004226 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004227
Felipe Leme46c4fc32016-05-04 09:21:43 -07004228 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004229 mUidRules.delete(uid);
4230 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004231 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004232 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004233
Felipe Leme70c57c22016-03-29 10:45:13 -07004234 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004235 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004236 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004237 // Temporarily whitelist foreground app, removing from blacklist if necessary
4238 // (since bw_penalty_box prevails over bw_happy_box).
4239
4240 setMeteredNetworkWhitelist(uid, true);
4241 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4242 // but ideally it should be just:
4243 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004244 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004245 setMeteredNetworkBlacklist(uid, false);
4246 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004247 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004248 // Remove temporary whitelist from app that is not on foreground anymore.
4249
4250 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4251 // but ideally they should be just:
4252 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4253 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004254 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004255 setMeteredNetworkWhitelist(uid, false);
4256 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004257 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004258 setMeteredNetworkBlacklist(uid, true);
4259 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004260 } else if (hasRule(newRule, RULE_REJECT_METERED)
4261 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004262 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004263 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004264 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004265 // Since blacklist prevails over whitelist, we need to handle the special case
4266 // where app is whitelisted and blacklisted at the same time (although such
4267 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004268 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004269 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004270 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4271 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004272 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004273 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004274 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004275 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004276 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4277 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004278 + ", whitelisted=" + isWhitelisted
4279 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004280 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004281 + ", newRule=" + uidRulesToString(newUidRules)
4282 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004283 }
Felipe Leme781ba142016-05-09 16:24:48 -07004284
Sudheer Shankac9d94072017-02-22 22:13:55 +00004285 // Dispatch changed rule to existing listeners.
4286 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004287 }
4288 }
4289
4290 /**
4291 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4292 * listeners in case of change.
4293 * <p>
4294 * There are 3 power-related rules that affects whether an app has background access on
4295 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4296 * restriction, it's added to the equivalent firewall chain:
4297 * <ul>
4298 * <li>App is idle: {@code fw_standby} firewall chain.
4299 * <li>Device is idle: {@code fw_dozable} firewall chain.
4300 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4301 * </ul>
4302 * <p>
4303 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4304 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4305 * <p>
4306 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4307 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004308 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004309 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004310 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4311
Sudheer Shankac9d94072017-02-22 22:13:55 +00004312 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004313
Sudheer Shankac9d94072017-02-22 22:13:55 +00004314 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004315 mUidRules.delete(uid);
4316 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004317 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004318 }
4319 }
4320
4321 /**
4322 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4323 *
4324 * @param uid the uid of the app to update rules for
4325 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4326 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4327 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004328 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004329 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004330 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004331 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4332 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4333 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4334 + (paroled ? "P" : "-"));
4335 }
4336 try {
4337 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4338 } finally {
4339 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4340 }
4341 }
4342
4343 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004344 if (!isUidValidForBlacklistRules(uid)) {
4345 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004346 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004347 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004348
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004349 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004350 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004351 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004352
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004353 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004354 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4355 int newRule = RULE_NONE;
4356
4357 // First step: define the new rule based on user restrictions and foreground state.
4358
4359 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4360 // by considering the foreground and non-foreground states.
4361 if (isForeground) {
4362 if (restrictMode) {
4363 newRule = RULE_ALLOW_ALL;
4364 }
4365 } else if (restrictMode) {
4366 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4367 }
4368
4369 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4370
4371 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004372 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004373 + ", isIdle: " + isIdle
4374 + ", mRestrictPower: " + mRestrictPower
4375 + ", mDeviceIdleMode: " + mDeviceIdleMode
4376 + ", isForeground=" + isForeground
4377 + ", isWhitelisted=" + isWhitelisted
4378 + ", oldRule=" + uidRulesToString(oldRule)
4379 + ", newRule=" + uidRulesToString(newRule)
4380 + ", newUidRules=" + uidRulesToString(newUidRules)
4381 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4382 }
4383
Felipe Leme781ba142016-05-09 16:24:48 -07004384 // Second step: notify listeners if state changed.
4385 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004386 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004387 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004388 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004389 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4390 } else {
4391 // All scenarios should have been covered above
4392 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4393 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004394 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004395 + ", newRule=" + uidRulesToString(newUidRules)
4396 + ", oldRule=" + uidRulesToString(oldUidRules));
4397 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004398 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004399 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004400
Sudheer Shankac9d94072017-02-22 22:13:55 +00004401 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004402 }
4403
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004404 private class AppIdleStateChangeListener
4405 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4406
4407 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004408 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4409 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004410 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004411 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4412 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004413 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004414 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004415 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004416 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004417 }
4418 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004419 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004420 }
4421
4422 @Override
4423 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004424 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004425 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004426 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004427 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004428 }
4429 }
4430
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004431 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4432 if (listener != null) {
4433 try {
4434 listener.onUidRulesChanged(uid, uidRules);
4435 } catch (RemoteException ignored) {
4436 }
4437 }
4438 }
4439
4440 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4441 String[] meteredIfaces) {
4442 if (listener != null) {
4443 try {
4444 listener.onMeteredIfacesChanged(meteredIfaces);
4445 } catch (RemoteException ignored) {
4446 }
4447 }
4448 }
4449
4450 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4451 boolean restrictBackground) {
4452 if (listener != null) {
4453 try {
4454 listener.onRestrictBackgroundChanged(restrictBackground);
4455 } catch (RemoteException ignored) {
4456 }
4457 }
4458 }
4459
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004460 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4461 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004462 if (listener != null) {
4463 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004464 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004465 } catch (RemoteException ignored) {
4466 }
4467 }
4468 }
4469
Jeff Sharkey9252b342018-01-19 07:58:35 +09004470 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4471 int overrideMask, int overrideValue) {
4472 if (listener != null) {
4473 try {
4474 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4475 } catch (RemoteException ignored) {
4476 }
4477 }
4478 }
4479
Makoto Onuki8e777332017-03-28 11:25:47 -07004480 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004481 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004482 public boolean handleMessage(Message msg) {
4483 switch (msg.what) {
4484 case MSG_RULES_CHANGED: {
4485 final int uid = msg.arg1;
4486 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004487 final int length = mListeners.beginBroadcast();
4488 for (int i = 0; i < length; i++) {
4489 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4490 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004491 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004492 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004493 return true;
4494 }
4495 case MSG_METERED_IFACES_CHANGED: {
4496 final String[] meteredIfaces = (String[]) msg.obj;
4497 final int length = mListeners.beginBroadcast();
4498 for (int i = 0; i < length; i++) {
4499 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004500 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004501 }
4502 mListeners.finishBroadcast();
4503 return true;
4504 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004505 case MSG_LIMIT_REACHED: {
4506 final String iface = (String) msg.obj;
4507
Felipe Lemef0823852016-06-08 13:43:08 -07004508 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004509 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004510 // force stats update to make sure we have
4511 // numbers that caused alert to trigger.
4512 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004513
Felipe Lemef0823852016-06-08 13:43:08 -07004514 updateNetworkEnabledNL();
4515 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004516 }
4517 }
4518 return true;
4519 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004520 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4521 final boolean restrictBackground = msg.arg1 != 0;
4522 final int length = mListeners.beginBroadcast();
4523 for (int i = 0; i < length; i++) {
4524 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004525 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004526 }
4527 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004528 final Intent intent =
4529 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4530 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4531 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4532 return true;
4533 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004534 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004535 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004536 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004537 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004538 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004539 final int length = mListeners.beginBroadcast();
4540 for (int i = 0; i < length; i++) {
4541 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004542 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004543 }
4544 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004545 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4546 if (notifyApp.booleanValue()) {
4547 broadcastRestrictBackgroundChanged(uid, notifyApp);
4548 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004549 return true;
4550 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004551 case MSG_ADVISE_PERSIST_THRESHOLD: {
4552 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004553 // make sure stats are recorded frequently enough; we aim
4554 // for 2MB threshold for 2GB/month rules.
4555 final long persistThreshold = lowestRule / 1000;
4556 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004557 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004558 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004559 case MSG_UPDATE_INTERFACE_QUOTA: {
4560 removeInterfaceQuota((String) msg.obj);
4561 // int params need to be stitched back into a long
4562 setInterfaceQuota((String) msg.obj,
4563 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4564 return true;
4565 }
4566 case MSG_REMOVE_INTERFACE_QUOTA: {
4567 removeInterfaceQuota((String) msg.obj);
4568 return true;
4569 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004570 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4571 resetUidFirewallRules(msg.arg1);
4572 return true;
4573 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004574 case MSG_SUBSCRIPTION_OVERRIDE: {
4575 final int overrideMask = msg.arg1;
4576 final int overrideValue = msg.arg2;
4577 final int subId = (int) msg.obj;
4578 final int length = mListeners.beginBroadcast();
4579 for (int i = 0; i < length; i++) {
4580 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4581 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4582 }
4583 mListeners.finishBroadcast();
4584 return true;
4585 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004586 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4587 final int userId = msg.arg1;
4588 final Set<String> packageNames = (Set<String>) msg.obj;
4589 setMeteredRestrictedPackagesInternal(packageNames, userId);
4590 return true;
4591 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004592 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4593 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4594 final boolean enabled = msg.arg1 != 0;
4595 setNetworkTemplateEnabledInner(template, enabled);
4596 return true;
4597 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004598 default: {
4599 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004600 }
4601 }
4602 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004603 };
4604
4605 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4606 @Override
4607 public boolean handleMessage(Message msg) {
4608 switch (msg.what) {
4609 case UID_MSG_STATE_CHANGED: {
4610 final int uid = msg.arg1;
4611 final int procState = msg.arg2;
4612 final long procStateSeq = (Long) msg.obj;
4613
4614 handleUidChanged(uid, procState, procStateSeq);
4615 return true;
4616 }
4617 case UID_MSG_GONE: {
4618 final int uid = msg.arg1;
4619 handleUidGone(uid);
4620 return true;
4621 }
4622 default: {
4623 return false;
4624 }
4625 }
4626 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004627 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004628
Makoto Onuki8e777332017-03-28 11:25:47 -07004629 void handleUidChanged(int uid, int procState, long procStateSeq) {
4630 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4631 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004632 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004633 synchronized (mUidRulesFirstLock) {
4634 // We received a uid state change callback, add it to the history so that it
4635 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004636 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004637 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004638 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004639 // Updating the network rules is done, so notify AMS about this.
4640 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4641 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004642 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4643 // called from the handler, so there's no multi-threading issue.
4644 if (updated) {
4645 updateNetworkStats(uid, isUidStateForeground(procState));
4646 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004647 } finally {
4648 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4649 }
4650 }
4651
4652 void handleUidGone(int uid) {
4653 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4654 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004655 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004656 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004657 updated = removeUidStateUL(uid);
4658 }
4659 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4660 // called from the handler, so there's no multi-threading issue.
4661 if (updated) {
4662 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004663 }
4664 } finally {
4665 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4666 }
4667 }
4668
Felipe Leme57e3d312016-08-23 14:42:52 -07004669 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4670 final PackageManager pm = mContext.getPackageManager();
4671 final String[] packages = pm.getPackagesForUid(uid);
4672 if (packages != null) {
4673 final int userId = UserHandle.getUserId(uid);
4674 for (String packageName : packages) {
4675 final Intent intent =
4676 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4677 intent.setPackage(packageName);
4678 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4679 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4680 }
4681 }
4682 }
4683
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004684 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4685 // long quotaBytes split up into two ints to fit in message
4686 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4687 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4688 }
4689
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004690 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004691 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004692 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004693 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004694 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004695 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004696 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004697 }
4698 }
4699
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004700 private void removeInterfaceQuotaAsync(String iface) {
4701 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4702 }
4703
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004704 private void removeInterfaceQuota(String iface) {
4705 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004706 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004707 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004708 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004709 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004710 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004711 }
4712 }
4713
Felipe Leme70c57c22016-03-29 10:45:13 -07004714 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4715 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004716 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004717 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004718 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004719 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4720 } catch (RemoteException e) {
4721 // ignored; service lives in system_server
4722 }
4723 }
4724
4725 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4726 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4727 try {
4728 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4729 } catch (IllegalStateException e) {
4730 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004731 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004732 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004733 }
4734 }
4735
Felipe Lemebc853dd2016-09-08 13:26:55 -07004736 private static final int CHAIN_TOGGLE_NONE = 0;
4737 private static final int CHAIN_TOGGLE_ENABLE = 1;
4738 private static final int CHAIN_TOGGLE_DISABLE = 2;
4739 @Retention(RetentionPolicy.SOURCE)
4740 @IntDef(flag = false, value = {
4741 CHAIN_TOGGLE_NONE,
4742 CHAIN_TOGGLE_ENABLE,
4743 CHAIN_TOGGLE_DISABLE
4744 })
4745 public @interface ChainToggleType {
4746 }
4747
4748 /**
4749 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004750 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004751 *
4752 * @param chain firewall chain.
4753 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4754 * @param toggle whether the chain should be enabled, disabled, or not changed.
4755 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004756 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004757 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004758 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004759 if (uidRules != null) {
4760 setUidFirewallRulesUL(chain, uidRules);
4761 }
4762 if (toggle != CHAIN_TOGGLE_NONE) {
4763 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4764 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004765 }
4766
Amith Yamasani15e472352015-04-24 19:06:07 -07004767 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004768 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4769 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4770 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004771 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004772 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004773 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004774 int size = uidRules.size();
4775 int[] uids = new int[size];
4776 int[] rules = new int[size];
4777 for(int index = size - 1; index >= 0; --index) {
4778 uids[index] = uidRules.keyAt(index);
4779 rules[index] = uidRules.valueAt(index);
4780 }
4781 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004782 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004783 } catch (IllegalStateException e) {
4784 Log.wtf(TAG, "problem setting firewall uid rules", e);
4785 } catch (RemoteException e) {
4786 // ignored; service lives in system_server
4787 }
4788 }
4789
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004790 /**
4791 * Add or remove a uid to the firewall blacklist for all network ifaces.
4792 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004793 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004794 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4795 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4796 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004797 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004798 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004799 if (chain == FIREWALL_CHAIN_DOZABLE) {
4800 mUidFirewallDozableRules.put(uid, rule);
4801 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4802 mUidFirewallStandbyRules.put(uid, rule);
4803 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4804 mUidFirewallPowerSaveRules.put(uid, rule);
4805 }
4806
4807 try {
4808 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004809 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004810 } catch (IllegalStateException e) {
4811 Log.wtf(TAG, "problem setting firewall uid rules", e);
4812 } catch (RemoteException e) {
4813 // ignored; service lives in system_server
4814 }
4815 } finally {
4816 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004817 }
4818 }
4819
4820 /**
4821 * Add or remove a uid to the firewall blacklist for all network ifaces.
4822 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004823 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004824 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004825 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4826 mFirewallChainStates.get(chain) == enable) {
4827 // All is the same, nothing to do.
4828 return;
4829 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004830 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004831 try {
4832 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004833 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004834 } catch (IllegalStateException e) {
4835 Log.wtf(TAG, "problem enable firewall chain", e);
4836 } catch (RemoteException e) {
4837 // ignored; service lives in system_server
4838 }
4839 }
4840
Felipe Leme03e95e22016-09-09 09:25:31 -07004841 /**
4842 * Resets all firewall rules associated with an UID.
4843 */
4844 private void resetUidFirewallRules(int uid) {
4845 try {
4846 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4847 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4848 mNetworkManager
4849 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4850 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4851 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4852 } catch (IllegalStateException e) {
4853 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4854 } catch (RemoteException e) {
4855 // ignored; service lives in system_server
4856 }
4857 }
4858
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004859 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004860 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004861 return getNetworkTotalBytes(template, start, end);
4862 }
4863
4864 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004865 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004866 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004867 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004868 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004869 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004870 }
4871 }
4872
4873 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4874 try {
4875 return mNetworkStats.getNetworkUidBytes(template, start, end);
4876 } catch (RuntimeException e) {
4877 Slog.w(TAG, "Failed to read network stats: " + e);
4878 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004879 }
4880 }
4881
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004882 private boolean isBandwidthControlEnabled() {
4883 final long token = Binder.clearCallingIdentity();
4884 try {
4885 return mNetworkManager.isBandwidthControlEnabled();
4886 } catch (RemoteException e) {
4887 // ignored; service lives in system_server
4888 return false;
4889 } finally {
4890 Binder.restoreCallingIdentity(token);
4891 }
4892 }
4893
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004894 private static Intent buildAllowBackgroundDataIntent() {
4895 return new Intent(ACTION_ALLOW_BACKGROUND);
4896 }
4897
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004898 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4899 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004900 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4901 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4902 return intent;
4903 }
4904
4905 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4906 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4907 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004908 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4909 return intent;
4910 }
4911
Wei Liu546cb772016-07-21 16:19:01 -07004912 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004913 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004914 intent.setComponent(ComponentName.unflattenFromString(
4915 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004916 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4917 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4918 return intent;
4919 }
4920
Wei Liu546cb772016-07-21 16:19:01 -07004921 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004922 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004923 intent.setComponent(ComponentName.unflattenFromString(
4924 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004925 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4926 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4927 return intent;
4928 }
4929
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004930 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004931 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004932 mHandler.getLooper().getQueue().addIdleHandler(handler);
4933 }
4934
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004935 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004936 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004937 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004938 mRestrictBackgroundPowerState = result;
4939
4940 boolean restrictBackground = result.batterySaverEnabled;
4941 boolean shouldInvokeRestrictBackground;
4942 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4943 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4944
4945 if (result.globalBatterySaverEnabled) {
4946 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4947 // turn it on.
4948 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4949 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4950 localRestrictBgChangedInBsm = false;
4951 } else {
4952 // Try to restore the restrictBackground if it doesn't change in bsm
4953 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4954 restrictBackground = mRestrictBackgroundBeforeBsm;
4955 }
4956
4957 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004958 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004959 }
4960
4961 // Change it at last so setRestrictBackground() won't affect this variable
4962 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4963 }
4964
Jeff Sharkey1b861272011-05-22 00:34:52 -07004965 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4966 final int size = source.size();
4967 for (int i = 0; i < size; i++) {
4968 target.put(source.keyAt(i), true);
4969 }
4970 }
4971
Stuart Scottf1fb3972015-04-02 18:00:02 -07004972 @Override
4973 public void factoryReset(String subscriber) {
paulhu59148b72019-08-12 16:25:11 +08004974 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004975
Stuart Scotte3e314d2015-04-20 14:07:45 -07004976 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4977 return;
4978 }
4979
Stuart Scottf1fb3972015-04-02 18:00:02 -07004980 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004981 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004982 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4983 for (NetworkPolicy policy : policies) {
4984 if (policy.template.equals(template)) {
4985 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4986 policy.inferred = false;
4987 policy.clearSnooze();
4988 }
4989 }
4990 setNetworkPolicies(policies);
4991
4992 // Turn restrict background data off
4993 setRestrictBackground(false);
4994
Stuart Scotte3e314d2015-04-20 14:07:45 -07004995 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4996 // Remove app's "restrict background data" flag
4997 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4998 setUidPolicy(uid, POLICY_NONE);
4999 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005000 }
5001 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08005002
Sudheer Shankab8f23162017-08-04 13:30:10 -07005003 @Override
5004 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005005 final long startTime = mStatLogger.getTime();
5006
paulhu59148b72019-08-12 16:25:11 +08005007 mContext.enforceCallingOrSelfPermission(OBSERVE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07005008 final int uidRules;
5009 final boolean isBackgroundRestricted;
5010 synchronized (mUidRulesFirstLock) {
5011 uidRules = mUidRules.get(uid, RULE_NONE);
5012 isBackgroundRestricted = mRestrictBackground;
5013 }
junyulai05986c62018-08-07 19:50:45 +08005014 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5015 isBackgroundRestricted, mLogger);
5016
5017 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5018
5019 return ret;
5020 }
5021
5022 private static boolean isSystem(int uid) {
5023 return uid < Process.FIRST_APPLICATION_UID;
5024 }
5025
5026 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
5027 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5028 final int reason;
5029 // Networks are never blocked for system components
5030 if (isSystem(uid)) {
5031 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005032 }
junyulai05986c62018-08-07 19:50:45 +08005033 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5034 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005035 }
junyulai05986c62018-08-07 19:50:45 +08005036 else if (!isNetworkMetered) {
5037 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005038 }
junyulai05986c62018-08-07 19:50:45 +08005039 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5040 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005041 }
junyulai05986c62018-08-07 19:50:45 +08005042 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5043 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005044 }
junyulai05986c62018-08-07 19:50:45 +08005045 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5046 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005047 }
junyulai05986c62018-08-07 19:50:45 +08005048 else if (isBackgroundRestricted) {
5049 reason = NTWK_BLOCKED_BG_RESTRICT;
5050 }
5051 else {
5052 reason = NTWK_ALLOWED_DEFAULT;
5053 }
5054
5055 final boolean blocked;
5056 switch(reason) {
5057 case NTWK_ALLOWED_DEFAULT:
5058 case NTWK_ALLOWED_NON_METERED:
5059 case NTWK_ALLOWED_TMP_WHITELIST:
5060 case NTWK_ALLOWED_WHITELIST:
5061 case NTWK_ALLOWED_SYSTEM:
5062 blocked = false;
5063 break;
5064 case NTWK_BLOCKED_POWER:
5065 case NTWK_BLOCKED_BLACKLIST:
5066 case NTWK_BLOCKED_BG_RESTRICT:
5067 blocked = true;
5068 break;
5069 default:
5070 throw new IllegalArgumentException();
5071 }
5072 if (logger != null) {
5073 logger.networkBlocked(uid, reason);
5074 }
5075
5076 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005077 }
5078
Felipe Lemed17fda42016-04-29 11:12:45 -07005079 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5080
5081 @Override
5082 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005083 synchronized (mUidRulesFirstLock) {
5084 boolean changed = removeUserStateUL(userId, false);
5085 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005086 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005087 synchronized (mNetworkPoliciesSecondLock) {
5088 writePolicyAL();
5089 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005090 }
5091 }
5092 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005093
5094 /**
5095 * @return true if the given uid is restricted from doing networking on metered networks.
5096 */
5097 @Override
5098 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5099 final int uidRules;
5100 final boolean isBackgroundRestricted;
5101 synchronized (mUidRulesFirstLock) {
5102 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5103 isBackgroundRestricted = mRestrictBackground;
5104 }
5105 return isBackgroundRestricted
5106 && !hasRule(uidRules, RULE_ALLOW_METERED)
5107 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5108 }
5109
5110 /**
5111 * @return true if networking is blocked on the given interface for the given uid according
5112 * to current networking policies.
5113 */
5114 @Override
5115 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005116 final long startTime = mStatLogger.getTime();
5117
junyulai05986c62018-08-07 19:50:45 +08005118 final int uidRules;
5119 final boolean isBackgroundRestricted;
5120 synchronized (mUidRulesFirstLock) {
5121 uidRules = mUidRules.get(uid, RULE_NONE);
5122 isBackgroundRestricted = mRestrictBackground;
5123 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005124 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005125 synchronized (mNetworkPoliciesSecondLock) {
5126 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005127 }
junyulai05986c62018-08-07 19:50:45 +08005128 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5129 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005130
5131 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5132
5133 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005134 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005135
5136 @Override
5137 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5138 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005139 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005140 if (added) {
5141 mPowerSaveTempWhitelistAppIds.put(appId, true);
5142 } else {
5143 mPowerSaveTempWhitelistAppIds.delete(appId);
5144 }
5145 updateRulesForTempWhitelistChangeUL(appId);
5146 }
5147 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005148
5149 @Override
5150 public SubscriptionPlan getSubscriptionPlan(Network network) {
5151 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005152 final int subId = getSubIdLocked(network);
5153 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005154 }
5155 }
5156
5157 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005158 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5159 synchronized (mNetworkPoliciesSecondLock) {
5160 final int subId = findRelevantSubIdNL(template);
5161 return getPrimarySubscriptionPlanLocked(subId);
5162 }
5163 }
5164
5165 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005166 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005167 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005168 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005169 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005170 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005171 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005172 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5173 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5174 }
5175
5176 if (quotaType == QUOTA_TYPE_JOBS) {
5177 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5178 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5179 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5180 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5181 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5182 } else {
5183 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5184 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005185 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005186
5187 @Override
5188 public void onAdminDataAvailable() {
5189 mAdminDataAvailableLatch.countDown();
5190 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005191
5192 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005193 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5194 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5195 }
5196
5197 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005198 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5199 setMeteredRestrictedPackagesInternal(packageNames, userId);
5200 }
5201
5202 @Override
5203 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5204 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5205 userId, 0, packageNames).sendToTarget();
5206 }
5207 }
5208
5209 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5210 synchronized (mUidRulesFirstLock) {
5211 final Set<Integer> newRestrictedUids = new ArraySet<>();
5212 for (String packageName : packageNames) {
5213 final int uid = getUidForPackage(packageName, userId);
5214 if (uid >= 0) {
5215 newRestrictedUids.add(uid);
5216 }
5217 }
5218 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5219 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5220 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5221 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5222 }
5223 }
5224
5225 private int getUidForPackage(String packageName, int userId) {
5226 try {
5227 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5228 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5229 } catch (NameNotFoundException e) {
5230 return -1;
5231 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005232 }
5233
5234 private int parseSubId(NetworkState state) {
5235 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5236 int subId = INVALID_SUBSCRIPTION_ID;
5237 if (state != null && state.networkCapabilities != null
5238 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5239 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5240 if (spec instanceof StringNetworkSpecifier) {
5241 try {
5242 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5243 } catch (NumberFormatException e) {
5244 }
5245 }
5246 }
5247 return subId;
5248 }
5249
Andreas Gampea36dc622018-02-05 17:19:22 -08005250 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005251 private int getSubIdLocked(Network network) {
5252 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005253 }
5254
Andreas Gampea36dc622018-02-05 17:19:22 -08005255 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005256 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5257 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005258 if (!ArrayUtils.isEmpty(plans)) {
5259 for (SubscriptionPlan plan : plans) {
5260 if (plan.getCycleRule().isRecurring()) {
5261 // Recurring plans will always have an active cycle
5262 return plan;
5263 } else {
5264 // Non-recurring plans need manual test for active cycle
5265 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5266 if (cycle.contains(ZonedDateTime.now(mClock))) {
5267 return plan;
5268 }
5269 }
5270 }
5271 }
5272 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005273 }
5274
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005275 /**
5276 * This will only ever be called once - during device boot.
5277 */
5278 private void waitForAdminData() {
5279 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5280 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5281 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5282 }
5283 }
5284
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005285 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5286 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005287 if (!mNetworkManagerReady) {
5288 return;
5289 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005290 if (oldRestrictedUids == null) {
5291 for (int uid : newRestrictedUids) {
5292 updateRulesForDataUsageRestrictionsUL(uid);
5293 }
5294 return;
5295 }
5296 for (int uid : oldRestrictedUids) {
5297 if (!newRestrictedUids.contains(uid)) {
5298 updateRulesForDataUsageRestrictionsUL(uid);
5299 }
5300 }
5301 for (int uid : newRestrictedUids) {
5302 if (!oldRestrictedUids.contains(uid)) {
5303 updateRulesForDataUsageRestrictionsUL(uid);
5304 }
5305 }
5306 }
5307
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005308 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005309 private boolean isRestrictedByAdminUL(int uid) {
5310 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5311 UserHandle.getUserId(uid));
5312 return restrictedUids != null && restrictedUids.contains(uid);
5313 }
5314
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005315 private static boolean hasRule(int uidRules, int rule) {
5316 return (uidRules & rule) != 0;
5317 }
5318
Jeff Sharkey2e471452018-01-19 18:02:47 +09005319 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5320 return (val != null) ? val : new NetworkState[0];
5321 }
5322
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005323 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5324 String key, boolean defaultValue) {
5325 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5326 }
5327
Heemin Seogb9820d42019-05-21 16:17:43 -07005328 private static boolean isHeadlessSystemUserBuild() {
5329 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
5330 }
5331
Chris Wren193ae6b2017-03-31 15:17:11 -04005332 private class NotificationId {
5333 private final String mTag;
5334 private final int mId;
5335
5336 NotificationId(NetworkPolicy policy, int type) {
5337 mTag = buildNotificationTag(policy, type);
5338 mId = type;
5339 }
5340
5341 @Override
5342 public boolean equals(Object o) {
5343 if (this == o) return true;
5344 if (!(o instanceof NotificationId)) return false;
5345 NotificationId that = (NotificationId) o;
5346 return Objects.equals(mTag, that.mTag);
5347 }
5348
5349 @Override
5350 public int hashCode() {
5351 return Objects.hash(mTag);
5352 }
5353
5354 /**
5355 * Build unique tag that identifies an active {@link NetworkPolicy}
5356 * notification of a specific type, like {@link #TYPE_LIMIT}.
5357 */
5358 private String buildNotificationTag(NetworkPolicy policy, int type) {
5359 return TAG + ":" + policy.template.hashCode() + ":" + type;
5360 }
5361
5362 public String getTag() {
5363 return mTag;
5364 }
5365
5366 public int getId() {
5367 return mId;
5368 }
5369 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005370}