blob: 09be474a5598d75ad363cd261d51b5dab3d0c03f [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;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070031import static android.content.pm.PackageManager.MATCH_ANY_USER;
32import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
33import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
34import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
35import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
Erik Klinef851d6d2015-04-20 16:03:48 +090036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080037import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
38import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
39import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060040import static android.net.ConnectivityManager.TYPE_MOBILE;
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +090041import static android.net.INetd.FIREWALL_CHAIN_DOZABLE;
42import static android.net.INetd.FIREWALL_CHAIN_POWERSAVE;
43import static android.net.INetd.FIREWALL_CHAIN_STANDBY;
44import static android.net.INetd.FIREWALL_RULE_ALLOW;
45import static android.net.INetd.FIREWALL_RULE_DENY;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060046import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090047import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey9252b342018-01-19 07:58:35 +090048import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070049import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070050import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070051import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070052import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeydc988062015-09-14 10:09:47 -070053import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060054import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070056import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070057import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070060import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070061import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070063import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070064import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080065import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
66import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060067import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070068import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070069import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070070import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070071import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070072import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080073import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey00072392018-04-12 14:26:32 -060074import static android.os.Trace.TRACE_TAG_NETWORK;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060075import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
79import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
80import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070081import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070082import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060083import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey0a5570d2018-04-10 12:38:29 -060084import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_NOTIFICATION_BOOL;
85import static android.telephony.CarrierConfigManager.KEY_DATA_RAPID_NOTIFICATION_BOOL;
86import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_NOTIFICATION_BOOL;
Jeff Sharkey9252b342018-01-19 07:58:35 +090087import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080088
Jeff Sharkey854b2b12012-04-13 16:03:40 -070089import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070091import static com.android.internal.util.XmlUtils.readBooleanAttribute;
92import static com.android.internal.util.XmlUtils.readIntAttribute;
93import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060094import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070095import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
96import static com.android.internal.util.XmlUtils.writeIntAttribute;
97import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060098import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070099import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700100import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
junyulai05986c62018-08-07 19:50:45 +0800102import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_SYSTEM;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700103import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
104import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
106import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
107import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700108import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600109
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800111import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700113
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700114import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700115import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900116import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700117import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700118import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800119import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700120import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700121import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700123import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700125import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700127import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700128import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700129import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600130import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700132import android.content.Intent;
133import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700134import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700135import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700136import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700137import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700138import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700139import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700143import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700144import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700145import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700146import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700147import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600148import android.net.Network;
149import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700150import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600152import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700153import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600154import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900155import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700157import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700158import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900159import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700161import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700162import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700163import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700164import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.os.Environment;
166import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700167import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700169import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700170import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700171import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700172import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700173import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700174import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600176import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800177import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700178import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700179import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600180import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700181import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700182import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700183import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600184import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700185import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700186import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700187import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700188import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100189import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700190import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600191import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800192import android.telephony.SubscriptionManager;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600193import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600194import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700195import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400196import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700197import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700198import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700199import android.util.ArrayMap;
200import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700201import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900202import android.util.DataUnit;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600203import android.util.IntArray;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700204import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700205import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600206import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600207import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700208import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900212import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700214
Jeff Sharkey497e4432011-06-14 17:27:29 -0700215import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700216import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400218import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500219import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700220import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800221import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800222import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600223import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700225import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600226import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700227import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700228import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700229import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700230import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800231import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600232
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600233import libcore.io.IoUtils;
234
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlSerializer;
237
238import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700239import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240import java.io.FileInputStream;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700244import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700245import java.lang.annotation.Retention;
246import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100247import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700248import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900249import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600250import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700251import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600252import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900253import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600255import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700256import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600257import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400258import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800259import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800260import java.util.concurrent.CountDownLatch;
261import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700262
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700263/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700264 * Service that maintains low-level network policy rules, using
265 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700266 * <p>
267 * Derives active rules by combining a given policy with other system status,
268 * and delivers to listeners, such as {@link ConnectivityManager}, for
269 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700270 *
271 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700272 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700273 * <ul>
274 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
275 * rules).
276 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
277 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700278 * </ul>
279 *
280 * <p>
281 * As such, methods that require synchronization have the following prefixes:
282 * <ul>
283 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
284 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000285 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
286 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700287 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700288 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700289public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700290 static final String TAG = NetworkPolicyLogger.TAG;
291 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
292 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700293
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900294 /**
295 * No opportunistic quota could be calculated from user data plan or data settings.
296 */
297 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
298
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700299 private static final int VERSION_INIT = 1;
300 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700301 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800302 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800303 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800304 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700305 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700306 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700307 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700308 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600309 private static final int VERSION_ADDED_CYCLE = 11;
310 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800312 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400313 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400315 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400317 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900318 @VisibleForTesting
319 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700320
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321 private static final String TAG_POLICY_LIST = "policy-list";
322 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600323 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700325 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800326 private static final String TAG_WHITELIST = "whitelist";
327 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800328 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329
330 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700331 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
333 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700334 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600335 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
336 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
337 private static final String ATTR_CYCLE_START = "cycleStart";
338 private static final String ATTR_CYCLE_END = "cycleEnd";
339 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340 private static final String ATTR_WARNING_BYTES = "warningBytes";
341 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700342 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800343 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
344 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800345 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700346 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700347 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700348 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700349 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600350 private static final String ATTR_SUB_ID = "subId";
351 private static final String ATTR_TITLE = "title";
352 private static final String ATTR_SUMMARY = "summary";
353 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
354 private static final String ATTR_USAGE_BYTES = "usageBytes";
355 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600356 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700357
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800358 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800359 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800360 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800361 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700362 private static final String ACTION_SNOOZE_RAPID =
363 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700364
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800365 /**
366 * Indicates the maximum wait time for admin data to be available;
367 */
368 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
369
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600370 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
371 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
372 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
373 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
374
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700375 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700376 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800377 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800378 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700379 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700380 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
381 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700382 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700383 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900384 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800385 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700386 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Sarah Chin7af1fd02019-09-26 11:37:13 -0700387 private static final int MSG_SUBSCRIPTION_PLANS_CHANGED = 19;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700388
Makoto Onuki8e777332017-03-28 11:25:47 -0700389 private static final int UID_MSG_STATE_CHANGED = 100;
390 private static final int UID_MSG_GONE = 101;
391
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600392 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
393
Jeff Sharkey75279902011-05-24 18:39:45 -0700394 private final Context mContext;
395 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700396 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700397 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700398 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700399 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700400 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700401 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
403 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700404 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 private IDeviceIdleController mDeviceIdleController;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700406
407 /** Current cached value of the current Battery Saver mode's setting for restrict background. */
jackqdyulei29c82ab2017-03-10 14:09:16 -0800408 @GuardedBy("mUidRulesFirstLock")
Kweku Adams25fa3a72019-07-12 17:00:17 -0700409 private boolean mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800410
411 // Store the status of restrict background before turning on battery saver.
412 // Used to restore mRestrictBackground when battery saver is turned off.
413 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700414
Sudheer Shanka543339f2017-07-28 15:18:07 -0700415 // Denotes the status of restrict background read from disk.
416 private boolean mLoadedRestrictBackground;
417
Felipe Lemef0823852016-06-08 13:43:08 -0700418 // See main javadoc for instructions on how to use these locks.
419 final Object mUidRulesFirstLock = new Object();
420 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700421
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700422 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
423 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700424
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
426 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
427 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800428 // Store whether user flipped restrict background in battery saver mode
429 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700430
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700431 private final boolean mSuppressDefaultPolicy;
432
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800433 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
434
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700435 private volatile boolean mNetworkManagerReady;
436
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700437 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600438 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700440
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600441 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600442 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600443 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600445 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600446 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600447
Jeff Sharkey9252b342018-01-19 07:58:35 +0900448 /** Map from subId to daily opportunistic quota. */
449 @GuardedBy("mNetworkPoliciesSecondLock")
450 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
451
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700452 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700454 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700456
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700458 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700460 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700461 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800462 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700463
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700464 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700465 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700466 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
467
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800468 // "Power save mode" is the concept used in the DeviceIdleController that includes various
469 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
470 // and "battery saver" are not equivalent.
471
Jeff Sharkey32566012014-12-02 18:30:14 -0800472 /**
473 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700474 * in power save mode, except device idle (doze) still applies.
475 * TODO: An int array might be sufficient
476 */
Felipe Lemef0823852016-06-08 13:43:08 -0700477 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700478 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
479
480 /**
481 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800482 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700483 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800484 */
Felipe Lemef0823852016-06-08 13:43:08 -0700485 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700486 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700487
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700489 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
490
Felipe Lemeb85a6372016-01-14 16:16:16 -0800491 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800492 * UIDs that have been white-listed temporarily to be able to have network access despite being
493 * idle. Other power saving restrictions still apply.
494 */
495 @GuardedBy("mUidRulesFirstLock")
496 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
497
498 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800499 * UIDs that have been initially white-listed by system to avoid restricted background.
500 */
Felipe Lemef0823852016-06-08 13:43:08 -0700501 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800502 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
503 new SparseBooleanArray();
504
505 /**
506 * UIDs that have been initially white-listed by system to avoid restricted background,
507 * but later revoked by user.
508 */
Felipe Lemef0823852016-06-08 13:43:08 -0700509 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800510 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
511 new SparseBooleanArray();
512
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700513 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700514 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800515 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700516 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700517 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800518 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700519
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700520 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700521 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400522 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700523
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700524 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700525 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800526 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700527
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600528 /** Map from network ID to last observed meteredness state */
529 @GuardedBy("mNetworkPoliciesSecondLock")
530 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900531 /** Map from network ID to last observed roaming state */
532 @GuardedBy("mNetworkPoliciesSecondLock")
533 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
534
Jeff Sharkey9252b342018-01-19 07:58:35 +0900535 /** Map from netId to subId as of last update */
536 @GuardedBy("mNetworkPoliciesSecondLock")
537 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
538
Jeff Sharkey146bb332018-04-18 15:42:57 -0600539 /** Map from subId to subscriberId as of last update */
540 @GuardedBy("mNetworkPoliciesSecondLock")
541 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
542 /** Set of all merged subscriberId as of last update */
543 @GuardedBy("mNetworkPoliciesSecondLock")
Malcolm Chen07fcb5b2019-07-02 22:29:35 -0700544 private List<String[]> mMergedSubscriberIds = new ArrayList<>();
Jeff Sharkey146bb332018-04-18 15:42:57 -0600545
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800546 /**
547 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
548 * userId to restricted uids which belong to that user.
549 */
550 @GuardedBy("mUidRulesFirstLock")
551 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
552
Jeff Sharkey32566012014-12-02 18:30:14 -0800553 private final RemoteCallbackList<INetworkPolicyListener>
554 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700555
Dianne Hackborn497175b2014-07-01 12:56:08 -0700556 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700557 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800558 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700559
560 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700562 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700563 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700564
Svet Ganov16a16892015-04-16 10:32:04 -0700565 private final AppOpsManager mAppOps;
566
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800567 private final IPackageManager mIPm;
568
Sudheer Shankae7361852017-03-07 11:51:46 -0800569 private ActivityManagerInternal mActivityManagerInternal;
570
Sudheer Shanka352dc572017-09-22 17:09:38 -0700571 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800572
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700573 // TODO: keep whitelist of system-critical services that should never have
574 // rules enforced, such as system, phone, and radio UIDs.
575
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700576 // TODO: migrate notifications to SystemUI
577
Makoto Onuki49392d32018-04-11 13:51:02 -0700578
579 interface Stats {
580 int UPDATE_NETWORK_ENABLED = 0;
581 int IS_UID_NETWORKING_BLOCKED = 1;
582
583 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
584 }
585
586 public final StatLogger mStatLogger = new StatLogger(new String[] {
587 "updateNetworkEnabledNL()",
588 "isUidNetworkingBlocked()",
589 });
590
Jeff Sharkey75279902011-05-24 18:39:45 -0700591 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700592 INetworkManagementService networkManagement) {
593 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
594 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700595 }
596
Jeff Sharkey9911a282018-02-14 22:29:11 -0700597 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598 return new File(Environment.getDataDirectory(), "system");
599 }
600
Jeff Sharkey9911a282018-02-14 22:29:11 -0700601 private static @NonNull Clock getDefaultClock() {
602 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
603 Clock.systemUTC());
604 }
605
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700606 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700607 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
608 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700609 mContext = checkNotNull(context, "missing context");
610 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700611 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700612 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700613 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700614 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700615 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700616 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700617 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700618
Amith Yamasani450a16b2013-09-18 16:28:50 -0700619 HandlerThread thread = new HandlerThread(TAG);
620 thread.start();
621 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700622
Makoto Onuki8e777332017-03-28 11:25:47 -0700623 // We create another thread for the UID events, which are more time-critical.
624 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
625 /*allowIo=*/ false);
626 mUidEventThread.start();
627 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
628
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700629 mSuppressDefaultPolicy = suppressDefaultPolicy;
630
Dianne Hackborne17b4452018-01-10 13:15:40 -0800631 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700632
633 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800634
Felipe Lemed17fda42016-04-29 11:12:45 -0700635 // Expose private service for system components to use.
636 LocalServices.addService(NetworkPolicyManagerInternal.class,
637 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700638 }
639
640 public void bindConnectivityManager(IConnectivityManager connManager) {
641 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700642 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700643
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700644 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700645 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700646 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700647 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
648 mPowerSaveWhitelistExceptIdleAppIds.clear();
649 if (whitelist != null) {
650 for (int uid : whitelist) {
651 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
652 }
653 }
654 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700655 mPowerSaveWhitelistAppIds.clear();
656 if (whitelist != null) {
657 for (int uid : whitelist) {
658 mPowerSaveWhitelistAppIds.put(uid, true);
659 }
660 }
661 } catch (RemoteException e) {
662 }
663 }
664
Felipe Lemea9505cc2016-02-26 10:28:41 -0800665 /**
666 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
667 * revoke the whitelist.
668 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700669 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800670 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700671 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700672 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800673 final List<UserInfo> users = mUserManager.getUsers();
674 final int numberUsers = users.size();
675
Felipe Lemea110eec2016-04-29 09:58:06 -0700676 boolean changed = false;
677 for (int i = 0; i < numberUsers; i++) {
678 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700679 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700680 }
681 return changed;
682 }
683
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700684 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700685 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700686 final SystemConfig sysConfig = SystemConfig.getInstance();
687 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800688 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
689 boolean changed = false;
690 for (int i = 0; i < allowDataUsage.size(); i++) {
691 final String pkg = allowDataUsage.valueAt(i);
692 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700693 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
694 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800695 final ApplicationInfo app;
696 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700697 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800698 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700699 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
700 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800701 continue;
702 }
703 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700704 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
705 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800706 continue;
707 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700708 final int uid = UserHandle.getUid(userId, app.uid);
709 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
710 if (LOGD)
711 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
712 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800713 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700714 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700715 if (LOGD)
716 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
717 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700718 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700719 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800720 }
721 }
722 return changed;
723 }
724
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800725 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800727 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700728 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800729 // Boost thread's priority during system server init
730 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 if (!isBandwidthControlEnabled()) {
732 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
733 return;
734 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700735
Felipe Leme873a83a2016-09-07 11:34:10 -0700736 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700737 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700738
Felipe Leme873a83a2016-09-07 11:34:10 -0700739 synchronized (mUidRulesFirstLock) {
740 synchronized (mNetworkPoliciesSecondLock) {
741 updatePowerSaveWhitelistUL();
742 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
743 mPowerManagerInternal.registerLowPowerModeObserver(
744 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800745 @Override
746 public int getServiceType() {
747 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700748 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800749
750 @Override
751 public void onLowPowerModeChanged(PowerSaveState result) {
752 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800753 if (LOGD) {
754 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
755 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800756 synchronized (mUidRulesFirstLock) {
757 if (mRestrictPower != enabled) {
758 mRestrictPower = enabled;
759 updateRulesForRestrictPowerUL();
760 }
761 }
762 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800763 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800764 mRestrictPower = mPowerManagerInternal.getLowPowerState(
765 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700766
767 mSystemReady = true;
768
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800769 waitForAdminData();
770
Felipe Leme873a83a2016-09-07 11:34:10 -0700771 // read policy from disk
772 readPolicyAL();
773
jackqdyulei29c82ab2017-03-10 14:09:16 -0800774 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700775 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700776 mRestrictBackgroundLowPowerMode = mPowerManagerInternal
777 .getLowPowerState(ServiceType.DATA_SAVER).batterySaverEnabled;
778 if (mRestrictBackgroundLowPowerMode && !mLoadedRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -0700779 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800780 }
781 mPowerManagerInternal.registerLowPowerModeObserver(
782 new PowerManagerInternal.LowPowerModeListener() {
783 @Override
784 public int getServiceType() {
785 return ServiceType.DATA_SAVER;
786 }
787
788 @Override
789 public void onLowPowerModeChanged(PowerSaveState result) {
790 synchronized (mUidRulesFirstLock) {
791 updateRestrictBackgroundByLowPowerModeUL(result);
792 }
793 }
794 });
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
797 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700798 }
Felipe Lemef0823852016-06-08 13:43:08 -0700799
Kweku Adamsdf33ae12019-10-08 11:51:41 -0700800 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700801 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700802 updateRulesForGlobalChangeAL(false);
803 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700804 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800805 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700806
Sudheer Shankae7361852017-03-07 11:51:46 -0800807 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700808 try {
809 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000810 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700811 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 mNetworkManager.registerObserver(mAlertObserver);
813 } catch (RemoteException e) {
814 // ignored; both services live in system_server
815 }
816
817 // listen for changes to power save whitelist
818 final IntentFilter whitelistFilter = new IntentFilter(
819 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
820 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
821
Felipe Leme873a83a2016-09-07 11:34:10 -0700822 // watch for network interfaces to be claimed
823 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
824 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
825
826 // listen for package changes to update policy
827 final IntentFilter packageFilter = new IntentFilter();
828 packageFilter.addAction(ACTION_PACKAGE_ADDED);
829 packageFilter.addDataScheme("package");
830 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
831
832 // listen for UID changes to update policy
833 mContext.registerReceiver(
834 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
835
836 // listen for user changes to update policy
837 final IntentFilter userFilter = new IntentFilter();
838 userFilter.addAction(ACTION_USER_ADDED);
839 userFilter.addAction(ACTION_USER_REMOVED);
840 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
841
842 // listen for stats update events
843 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
844 mContext.registerReceiver(
845 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
846
847 // listen for restrict background changes from notifications
848 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
849 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
850
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700851 // Listen for snooze from notifications
852 mContext.registerReceiver(mSnoozeReceiver,
853 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
854 mContext.registerReceiver(mSnoozeReceiver,
855 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700856
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600857 // listen for configured wifi networks to be loaded
858 final IntentFilter wifiFilter =
859 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
860 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700861
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700862 // listen for carrier config changes to update data cycle information
863 final IntentFilter carrierConfigFilter = new IntentFilter(
864 ACTION_CARRIER_CONFIG_CHANGED);
865 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
866
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600867 // listen for meteredness changes
868 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
869 new NetworkRequest.Builder().build(), mNetworkCallback);
870
Felipe Leme873a83a2016-09-07 11:34:10 -0700871 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600872
873 // Listen for subscriber changes
874 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
875 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
876 @Override
877 public void onSubscriptionsChanged() {
878 updateNetworksInternal();
879 }
880 });
881
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800882 // tell systemReady() that the service has been initialized
883 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700884 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800885 // Restore the default priority after init is done
886 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700887 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700888 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700889 }
890
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800891 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700892 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800893 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
894 mHandler.post(() -> initService(initCompleteSignal));
895 return initCompleteSignal;
896 }
897
898 public void systemReady(CountDownLatch initCompleteSignal) {
899 // wait for initService to complete
900 try {
901 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
902 throw new IllegalStateException("Service " + TAG +" init timeout");
903 }
904 } catch (InterruptedException e) {
905 Thread.currentThread().interrupt();
906 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
907 }
908 }
909
Sudheer Shankac9d94072017-02-22 22:13:55 +0000910 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700911 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700912 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
913 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700914 }
915
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700916 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700917 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700918 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700919
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700920 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700921 }
922
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700923 @Override public void onUidIdle(int uid, boolean disabled) {
924 }
925
926 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700928 };
929
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700931 @Override
932 public void onReceive(Context context, Intent intent) {
933 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700934 synchronized (mUidRulesFirstLock) {
935 updatePowerSaveWhitelistUL();
936 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700937 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700938 }
939 }
940 };
941
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700942 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700943 @Override
944 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700945 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700946
947 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700948 final int uid = intent.getIntExtra(EXTRA_UID, -1);
949 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700950
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700951 if (ACTION_PACKAGE_ADDED.equals(action)) {
952 // update rules for UID, since it might be subject to
953 // global background data policy
954 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700955 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700956 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700957 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700958 }
959 }
960 };
961
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700963 @Override
964 public void onReceive(Context context, Intent intent) {
965 // on background handler thread, and UID_REMOVED is protected
966
967 final int uid = intent.getIntExtra(EXTRA_UID, -1);
968 if (uid == -1) return;
969
970 // remove any policy and update rules to clean up
971 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700972 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700973 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700974 synchronized (mNetworkPoliciesSecondLock) {
975 writePolicyAL();
976 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700977 }
978 }
979 };
980
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700981 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700982 @Override
983 public void onReceive(Context context, Intent intent) {
984 // on background handler thread, and USER_ADDED and USER_REMOVED
985 // broadcasts are protected
986
987 final String action = intent.getAction();
988 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
989 if (userId == -1) return;
990
Amith Yamasani15e472352015-04-24 19:06:07 -0700991 switch (action) {
992 case ACTION_USER_REMOVED:
993 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700994 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800995 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700996 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700997 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800998 // Removing outside removeUserStateUL since that can also be called when
999 // user resets app preferences.
1000 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001001 if (action == ACTION_USER_ADDED) {
1002 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001003 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001004 }
1005 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001006 synchronized (mNetworkPoliciesSecondLock) {
1007 updateRulesForGlobalChangeAL(true);
1008 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001009 }
1010 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001011 }
1012 }
1013 };
1014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001015 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 * Receiver that watches for {@link INetworkStatsService} updates, which we
1017 * use to check against {@link NetworkPolicy#warningBytes}.
1018 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001019 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 @Override
1021 public void onReceive(Context context, Intent intent) {
1022 // on background handler thread, and verified
1023 // READ_NETWORK_USAGE_HISTORY permission above.
1024
Felipe Lemef0823852016-06-08 13:43:08 -07001025 synchronized (mNetworkPoliciesSecondLock) {
1026 updateNetworkEnabledNL();
1027 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 }
1029 }
1030 };
1031
1032 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001033 * Receiver that watches for {@link Notification} control of
1034 * {@link #mRestrictBackground}.
1035 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001036 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1040 // permission above.
1041
1042 setRestrictBackground(false);
1043 }
1044 };
1045
1046 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001047 * Receiver that watches for {@link Notification} control of
1048 * {@link NetworkPolicy#lastWarningSnooze}.
1049 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001050 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 @Override
1052 public void onReceive(Context context, Intent intent) {
1053 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1054 // permission above.
1055
1056 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001057 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1058 performSnooze(template, TYPE_WARNING);
1059 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1060 performSnooze(template, TYPE_RAPID);
1061 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001062 }
1063 };
1064
1065 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001066 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001067 * we can perform upgrade logic. After initial upgrade logic, it updates
1068 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001069 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001070 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001071 @Override
1072 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001073 synchronized (mUidRulesFirstLock) {
1074 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001075 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001076 }
1077 }
1078 // Only need to perform upgrade logic once
1079 mContext.unregisterReceiver(this);
1080 }
1081 };
1082
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001083 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1084 Network network) {
1085 final boolean lastValue = lastValues.get(network.netId, false);
1086 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1087 if (changed) {
1088 lastValues.put(network.netId, newValue);
1089 }
1090 return changed;
1091 }
1092
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001093 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1094 @Override
1095 public void onCapabilitiesChanged(Network network,
1096 NetworkCapabilities networkCapabilities) {
1097 if (network == null || networkCapabilities == null) return;
1098
1099 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001100 final boolean newMetered = !networkCapabilities
1101 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001102 final boolean meteredChanged = updateCapabilityChange(
1103 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001104
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001105 final boolean newRoaming = !networkCapabilities
1106 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1107 final boolean roamingChanged = updateCapabilityChange(
1108 mNetworkRoaming, newRoaming, network);
1109
1110 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001111 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001112 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001113 }
1114 }
1115 }
1116 };
1117
1118 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 * Observer that watches for {@link INetworkManagementService} alerts.
1120 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001121 final private INetworkManagementEventObserver mAlertObserver
1122 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 @Override
1124 public void limitReached(String limitName, String iface) {
1125 // only someone like NMS should be calling us
1126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1127
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001128 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1129 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001130 }
1131 }
1132 };
1133
1134 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1136 * to show visible notifications as needed.
1137 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001138 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001139 void updateNotificationsNL() {
1140 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001141 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001143 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001144 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146
1147 // TODO: when switching to kernel notifications, compute next future
1148 // cycle boundary to recompute notifications.
1149
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001150 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001151 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1153 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001154 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001155
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001157 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001158 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159
Jeff Sharkey53313d72017-07-13 16:47:32 -06001160 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1161 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001162 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1163 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1164 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001165
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001166 // Carrier might want to manage notifications themselves
1167 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001168 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1169 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1170 // Don't show notifications until we confirm that the loaded config is from an
1171 // identified carrier, which may want to manage their own notifications. This method
1172 // should be called every time the carrier config changes anyways, and there's no
1173 // reason to alert if there isn't a carrier.
1174 return;
1175 }
1176
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001177 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1178 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1179 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1180 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1181 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1182 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1183
1184 // Notify when data usage is over warning
1185 if (notifyWarning) {
1186 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1187 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1188 if (!snoozedThisCycle) {
1189 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1190 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001192 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001194 // Notify when data usage is over limit
1195 if (notifyLimit) {
1196 if (policy.isOverLimit(totalBytes)) {
1197 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1198 if (snoozedThisCycle) {
1199 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1200 } else {
1201 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1202 notifyOverLimitNL(policy.template);
1203 }
1204 } else {
1205 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 }
1207 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001208
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001209 // Warn if average usage over last 4 days is on track to blow pretty
1210 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001211 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001212 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001213 final long recentStart = now - recentDuration;
1214 final long recentEnd = now;
1215 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001216
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001217 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001218 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001219 final long alertBytes = (policy.limitBytes * 3) / 2;
1220
1221 if (LOGD) {
1222 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1223 + projectedBytes + " alert " + alertBytes);
1224 }
1225
1226 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1227 - DateUtils.DAY_IN_MILLIS;
1228 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001229 enqueueNotification(policy, TYPE_RAPID, 0,
1230 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001231 }
1232 }
1233 }
1234
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001235 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001236 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001237 final NotificationId notificationId = beforeNotifs.valueAt(i);
1238 if (!mActiveNotifs.contains(notificationId)) {
1239 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 }
1241 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001242
1243 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001244 }
1245
1246 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001247 * Attempt to find a specific app to blame for rapid data usage during the
1248 * given time period.
1249 */
1250 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1251 long start, long end) {
1252 long totalBytes = 0;
1253 long maxBytes = 0;
1254 int maxUid = 0;
1255
1256 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1257 NetworkStats.Entry entry = null;
1258 for (int i = 0; i < stats.size(); i++) {
1259 entry = stats.getValues(i, entry);
1260 final long bytes = entry.rxBytes + entry.txBytes;
1261 totalBytes += bytes;
1262 if (bytes > maxBytes) {
1263 maxBytes = bytes;
1264 maxUid = entry.uid;
1265 }
1266 }
1267
1268 // Only point blame if the majority of usage was done by a single app.
1269 // TODO: support shared UIDs
1270 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1271 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001272 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001273 try {
1274 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1275 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1276 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1277 } catch (NameNotFoundException ignored) {
1278 }
1279 }
1280 }
1281
1282 return null;
1283 }
1284
1285 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001286 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001287 * current device state, such as when
1288 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1289 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001290 *
1291 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1292 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001293 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001294 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001295 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001296 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001297 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1298 final int subId = mSubIdToSubscriberId.keyAt(i);
1299 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001300 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1301 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1302 true);
1303 if (template.matches(probeIdent)) {
1304 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001305 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001306 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001307 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001308 }
1309
1310 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001311 * Notify that given {@link NetworkTemplate} is over
1312 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1313 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001314 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001315 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001316 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001317 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001318 mOverLimitNotified.add(template);
1319 }
1320 }
1321
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001322 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001323 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001324 mOverLimitNotified.remove(template);
1325 }
1326
1327 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001328 * Show notification for combined {@link NetworkPolicy} and specific type,
1329 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1330 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001331 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1332 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001333 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001334 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001335 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001336 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001337 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001338 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001339 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001340
1341 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001342 final CharSequence title;
1343 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001344 switch (type) {
1345 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001346 title = res.getText(R.string.data_usage_warning_title);
1347 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001348 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001349
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001350 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001351
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001352 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1353 builder.setDeleteIntent(PendingIntent.getBroadcast(
1354 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1355
Wei Liu546cb772016-07-21 16:19:01 -07001356 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001357 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001358 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001359 builder.setContentIntent(PendingIntent.getActivityAsUser(
1360 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1361 /* options= */ null, UserHandle.CURRENT));
1362 } else {
1363 builder.setContentIntent(PendingIntent.getActivity(
1364 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1365 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001366 break;
1367 }
1368 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001369 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001370 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001371 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001372 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001373 case MATCH_WIFI:
1374 title = res.getText(R.string.data_usage_wifi_limit_title);
1375 break;
1376 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001377 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001378 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001379 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001380
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001381 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001382 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001383
Wei Liu546cb772016-07-21 16:19:01 -07001384 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001385 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001386 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001387 builder.setContentIntent(PendingIntent.getActivityAsUser(
1388 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1389 /* options= */ null, UserHandle.CURRENT));
1390 } else {
1391 builder.setContentIntent(PendingIntent.getActivity(
1392 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1393 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001394 break;
1395 }
1396 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001397 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001398 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1400 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001401 case MATCH_WIFI:
1402 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1403 break;
1404 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001405 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001406 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001407 final long overBytes = totalBytes - policy.limitBytes;
1408 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001409 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001410
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001411 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001412 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001413 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001414
Wei Liu546cb772016-07-21 16:19:01 -07001415 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001416 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001417 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001418 builder.setContentIntent(PendingIntent.getActivityAsUser(
1419 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1420 /* options= */ null, UserHandle.CURRENT));
1421 } else {
1422 builder.setContentIntent(PendingIntent.getActivity(
1423 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1424 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001425 break;
1426 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001427 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001428 title = res.getText(R.string.data_usage_rapid_title);
1429 if (rapidBlame != null) {
1430 body = res.getString(R.string.data_usage_rapid_app_body,
1431 rapidBlame.loadLabel(mContext.getPackageManager()));
1432 } else {
1433 body = res.getString(R.string.data_usage_rapid_body);
1434 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001435
Jeff Sharkey2e471452018-01-19 18:02:47 +09001436 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001437
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001438 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1439 builder.setDeleteIntent(PendingIntent.getBroadcast(
1440 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1441
1442 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001443 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001444 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001445 builder.setContentIntent(PendingIntent.getActivityAsUser(
1446 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1447 /* options= */ null, UserHandle.CURRENT));
1448 } else {
1449 builder.setContentIntent(PendingIntent.getActivity(
1450 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1451 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001452 break;
1453 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001454 default: {
1455 return;
1456 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001457 }
1458
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001459 builder.setTicker(title);
1460 builder.setContentTitle(title);
1461 builder.setContentText(body);
1462 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001463
1464 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1465 notificationId.getId(), builder.build(), UserHandle.ALL);
1466 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001467 }
1468
Chris Wren193ae6b2017-03-31 15:17:11 -04001469 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001470 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1471 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001472 }
1473
1474 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001476 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001477 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001478 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001479 @Override
1480 public void onReceive(Context context, Intent intent) {
1481 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1482 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001483 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484 }
1485 };
1486
Jeff Sharkey146bb332018-04-18 15:42:57 -06001487 private void updateNetworksInternal() {
1488 // Get all of our cross-process communication with telephony out of
1489 // the way before we acquire internal locks.
1490 updateSubscriptions();
1491
1492 synchronized (mUidRulesFirstLock) {
1493 synchronized (mNetworkPoliciesSecondLock) {
1494 ensureActiveMobilePolicyAL();
1495 normalizePoliciesNL();
1496 updateNetworkEnabledNL();
1497 updateNetworkRulesNL();
1498 updateNotificationsNL();
1499 }
1500 }
1501 }
1502
Jeff Sharkey2e471452018-01-19 18:02:47 +09001503 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001504 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001505 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001506 final CountDownLatch latch = new CountDownLatch(1);
1507 mHandler.post(() -> {
1508 latch.countDown();
1509 });
1510 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001511 }
1512
Sudheer Shankac0f85c12019-10-12 15:01:44 -07001513 @VisibleForTesting
1514 Handler getHandlerForTesting() {
1515 return mHandler;
1516 }
1517
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001518 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001519 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1520 * if necessary.
1521 *
1522 * @param subId that has its associated NetworkPolicy updated if necessary
1523 * @return if any policies were updated
1524 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001525 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001526 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001527 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001528
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001529 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001530 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001531 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001532 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001533 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1534 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1535 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001536 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1537 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001538 }
1539 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001540 return policyUpdated;
1541 }
1542
1543 /**
1544 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1545 *
1546 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1547 * to do so, it returns the fallback value.
1548 *
1549 * @param config The CarrierConfig to read the value from.
1550 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1551 * @return cycleDay to use in the mobile NetworkPolicy.
1552 */
1553 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001554 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001555 int fallbackCycleDay) {
1556 if (config == null) {
1557 return fallbackCycleDay;
1558 }
1559 int cycleDay =
1560 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1561 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1562 return fallbackCycleDay;
1563 }
1564 // validate cycleDay value
1565 final Calendar cal = Calendar.getInstance();
1566 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1567 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1568 Slog.e(TAG, "Invalid date in "
1569 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1570 return fallbackCycleDay;
1571 }
1572 return cycleDay;
1573 }
1574
1575 /**
1576 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1577 *
1578 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1579 * to do so, it returns the fallback value.
1580 *
1581 * @param config The CarrierConfig to read the value from.
1582 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1583 * @return warningBytes to use in the mobile NetworkPolicy.
1584 */
1585 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001586 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001587 long fallbackWarningBytes) {
1588 if (config == null) {
1589 return fallbackWarningBytes;
1590 }
1591 long warningBytes =
1592 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1593
1594 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1595 return WARNING_DISABLED;
1596 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1597 return getPlatformDefaultWarningBytes();
1598 } else if (warningBytes < 0) {
1599 Slog.e(TAG, "Invalid value in "
1600 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1601 + "non-negative value but got: " + warningBytes);
1602 return fallbackWarningBytes;
1603 }
1604
1605 return warningBytes;
1606 }
1607
1608 /**
1609 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1610 *
1611 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1612 * to do so, it returns the fallback value.
1613 *
1614 * @param config The CarrierConfig to read the value from.
1615 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1616 * @return limitBytes to use in the mobile NetworkPolicy.
1617 */
1618 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001619 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001620 long fallbackLimitBytes) {
1621 if (config == null) {
1622 return fallbackLimitBytes;
1623 }
1624 long limitBytes =
1625 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1626
1627 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1628 return LIMIT_DISABLED;
1629 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1630 return getPlatformDefaultLimitBytes();
1631 } else if (limitBytes < 0) {
1632 Slog.e(TAG, "Invalid value in "
1633 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1634 + "non-negative value but got: " + limitBytes);
1635 return fallbackLimitBytes;
1636 }
1637 return limitBytes;
1638 }
1639
1640 /**
1641 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1642 */
1643 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1644 @Override
1645 public void onReceive(Context context, Intent intent) {
1646 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1647 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1648
1649 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1650 return;
1651 }
1652 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001653
1654 // Get all of our cross-process communication with telephony out of
1655 // the way before we acquire internal locks.
1656 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001657
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001658 synchronized (mUidRulesFirstLock) {
1659 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001660 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1661 if (subscriberId != null) {
1662 ensureActiveMobilePolicyAL(subId, subscriberId);
1663 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1664 } else {
1665 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1666 }
1667
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001668 // update network and notification rules, as the data cycle changed and it's
1669 // possible that we should be triggering warnings/limits now
1670 handleNetworkPoliciesUpdateAL(true);
1671 }
1672 }
1673 }
1674 };
1675
1676 /**
1677 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1678 * one has been updated.
1679 *
1680 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1681 * update.
1682 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001683 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001684 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1685 if (shouldNormalizePolicies) {
1686 normalizePoliciesNL();
1687 }
1688 updateNetworkEnabledNL();
1689 updateNetworkRulesNL();
1690 updateNotificationsNL();
1691 writePolicyAL();
1692 }
1693
1694 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001695 * Proactively control network data connections when they exceed
1696 * {@link NetworkPolicy#limitBytes}.
1697 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001698 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001699 void updateNetworkEnabledNL() {
1700 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001701 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001702
1703 // TODO: reset any policy-disabled networks when any policy is removed
1704 // completely, which is currently rare case.
1705
Makoto Onuki49392d32018-04-11 13:51:02 -07001706 final long startTime = mStatLogger.getTime();
1707
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001708 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1709 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001710 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001711 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001712 setNetworkTemplateEnabled(policy.template, true);
1713 continue;
1714 }
1715
Jeff Sharkey53313d72017-07-13 16:47:32 -06001716 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1717 .cycleIterator(policy).next();
1718 final long start = cycle.first.toInstant().toEpochMilli();
1719 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001720 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001721
1722 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001723 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1724 && policy.lastLimitSnooze < start;
1725 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001726
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001727 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001728 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001729
1730 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001731 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001732 }
1733
1734 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001735 * Proactively disable networks that match the given
1736 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001737 */
1738 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001739 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1740 // held. Call it via the handler.
1741 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1742 .sendToTarget();
1743 }
1744
1745 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001746 // TODO: reach into ConnectivityManager to proactively disable bringing
1747 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001748
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001749 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001750 // If mobile data usage hits the limit or if the user resumes the data, we need to
1751 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001752
Jeff Sharkey146bb332018-04-18 15:42:57 -06001753 final IntArray matchingSubIds = new IntArray();
1754 synchronized (mNetworkPoliciesSecondLock) {
1755 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1756 final int subId = mSubIdToSubscriberId.keyAt(i);
1757 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1758
1759 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1760 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1761 true);
1762 // Template is matched when subscriber id matches.
1763 if (template.matches(probeIdent)) {
1764 matchingSubIds.add(subId);
1765 }
Jack Yu8781b682016-07-08 14:28:51 -07001766 }
1767 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001768
1769 // Only talk with telephony outside of locks
1770 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1771 for (int i = 0; i < matchingSubIds.size(); i++) {
1772 final int subId = matchingSubIds.get(i);
1773 tm.setPolicyDataEnabled(enabled, subId);
1774 }
Jack Yu8781b682016-07-08 14:28:51 -07001775 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001776 }
1777
1778 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001779 * Collect all ifaces from a {@link NetworkState} into the given set.
1780 */
1781 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1782 final String baseIface = state.linkProperties.getInterfaceName();
1783 if (baseIface != null) {
1784 ifaces.add(baseIface);
1785 }
1786 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1787 final String stackedIface = stackedLink.getInterfaceName();
1788 if (stackedIface != null) {
1789 ifaces.add(stackedIface);
1790 }
1791 }
1792 }
1793
1794 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001795 * Examine all currently active subscriptions from
1796 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1797 * internal data structures.
1798 * <p>
1799 * Callers <em>must not</em> hold any locks when this method called.
1800 */
1801 void updateSubscriptions() {
1802 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1803 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1804
1805 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1806 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1807
1808 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001809 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001810
1811 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1812 for (int subId : subIds) {
1813 final String subscriberId = tm.getSubscriberId(subId);
1814 if (!TextUtils.isEmpty(subscriberId)) {
1815 subIdToSubscriberId.put(subId, subscriberId);
1816 } else {
1817 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1818 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001819
1820 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1821 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1822 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001823 }
1824
1825 synchronized (mNetworkPoliciesSecondLock) {
1826 mSubIdToSubscriberId.clear();
1827 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1828 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1829 subIdToSubscriberId.valueAt(i));
1830 }
1831
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001832 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001833 }
1834
1835 Trace.traceEnd(TRACE_TAG_NETWORK);
1836 }
1837
1838 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001839 * Examine all connected {@link NetworkState}, looking for
1840 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1841 * remaining quota based on usage cycle and historical stats.
1842 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001843 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001844 void updateNetworkRulesNL() {
1845 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001846 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001847
1848 final NetworkState[] states;
1849 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001850 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001852 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001853 return;
1854 }
1855
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001856 // First, generate identities of all connected networks so we can
1857 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001858 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001859 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001860 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001861 if (state.network != null) {
1862 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1863 }
Wei Liub8eaf452016-01-25 10:32:27 -08001864 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001865 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1866 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001867 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001868 }
1869 }
1870
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001871 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001872 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001873
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001874 // For every well-defined policy, compute remaining data based on
1875 // current cycle and historical stats, and push to kernel.
1876 final ArraySet<String> matchingIfaces = new ArraySet<>();
1877 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1878 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1879
1880 // Collect all ifaces that match this policy
1881 matchingIfaces.clear();
1882 for (int j = identified.size() - 1; j >= 0; j--) {
1883 if (policy.template.matches(identified.valueAt(j))) {
1884 collectIfaces(matchingIfaces, identified.keyAt(j));
1885 }
1886 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001887
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001888 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001889 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001890 }
1891
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001892 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001893 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001894 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001895 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001896 if (hasLimit && policy.hasCycle()) {
1897 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1898 .cycleIterator(policy).next();
1899 final long start = cycle.first.toInstant().toEpochMilli();
1900 final long end = cycle.second.toInstant().toEpochMilli();
1901 final long totalBytes = getTotalBytes(policy.template, start, end);
1902
1903 if (policy.lastLimitSnooze >= start) {
1904 // snoozing past quota, but we still need to restrict apps,
1905 // so push really high quota.
1906 quotaBytes = Long.MAX_VALUE;
1907 } else {
1908 // remaining "quota" bytes are based on total usage in
1909 // current cycle. kernel doesn't like 0-byte rules, so we
1910 // set 1-byte quota and disable the radio later.
1911 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1912 }
1913 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001914 // metered network, but no policy limit; we still need to
1915 // restrict apps, so push really high quota.
1916 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001917 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001918
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001919 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001920 // TODO: switch to shared quota once NMS supports
1921 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001922 }
1923
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001924 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1925 final String iface = matchingIfaces.valueAt(j);
1926 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001927 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001928 }
1929 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001930
1931 // keep track of lowest warning or limit of active policies
1932 if (hasWarning && policy.warningBytes < lowestRule) {
1933 lowestRule = policy.warningBytes;
1934 }
1935 if (hasLimit && policy.limitBytes < lowestRule) {
1936 lowestRule = policy.limitBytes;
1937 }
1938 }
1939
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001940 // One final pass to catch any metered ifaces that don't have explicitly
1941 // defined policies; typically Wi-Fi networks.
1942 for (NetworkState state : states) {
1943 if (state.networkInfo != null && state.networkInfo.isConnected()
1944 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1945 matchingIfaces.clear();
1946 collectIfaces(matchingIfaces, state);
1947 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1948 final String iface = matchingIfaces.valueAt(j);
1949 if (!newMeteredIfaces.contains(iface)) {
1950 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1951 newMeteredIfaces.add(iface);
1952 }
1953 }
1954 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001955 }
1956
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001957 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001958 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1959 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001960 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001961 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001962 }
1963 }
1964 mMeteredIfaces = newMeteredIfaces;
1965
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001966 final ContentResolver cr = mContext.getContentResolver();
1967 final boolean quotaEnabled = Settings.Global.getInt(cr,
1968 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1969 final long quotaUnlimited = Settings.Global.getLong(cr,
1970 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1971 final float quotaLimited = Settings.Global.getFloat(cr,
1972 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1973
Jeff Sharkey9252b342018-01-19 07:58:35 +09001974 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001975 mSubscriptionOpportunisticQuota.clear();
1976 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001977 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001978 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001979 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001980 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001981 if (plan == null) continue;
1982
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001983 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001984 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001985 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1986 // Clamp to 0 when roaming
1987 quotaBytes = 0;
1988 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001989 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001990 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001991 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001992 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001993 } else {
1994 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001995 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1996 final long start = cycle.getLower().toInstant().toEpochMilli();
1997 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001998 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001999 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002000 .truncatedTo(ChronoUnit.DAYS)
2001 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09002002 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002003 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
2004 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09002005 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002006 // Number of remaining days including current day
2007 final long remainingDays =
2008 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002009
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002010 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002011 }
2012
2013 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2014 }
2015
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002016 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002017 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002018
2019 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002020
2021 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002022 }
2023
2024 /**
2025 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2026 * have at least a default mobile policy defined.
2027 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002028 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002029 private void ensureActiveMobilePolicyAL() {
2030 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002031 if (mSuppressDefaultPolicy) return;
2032
Jeff Sharkey146bb332018-04-18 15:42:57 -06002033 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2034 final int subId = mSubIdToSubscriberId.keyAt(i);
2035 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002036
Hugo Benichi446c9c92017-04-10 09:41:10 +09002037 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002038 }
2039 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002040
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002041 /**
2042 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2043 * have at least a default mobile policy defined.
2044 *
2045 * @param subId to build a default policy for
2046 * @param subscriberId that we check for an existing policy
2047 * @return true if a mobile network policy was added, or false one already existed.
2048 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002049 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002050 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002051 // Poke around to see if we already have a policy
2052 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002053 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002054 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2055 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2056 if (template.matches(probeIdent)) {
2057 if (LOGD) {
2058 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2059 + NetworkIdentity.scrubSubscriberId(subscriberId));
2060 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002061 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002062 }
2063 }
2064
Jeff Sharkey32566012014-12-02 18:30:14 -08002065 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2066 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002067 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002068 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002069 return true;
2070 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002071
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002072 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002073 final int dataWarningConfig = mContext.getResources().getInteger(
2074 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002075 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002076 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002077 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002078 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002079 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002080 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002081
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002082 private long getPlatformDefaultLimitBytes() {
2083 return LIMIT_DISABLED;
2084 }
2085
2086 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002087 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002088 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002089 final RecurrenceRule cycleRule = NetworkPolicy
2090 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002091 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002092 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2093 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2094 synchronized (mUidRulesFirstLock) {
2095 synchronized (mNetworkPoliciesSecondLock) {
2096 updateDefaultMobilePolicyAL(subId, policy);
2097 }
2098 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002099 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002100 }
2101
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002102 /**
2103 * Update the given {@link NetworkPolicy} based on any carrier-provided
2104 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2105 * Leaves policy untouched if the user has modified it.
2106 *
2107 * @return if the policy was modified
2108 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002109 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002110 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2111 if (!policy.inferred) {
2112 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2113 return false;
2114 }
2115
2116 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2117 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2118 policy.lastLimitSnooze, policy.metered, policy.inferred);
2119
2120 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2121 if (!ArrayUtils.isEmpty(plans)) {
2122 final SubscriptionPlan plan = plans[0];
2123 policy.cycleRule = plan.getCycleRule();
2124 final long planLimitBytes = plan.getDataLimitBytes();
2125 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2126 policy.warningBytes = getPlatformDefaultWarningBytes();
2127 policy.limitBytes = getPlatformDefaultLimitBytes();
2128 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2129 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2130 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2131 } else {
2132 policy.warningBytes = (planLimitBytes * 9) / 10;
2133 switch (plan.getDataLimitBehavior()) {
2134 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2135 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2136 policy.limitBytes = planLimitBytes;
2137 break;
2138 default:
2139 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2140 break;
2141 }
2142 }
2143 } else {
2144 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2145 final int currentCycleDay;
2146 if (policy.cycleRule.isMonthly()) {
2147 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2148 } else {
2149 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2150 }
2151 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2152 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2153 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2154 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2155 }
2156
2157 if (policy.equals(original)) {
2158 return false;
2159 } else {
2160 Slog.d(TAG, "Updated " + original + " to " + policy);
2161 return true;
2162 }
2163 }
2164
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002165 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002166 private void readPolicyAL() {
2167 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002168
2169 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002170 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002171 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002172 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002173 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002174
2175 FileInputStream fis = null;
2176 try {
2177 fis = mPolicyFile.openRead();
2178 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002179 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002180
Felipe Leme46b451f2016-08-19 08:46:17 -07002181 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2182 // to skip UIDs that were explicitly blacklisted.
2183 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2184
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002185 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002186 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002187 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002188 while ((type = in.next()) != END_DOCUMENT) {
2189 final String tag = in.getName();
2190 if (type == START_TAG) {
2191 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002192 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002193 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002194 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2195 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002196 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2197 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2198 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002199 final String networkId;
2200 if (version >= VERSION_ADDED_NETWORK_ID) {
2201 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2202 } else {
2203 networkId = null;
2204 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002205 final RecurrenceRule cycleRule;
2206 if (version >= VERSION_ADDED_CYCLE) {
2207 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2208 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2209 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2210 cycleRule = new RecurrenceRule(
2211 RecurrenceRule.convertZonedDateTime(start),
2212 RecurrenceRule.convertZonedDateTime(end),
2213 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002214 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002215 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2216 final String cycleTimezone;
2217 if (version >= VERSION_ADDED_TIMEZONE) {
2218 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2219 } else {
2220 cycleTimezone = "UTC";
2221 }
2222 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002223 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002224 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2225 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002226 final long lastLimitSnooze;
2227 if (version >= VERSION_SPLIT_SNOOZE) {
2228 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2229 } else if (version >= VERSION_ADDED_SNOOZE) {
2230 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002231 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002232 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002233 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002234 final boolean metered;
2235 if (version >= VERSION_ADDED_METERED) {
2236 metered = readBooleanAttribute(in, ATTR_METERED);
2237 } else {
2238 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002239 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002240 metered = true;
2241 break;
2242 default:
2243 metered = false;
2244 }
2245 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002246 final long lastWarningSnooze;
2247 if (version >= VERSION_SPLIT_SNOOZE) {
2248 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2249 } else {
2250 lastWarningSnooze = SNOOZE_NEVER;
2251 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002252 final boolean inferred;
2253 if (version >= VERSION_ADDED_INFERRED) {
2254 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2255 } else {
2256 inferred = false;
2257 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002258
Jeff Sharkey32566012014-12-02 18:30:14 -08002259 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2260 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002261 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002262 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2263 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002264 lastLimitSnooze, metered, inferred));
2265 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002266
2267 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2268 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2269 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2270 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2271 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2272 RecurrenceRule.convertZonedDateTime(start),
2273 RecurrenceRule.convertZonedDateTime(end),
2274 RecurrenceRule.convertPeriod(period));
2275 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2276 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2277
2278 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2279 SubscriptionPlan.BYTES_UNKNOWN);
2280 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2281 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2282 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2283 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2284 builder.setDataLimit(limitBytes, limitBehavior);
2285 }
2286
2287 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2288 SubscriptionPlan.BYTES_UNKNOWN);
2289 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2290 SubscriptionPlan.TIME_UNKNOWN);
2291 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2292 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2293 builder.setDataUsage(usageBytes, usageTime);
2294 }
2295
2296 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2297 final SubscriptionPlan plan = builder.build();
2298 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2299 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2300
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002301 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2302 mSubscriptionPlansOwner.put(subId, ownerPackage);
2303
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002304 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002305 final int uid = readIntAttribute(in, ATTR_UID);
2306 final int policy = readIntAttribute(in, ATTR_POLICY);
2307
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002308 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002309 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002310 } else {
2311 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2312 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002313 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002314 final int appId = readIntAttribute(in, ATTR_APP_ID);
2315 final int policy = readIntAttribute(in, ATTR_POLICY);
2316
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002318 // app policy is deprecated so this is only used in pre system user split.
2319 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002320 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002321 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002322 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002323 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002324 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002325 } else if (TAG_WHITELIST.equals(tag)) {
2326 insideWhitelist = true;
2327 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2328 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002329 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002330 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2331 final int uid = readIntAttribute(in, ATTR_UID);
2332 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002333 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002334 } else if (type == END_TAG) {
2335 if (TAG_WHITELIST.equals(tag)) {
2336 insideWhitelist = false;
2337 }
2338
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002339 }
2340 }
2341
Felipe Leme46b451f2016-08-19 08:46:17 -07002342 final int size = whitelistedRestrictBackground.size();
2343 for (int i = 0; i < size; i++) {
2344 final int uid = whitelistedRestrictBackground.keyAt(i);
2345 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2346 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2347 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2348 + " because its policy is " + uidPoliciesToString(policy));
2349 continue;
2350 }
2351 if (UserHandle.isApp(uid)) {
2352 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2353 if (LOGV)
2354 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2355 setUidPolicyUncheckedUL(uid, newPolicy, false);
2356 } else {
2357 Slog.w(TAG, "unable to update policy on UID " + uid);
2358 }
2359 }
2360
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002361 } catch (FileNotFoundException e) {
2362 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002363 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002364 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002365 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002366 } finally {
2367 IoUtils.closeQuietly(fis);
2368 }
2369 }
2370
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002371 /**
2372 * Upgrade legacy background data flags, notifying listeners of one last
2373 * change to always-true.
2374 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002375 private void upgradeDefaultBackgroundDataUL() {
2376 // This method is only called when we're unable to find the network policy flag, which
2377 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002378
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002379 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002380 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002381 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2382
2383 // NOTE: We used to read the legacy setting here :
2384 //
2385 // final int legacyFlagValue = Settings.Secure.getInt(
2386 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2387 //
2388 // This is no longer necessary because we will never upgrade directly from Gingerbread
2389 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2390 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002391 }
2392
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002393 /**
2394 * Perform upgrade step of moving any user-defined meterness overrides over
2395 * into {@link WifiConfiguration}.
2396 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002397 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002398 private void upgradeWifiMeteredOverrideAL() {
2399 boolean modified = false;
2400 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2401 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2402 for (int i = 0; i < mNetworkPolicy.size(); ) {
2403 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2404 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2405 && !policy.inferred) {
2406 mNetworkPolicy.removeAt(i);
2407 modified = true;
2408
2409 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2410 for (WifiConfiguration config : configs) {
2411 if (Objects.equals(resolveNetworkId(config), networkId)) {
2412 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2413 config.meteredOverride = policy.metered
2414 ? WifiConfiguration.METERED_OVERRIDE_METERED
2415 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2416 wm.updateNetwork(config);
2417 }
2418 }
2419 } else {
2420 i++;
2421 }
2422 }
2423 if (modified) {
2424 writePolicyAL();
2425 }
2426 }
2427
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002428 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002429 void writePolicyAL() {
2430 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002431
2432 FileOutputStream fos = null;
2433 try {
2434 fos = mPolicyFile.startWrite();
2435
2436 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002437 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002438 out.startDocument(null, true);
2439
2440 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002441 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002442 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002443
2444 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002445 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2446 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002447 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002448 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002449
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002450 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002451 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2452 final String subscriberId = template.getSubscriberId();
2453 if (subscriberId != null) {
2454 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002455 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002456 final String networkId = template.getNetworkId();
2457 if (networkId != null) {
2458 out.attribute(null, ATTR_NETWORK_ID, networkId);
2459 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002460 writeStringAttribute(out, ATTR_CYCLE_START,
2461 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2462 writeStringAttribute(out, ATTR_CYCLE_END,
2463 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2464 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2465 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002466 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2467 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002468 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2469 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002470 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002471 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002472 out.endTag(null, TAG_NETWORK_POLICY);
2473 }
2474
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002475 // write all known subscription plans
2476 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2477 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002478 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002479 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2480 if (ArrayUtils.isEmpty(plans)) continue;
2481
2482 for (SubscriptionPlan plan : plans) {
2483 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2484 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002485 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002486 final RecurrenceRule cycleRule = plan.getCycleRule();
2487 writeStringAttribute(out, ATTR_CYCLE_START,
2488 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2489 writeStringAttribute(out, ATTR_CYCLE_END,
2490 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2491 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2492 RecurrenceRule.convertPeriod(cycleRule.period));
2493 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2494 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2495 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2496 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2497 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2498 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2499 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2500 }
2501 }
2502
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002503 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002504 for (int i = 0; i < mUidPolicy.size(); i++) {
2505 final int uid = mUidPolicy.keyAt(i);
2506 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507
Jeff Sharkey497e4432011-06-14 17:27:29 -07002508 // skip writing empty policies
2509 if (policy == POLICY_NONE) continue;
2510
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002511 out.startTag(null, TAG_UID_POLICY);
2512 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002513 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002514 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002515 }
2516
2517 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002518
2519 // write all whitelists
2520 out.startTag(null, TAG_WHITELIST);
2521
Felipe Lemea9505cc2016-02-26 10:28:41 -08002522 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002523 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002524 for (int i = 0; i < size; i++) {
2525 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2526 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2527 writeIntAttribute(out, ATTR_UID, uid);
2528 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2529 }
2530
Felipe Lemeb85a6372016-01-14 16:16:16 -08002531 out.endTag(null, TAG_WHITELIST);
2532
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002533 out.endDocument();
2534
2535 mPolicyFile.finishWrite(fos);
2536 } catch (IOException e) {
2537 if (fos != null) {
2538 mPolicyFile.failWrite(fos);
2539 }
2540 }
2541 }
2542
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002543 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002544 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002545 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002546
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002547 if (!UserHandle.isApp(uid)) {
2548 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002549 }
Felipe Lemef0823852016-06-08 13:43:08 -07002550 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002551 final long token = Binder.clearCallingIdentity();
2552 try {
2553 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2554 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002555 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002556 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002557 }
2558 } finally {
2559 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002560 }
2561 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002562 }
2563
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002564 @Override
2565 public void addUidPolicy(int uid, int policy) {
2566 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002567
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002568 if (!UserHandle.isApp(uid)) {
2569 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2570 }
2571
Felipe Lemef0823852016-06-08 13:43:08 -07002572 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002573 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2574 policy |= oldPolicy;
2575 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002576 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002577 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002578 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002580 }
2581
2582 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002583 public void removeUidPolicy(int uid, int policy) {
2584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2585
2586 if (!UserHandle.isApp(uid)) {
2587 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2588 }
2589
Felipe Lemef0823852016-06-08 13:43:08 -07002590 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002591 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2592 policy = oldPolicy & ~policy;
2593 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002594 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002595 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002596 }
2597 }
2598 }
2599
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002600 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002601 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002602 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002603
Felipe Leme57e3d312016-08-23 14:42:52 -07002604 final boolean notifyApp;
2605 if (!isUidValidForWhitelistRules(uid)) {
2606 notifyApp = false;
2607 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002608 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2609 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2610 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2611 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002612 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2613 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002614 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2615 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2616 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2617 if (LOGD)
2618 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2619 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2620 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002621 notifyApp = wasBlocked != isBlocked;
2622 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002623 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2624 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002625 if (persist) {
2626 synchronized (mNetworkPoliciesSecondLock) {
2627 writePolicyAL();
2628 }
2629 }
Felipe Leme923845f2016-03-02 13:42:48 -08002630 }
2631
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002632 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002633 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002634 if (policy == POLICY_NONE) {
2635 mUidPolicy.delete(uid);
2636 } else {
2637 mUidPolicy.put(uid, policy);
2638 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002639
2640 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002641 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002642 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002643 synchronized (mNetworkPoliciesSecondLock) {
2644 writePolicyAL();
2645 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002646 }
2647 }
2648
2649 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002650 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002651 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2652
Felipe Lemef0823852016-06-08 13:43:08 -07002653 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002654 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002655 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002656 }
2657
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002658 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002659 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002660 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2661
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002662 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002663 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002664 for (int i = 0; i < mUidPolicy.size(); i++) {
2665 final int uid = mUidPolicy.keyAt(i);
2666 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002667 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2668 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002669 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002670 }
2671 }
2672 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002673 return uids;
2674 }
2675
2676 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002677 * Removes any persistable state associated with given {@link UserHandle}, persisting
2678 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002679 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002680 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002681 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002682
Sudheer Shanka352dc572017-09-22 17:09:38 -07002683 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002684 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002685
Felipe Lemea110eec2016-04-29 09:58:06 -07002686 // Remove entries from revoked default restricted background UID whitelist
2687 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2688 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2689 if (UserHandle.getUserId(uid) == userId) {
2690 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002691 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002692 }
2693 }
2694
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002695 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002696 int[] uids = new int[0];
2697 for (int i = 0; i < mUidPolicy.size(); i++) {
2698 final int uid = mUidPolicy.keyAt(i);
2699 if (UserHandle.getUserId(uid) == userId) {
2700 uids = appendInt(uids, uid);
2701 }
2702 }
2703
2704 if (uids.length > 0) {
2705 for (int uid : uids) {
2706 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002707 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002708 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002709 }
Felipe Lemef0823852016-06-08 13:43:08 -07002710 synchronized (mNetworkPoliciesSecondLock) {
2711 updateRulesForGlobalChangeAL(true);
2712 if (writePolicy && changed) {
2713 writePolicyAL();
2714 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002715 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002716 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002717 }
2718
2719 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002720 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002721 // TODO: create permission for observing network policy
2722 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002723 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002724 }
2725
2726 @Override
2727 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002728 // TODO: create permission for observing network policy
2729 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002730 mListeners.unregister(listener);
2731 }
2732
Jeff Sharkey1b861272011-05-22 00:34:52 -07002733 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002734 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002735 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2736
Felipe Leme6a05eee2016-02-19 14:43:51 -08002737 final long token = Binder.clearCallingIdentity();
2738 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002739 synchronized (mUidRulesFirstLock) {
2740 synchronized (mNetworkPoliciesSecondLock) {
2741 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002742 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002743 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002744 }
2745 } finally {
2746 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002747 }
2748 }
2749
Hugo Benichi446c9c92017-04-10 09:41:10 +09002750 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002751 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002752 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2753 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002754 }
2755
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002756 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002757 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002758 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002759 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002760 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2761 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2762 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002763 } catch (SecurityException e) {
2764 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002765
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002766 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2767 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2768 return new NetworkPolicy[0];
2769 }
Svet Ganov16a16892015-04-16 10:32:04 -07002770 }
2771
Felipe Lemef0823852016-06-08 13:43:08 -07002772 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002773 final int size = mNetworkPolicy.size();
2774 final NetworkPolicy[] policies = new NetworkPolicy[size];
2775 for (int i = 0; i < size; i++) {
2776 policies[i] = mNetworkPolicy.valueAt(i);
2777 }
2778 return policies;
2779 }
2780 }
2781
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002782 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002783 private void normalizePoliciesNL() {
2784 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002785 }
2786
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002787 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002788 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002789 mNetworkPolicy.clear();
2790 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002791 if (policy == null) {
2792 continue;
2793 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002794 // When two normalized templates conflict, prefer the most
2795 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002796 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002797 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2798 if (existing == null || existing.compareTo(policy) > 0) {
2799 if (existing != null) {
2800 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2801 }
2802 mNetworkPolicy.put(policy.template, policy);
2803 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002804 }
2805 }
2806
2807 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002808 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002809 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002810
2811 final long token = Binder.clearCallingIdentity();
2812 try {
2813 performSnooze(template, TYPE_LIMIT);
2814 } finally {
2815 Binder.restoreCallingIdentity(token);
2816 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002817 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002818
Dianne Hackborn497175b2014-07-01 12:56:08 -07002819 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002820 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002821 synchronized (mUidRulesFirstLock) {
2822 synchronized (mNetworkPoliciesSecondLock) {
2823 // find and snooze local policy that matches
2824 final NetworkPolicy policy = mNetworkPolicy.get(template);
2825 if (policy == null) {
2826 throw new IllegalArgumentException("unable to find policy for " + template);
2827 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002828
Felipe Lemef0823852016-06-08 13:43:08 -07002829 switch (type) {
2830 case TYPE_WARNING:
2831 policy.lastWarningSnooze = currentTime;
2832 break;
2833 case TYPE_LIMIT:
2834 policy.lastLimitSnooze = currentTime;
2835 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002836 case TYPE_RAPID:
2837 policy.lastRapidSnooze = currentTime;
2838 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002839 default:
2840 throw new IllegalArgumentException("unexpected type");
2841 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002842
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002843 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002844 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002845 }
2846 }
2847
2848 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002849 public void onTetheringChanged(String iface, boolean tethering) {
2850 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002851 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002852 if (mRestrictBackground && tethering) {
2853 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2854 setRestrictBackground(false);
2855 }
2856 }
2857 }
2858
2859 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002860 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002861 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002862 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002863 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2864 final long token = Binder.clearCallingIdentity();
2865 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002866 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002867 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002868 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002869 } finally {
2870 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002871 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002872 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002873 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002874 }
2875 }
2876
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002877 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002878 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002879 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002880 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002881 if (restrictBackground == mRestrictBackground) {
2882 // Ideally, UI should never allow this scenario...
2883 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002884 return;
2885 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002886 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2887 final boolean oldRestrictBackground = mRestrictBackground;
2888 mRestrictBackground = restrictBackground;
2889 // Must whitelist foreground apps before turning data saver mode on.
2890 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2891 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2892 updateRulesForRestrictBackgroundUL();
2893 try {
2894 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2895 Slog.e(TAG,
2896 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2897 mRestrictBackground = oldRestrictBackground;
2898 // TODO: if it knew the foreground apps (see TODO above), it could call
2899 // updateRulesForRestrictBackgroundUL() again to restore state.
2900 return;
2901 }
2902 } catch (RemoteException e) {
2903 // ignored; service lives in system_server
2904 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002905
Sudheer Shanka543339f2017-07-28 15:18:07 -07002906 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002907 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002908
Kweku Adams25fa3a72019-07-12 17:00:17 -07002909 if (mRestrictBackgroundLowPowerMode) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002910 mRestrictBackgroundChangedInBsm = true;
2911 }
2912 synchronized (mNetworkPoliciesSecondLock) {
2913 updateNotificationsNL();
2914 writePolicyAL();
2915 }
2916 } finally {
2917 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002918 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002919 }
2920
2921 private void sendRestrictBackgroundChangedMsg() {
2922 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2923 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2924 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002925 }
2926
Felipe Lemeb85a6372016-01-14 16:16:16 -08002927 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002928 public int getRestrictBackgroundByCaller() {
2929 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2930 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002931
Felipe Lemef0823852016-06-08 13:43:08 -07002932 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002933 // Must clear identity because getUidPolicy() is restricted to system.
2934 final long token = Binder.clearCallingIdentity();
2935 final int policy;
2936 try {
2937 policy = getUidPolicy(uid);
2938 } finally {
2939 Binder.restoreCallingIdentity(token);
2940 }
2941 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2942 // App is blacklisted.
2943 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2944 }
Felipe Leme1b103232016-01-22 09:44:57 -08002945 if (!mRestrictBackground) {
2946 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2947 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002948 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002949 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2950 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2951 }
2952 }
2953
2954 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002955 public boolean getRestrictBackground() {
2956 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2957
Felipe Lemef0823852016-06-08 13:43:08 -07002958 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002959 return mRestrictBackground;
2960 }
2961 }
2962
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002963 @Override
2964 public void setDeviceIdleMode(boolean enabled) {
2965 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002966 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2967 try {
2968 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002969 if (mDeviceIdleMode == enabled) {
2970 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002971 }
Felipe Lemeea014392016-09-06 13:59:54 -07002972 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002973 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002974 if (mSystemReady) {
2975 // Device idle change means we need to rebuild rules for all
2976 // known apps, so do a global refresh.
2977 updateRulesForRestrictPowerUL();
2978 }
2979 }
2980 if (enabled) {
2981 EventLogTags.writeDeviceIdleOnPhase("net");
2982 } else {
2983 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002984 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002985 } finally {
2986 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002987 }
2988 }
2989
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002990 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002991 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2992 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002993 final long token = Binder.clearCallingIdentity();
2994 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002995 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2996 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2997 for (WifiConfiguration config : configs) {
2998 if (Objects.equals(resolveNetworkId(config), networkId)) {
2999 config.meteredOverride = meteredOverride;
3000 wm.updateNetwork(config);
3001 }
3002 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003003 } finally {
3004 Binder.restoreCallingIdentity(token);
3005 }
3006 }
3007
Jeff Sharkey46645002011-07-27 21:11:21 -07003008 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003009 @Deprecated
3010 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3011 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3012 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3013 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003014 }
3015
Jeff Sharkey53313d72017-07-13 16:47:32 -06003016 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3017 // Verify they're not lying about package name
3018 mAppOps.checkPackage(callingUid, callingPackage);
3019
Jeff Sharkey53313d72017-07-13 16:47:32 -06003020 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003021 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003022 final long token = Binder.clearCallingIdentity();
3023 try {
3024 si = mContext.getSystemService(SubscriptionManager.class)
3025 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003026 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003027 } finally {
3028 Binder.restoreCallingIdentity(token);
3029 }
3030
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003031 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003032 if (si != null) {
3033 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3034 return;
3035 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003036 }
3037
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003038 // Second check: has the CarrierService delegated access?
3039 if (config != null) {
3040 final String overridePackage = config
3041 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3042 if (!TextUtils.isEmpty(overridePackage)
3043 && Objects.equals(overridePackage, callingPackage)) {
3044 return;
3045 }
3046 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003047
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003048 // Third check: is caller the fallback/default CarrierService?
3049 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3050 if (!TextUtils.isEmpty(defaultPackage)
3051 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003052 return;
3053 }
3054
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003055 // Fourth check: is caller a testing app?
3056 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3057 if (!TextUtils.isEmpty(testPackage)
3058 && Objects.equals(testPackage, callingPackage)) {
3059 return;
3060 }
3061
3062 // Fifth check: is caller a legacy testing app?
3063 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3064 if (!TextUtils.isEmpty(legacyTestPackage)
3065 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003066 return;
3067 }
3068
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003069 // Final check: does the caller hold a permission?
3070 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003071 }
3072
Sarah Chin7af1fd02019-09-26 11:37:13 -07003073 private void enforceSubscriptionPlanValidity(SubscriptionPlan[] plans) {
3074 // nothing to check if no plans
3075 if (plans.length == 0) {
3076 return;
3077 }
3078
3079 long applicableNetworkTypes = 0;
3080 boolean allNetworks = false;
3081 for (SubscriptionPlan plan : plans) {
3082 if (plan.getNetworkTypes() == null) {
3083 allNetworks = true;
3084 } else {
3085 if ((applicableNetworkTypes & plan.getNetworkTypesBitMask()) != 0) {
3086 throw new IllegalArgumentException(
3087 "Multiple subscription plans defined for a single network type.");
3088 } else {
3089 applicableNetworkTypes |= plan.getNetworkTypesBitMask();
3090 }
3091 }
3092 }
3093
3094 // ensure at least one plan applies for every network type
3095 if (!allNetworks) {
3096 throw new IllegalArgumentException(
3097 "No generic subscription plan that applies to all network types.");
3098 }
3099 }
3100
Jeff Sharkey53313d72017-07-13 16:47:32 -06003101 @Override
3102 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3103 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3104
Jeff Sharkey53313d72017-07-13 16:47:32 -06003105 final String fake = SystemProperties.get("fw.fake_plan");
3106 if (!TextUtils.isEmpty(fake)) {
3107 final List<SubscriptionPlan> plans = new ArrayList<>();
3108 if ("month_hard".equals(fake)) {
3109 plans.add(SubscriptionPlan.Builder
3110 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3111 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003112 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3113 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3114 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3115 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3116 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003117 plans.add(SubscriptionPlan.Builder
3118 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3119 .setTitle("G-Mobile Happy")
3120 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3121 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3122 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3123 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3124 .build());
3125 plans.add(SubscriptionPlan.Builder
3126 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3127 .setTitle("G-Mobile, Charged after limit")
3128 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3129 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3130 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3131 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3132 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003133 } else if ("month_soft".equals(fake)) {
3134 plans.add(SubscriptionPlan.Builder
3135 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3136 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3137 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3138 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003139 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3140 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3141 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3142 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3143 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003144 plans.add(SubscriptionPlan.Builder
3145 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3146 .setTitle("G-Mobile, Throttled after limit")
3147 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3148 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3149 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3150 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3151 .build());
3152 plans.add(SubscriptionPlan.Builder
3153 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3154 .setTitle("G-Mobile, No data connection after limit")
3155 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3156 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3157 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3158 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3159 .build());
3160
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003161 } else if ("month_over".equals(fake)) {
3162 plans.add(SubscriptionPlan.Builder
3163 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3164 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3165 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3166 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3167 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3168 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3169 .build());
3170 plans.add(SubscriptionPlan.Builder
3171 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3172 .setTitle("G-Mobile, Throttled after limit")
3173 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3174 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3175 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3176 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3177 .build());
3178 plans.add(SubscriptionPlan.Builder
3179 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3180 .setTitle("G-Mobile, No data connection after limit")
3181 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3182 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3183 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3184 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3185 .build());
3186
Jeff Sharkey53313d72017-07-13 16:47:32 -06003187 } else if ("month_none".equals(fake)) {
3188 plans.add(SubscriptionPlan.Builder
3189 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3190 .setTitle("G-Mobile")
3191 .build());
3192 } else if ("prepaid".equals(fake)) {
3193 plans.add(SubscriptionPlan.Builder
3194 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3195 ZonedDateTime.now().plusDays(10))
3196 .setTitle("G-Mobile")
3197 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3198 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3199 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3200 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3201 .build());
3202 } else if ("prepaid_crazy".equals(fake)) {
3203 plans.add(SubscriptionPlan.Builder
3204 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3205 ZonedDateTime.now().plusDays(10))
3206 .setTitle("G-Mobile Anytime")
3207 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3208 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3209 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3210 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3211 .build());
3212 plans.add(SubscriptionPlan.Builder
3213 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3214 ZonedDateTime.now().plusDays(20))
3215 .setTitle("G-Mobile Nickel Nights")
3216 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003217 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3218 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003219 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3220 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3221 .build());
3222 plans.add(SubscriptionPlan.Builder
3223 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3224 ZonedDateTime.now().plusDays(20))
3225 .setTitle("G-Mobile Bonus 3G")
3226 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003227 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003228 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3229 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3230 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3231 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003232 } else if ("unlimited".equals(fake)) {
3233 plans.add(SubscriptionPlan.Builder
3234 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3235 ZonedDateTime.now().plusDays(10))
3236 .setTitle("G-Mobile Awesome")
3237 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3238 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3239 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3240 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3241 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003242 }
3243 return plans.toArray(new SubscriptionPlan[plans.size()]);
3244 }
3245
Jeff Sharkey4635f102017-09-01 11:27:13 -06003246 synchronized (mNetworkPoliciesSecondLock) {
3247 // Only give out plan details to the package that defined them,
3248 // so that we don't risk leaking plans between apps. We always
3249 // let in core system components (like the Settings app).
3250 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3251 if (Objects.equals(ownerPackage, callingPackage)
3252 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3253 return mSubscriptionPlans.get(subId);
3254 } else {
3255 Log.w(TAG, "Not returning plans because caller " + callingPackage
3256 + " doesn't match owner " + ownerPackage);
3257 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003258 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003259 }
3260 }
3261
3262 @Override
3263 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3264 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003265 enforceSubscriptionPlanValidity(plans);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003266
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003267 for (SubscriptionPlan plan : plans) {
3268 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003269 }
3270
3271 final long token = Binder.clearCallingIdentity();
3272 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003273 synchronized (mUidRulesFirstLock) {
3274 synchronized (mNetworkPoliciesSecondLock) {
3275 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003276 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003277
Jeff Sharkey146bb332018-04-18 15:42:57 -06003278 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3279 if (subscriberId != null) {
3280 ensureActiveMobilePolicyAL(subId, subscriberId);
3281 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3282 } else {
3283 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3284 }
3285
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003286 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003287 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003288 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003289
3290 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3291 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3292 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3293 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003294 mHandler.sendMessage(
3295 mHandler.obtainMessage(MSG_SUBSCRIPTION_PLANS_CHANGED, subId, 0, plans));
Jeff Sharkey53313d72017-07-13 16:47:32 -06003296 } finally {
3297 Binder.restoreCallingIdentity(token);
3298 }
3299 }
3300
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003301 /**
3302 * Only visible for testing purposes. This doesn't give any access to
3303 * existing plans; it simply lets the debug package define new plans.
3304 */
3305 void setSubscriptionPlansOwner(int subId, String packageName) {
3306 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3307 }
3308
Jeff Sharkey53313d72017-07-13 16:47:32 -06003309 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003310 public String getSubscriptionPlansOwner(int subId) {
3311 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3312 throw new SecurityException();
3313 }
3314
3315 synchronized (mNetworkPoliciesSecondLock) {
3316 return mSubscriptionPlansOwner.get(subId);
3317 }
3318 }
3319
3320 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003321 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
Sarah Chin7af1fd02019-09-26 11:37:13 -07003322 long timeoutMillis, String callingPackage) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003323 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3324
3325 // We can only override when carrier told us about plans
3326 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003327 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3328 if (plan == null
3329 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003330 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003331 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003332 }
3333 }
3334
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003335 // Only allow overrides when feature is enabled. However, we always
3336 // allow disabling of overrides for safety reasons.
3337 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3338 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3339 if (overrideEnabled || overrideValue == 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003340 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3341 overrideMask, overrideValue, subId));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003342 if (timeoutMillis > 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003343 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3344 overrideMask, 0, subId), timeoutMillis);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003345 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003346 }
3347 }
3348
3349 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003350 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003351 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003352
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003353 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3354
Dianne Hackborn497175b2014-07-01 12:56:08 -07003355 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003356 for (String arg : args) {
3357 argSet.add(arg);
3358 }
3359
Felipe Lemef0823852016-06-08 13:43:08 -07003360 synchronized (mUidRulesFirstLock) {
3361 synchronized (mNetworkPoliciesSecondLock) {
3362 if (argSet.contains("--unsnooze")) {
3363 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3364 mNetworkPolicy.valueAt(i).clearSnooze();
3365 }
3366
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003367 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003368
3369 fout.println("Cleared snooze timestamps");
3370 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003371 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003372
Felipe Lemef0823852016-06-08 13:43:08 -07003373 fout.print("System ready: "); fout.println(mSystemReady);
3374 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3375 fout.print("Restrict power: "); fout.println(mRestrictPower);
3376 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003377 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3378
3379 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003380 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003381 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003382 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3383 fout.println(mNetworkPolicy.valueAt(i).toString());
3384 }
3385 fout.decreaseIndent();
3386
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003387 fout.println();
3388 fout.println("Subscription plans:");
3389 fout.increaseIndent();
3390 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3391 final int subId = mSubscriptionPlans.keyAt(i);
3392 fout.println("Subscriber ID " + subId + ":");
3393 fout.increaseIndent();
3394 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3395 if (!ArrayUtils.isEmpty(plans)) {
3396 for (SubscriptionPlan plan : plans) {
3397 fout.println(plan);
3398 }
3399 }
3400 fout.decreaseIndent();
3401 }
3402 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003403
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003404 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003405 fout.println("Active subscriptions:");
3406 fout.increaseIndent();
3407 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3408 final int subId = mSubIdToSubscriberId.keyAt(i);
3409 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3410
3411 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3412 }
3413 fout.decreaseIndent();
3414
3415 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003416 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3417 fout.println("Merged subscriptions: " + Arrays.toString(
3418 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3419 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003420
3421 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003422 fout.println("Policy for UIDs:");
3423 fout.increaseIndent();
3424 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003425 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003426 final int uid = mUidPolicy.keyAt(i);
3427 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003428 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003429 fout.print(uid);
3430 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003431 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003432 fout.println();
3433 }
3434 fout.decreaseIndent();
3435
3436 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3437 if (size > 0) {
3438 fout.println("Power save whitelist (except idle) app ids:");
3439 fout.increaseIndent();
3440 for (int i = 0; i < size; i++) {
3441 fout.print("UID=");
3442 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3443 fout.print(": ");
3444 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3445 fout.println();
3446 }
3447 fout.decreaseIndent();
3448 }
3449
3450 size = mPowerSaveWhitelistAppIds.size();
3451 if (size > 0) {
3452 fout.println("Power save whitelist app ids:");
3453 fout.increaseIndent();
3454 for (int i = 0; i < size; i++) {
3455 fout.print("UID=");
3456 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3457 fout.print(": ");
3458 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3459 fout.println();
3460 }
3461 fout.decreaseIndent();
3462 }
3463
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003464 size = mAppIdleTempWhitelistAppIds.size();
3465 if (size > 0) {
3466 fout.println("App idle whitelist app ids:");
3467 fout.increaseIndent();
3468 for (int i = 0; i < size; i++) {
3469 fout.print("UID=");
3470 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3471 fout.print(": ");
3472 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3473 fout.println();
3474 }
3475 fout.decreaseIndent();
3476 }
3477
Felipe Lemef0823852016-06-08 13:43:08 -07003478 size = mDefaultRestrictBackgroundWhitelistUids.size();
3479 if (size > 0) {
3480 fout.println("Default restrict background whitelist uids:");
3481 fout.increaseIndent();
3482 for (int i = 0; i < size; i++) {
3483 fout.print("UID=");
3484 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3485 fout.println();
3486 }
3487 fout.decreaseIndent();
3488 }
3489
3490 size = mRestrictBackgroundWhitelistRevokedUids.size();
3491 if (size > 0) {
3492 fout.println("Default restrict background whitelist uids revoked by users:");
3493 fout.increaseIndent();
3494 for (int i = 0; i < size; i++) {
3495 fout.print("UID=");
3496 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3497 fout.println();
3498 }
3499 fout.decreaseIndent();
3500 }
3501
3502 final SparseBooleanArray knownUids = new SparseBooleanArray();
3503 collectKeys(mUidState, knownUids);
3504 collectKeys(mUidRules, knownUids);
3505
3506 fout.println("Status for all known UIDs:");
3507 fout.increaseIndent();
3508 size = knownUids.size();
3509 for (int i = 0; i < size; i++) {
3510 final int uid = knownUids.keyAt(i);
3511 fout.print("UID=");
3512 fout.print(uid);
3513
3514 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3515 fout.print(" state=");
3516 fout.print(state);
3517 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3518 fout.print(" (fg)");
3519 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003520 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003521 ? " (fg svc)" : " (bg)");
3522 }
3523
3524 final int uidRules = mUidRules.get(uid, RULE_NONE);
3525 fout.print(" rules=");
3526 fout.print(uidRulesToString(uidRules));
3527 fout.println();
3528 }
3529 fout.decreaseIndent();
3530
3531 fout.println("Status for just UIDs with rules:");
3532 fout.increaseIndent();
3533 size = mUidRules.size();
3534 for (int i = 0; i < size; i++) {
3535 final int uid = mUidRules.keyAt(i);
3536 fout.print("UID=");
3537 fout.print(uid);
3538 final int uidRules = mUidRules.get(uid, RULE_NONE);
3539 fout.print(" rules=");
3540 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003541 fout.println();
3542 }
3543 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003544
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003545 fout.println("Admin restricted uids for metered data:");
3546 fout.increaseIndent();
3547 size = mMeteredRestrictedUids.size();
3548 for (int i = 0; i < size; ++i) {
3549 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3550 fout.println(mMeteredRestrictedUids.valueAt(i));
3551 }
3552 fout.decreaseIndent();
3553
Makoto Onuki49392d32018-04-11 13:51:02 -07003554 fout.println();
3555 mStatLogger.dump(fout);
3556
Sudheer Shanka352dc572017-09-22 17:09:38 -07003557 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003558 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003559 }
3560 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003561
3562 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003563 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003564 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003565 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003566 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003567 }
3568
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003569 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003570 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003571 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003572 return isUidStateForeground(
3573 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003574 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003575 }
3576
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003577 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003578 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003579 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003580 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003581 }
3582
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003583 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003584 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003585 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3586 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3587 }
3588
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003589 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003590 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003591 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003592 }
3593
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003594 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003595 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003596 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003597 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003598 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003599 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003600 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003601 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3602 try {
3603 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3604 if (oldUidState != uidState) {
3605 // state changed, push updated rules
3606 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003607 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3608 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3609 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003610 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003611 if (mDeviceIdleMode) {
3612 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003613 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003614 if (mRestrictPower) {
3615 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003616 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003617 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003618 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003619 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003620 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003621 } finally {
3622 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003623 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003624 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003625 }
3626
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003627 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003628 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003629 final int index = mUidState.indexOfKey(uid);
3630 if (index >= 0) {
3631 final int oldUidState = mUidState.valueAt(index);
3632 mUidState.removeAt(index);
3633 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003634 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003635 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003636 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003637 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003638 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003639 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003640 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003641 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003642 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003643 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003645 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003646 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003647 }
3648
Felipe Lemef28983d2016-03-25 12:18:23 -07003649 // adjust stats accounting based on foreground status
3650 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003651 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3652 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3653 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3654 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003655 try {
3656 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003657 } finally {
3658 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003659 }
3660 }
3661
Sudheer Shankac9d94072017-02-22 22:13:55 +00003662 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3663 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003664 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003665 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003666 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003667 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003668 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003669 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003670 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003671 }
3672
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003673 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003674 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003675 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3676 try {
3677 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3678 mUidFirewallPowerSaveRules);
3679 } finally {
3680 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3681 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003682 }
3683
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003684 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003685 void updateRuleForRestrictPowerUL(int uid) {
3686 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003687 }
3688
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003689 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003690 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003691 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3692 try {
3693 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3694 mUidFirewallDozableRules);
3695 } finally {
3696 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3697 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003698 }
3699
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003700 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003701 void updateRuleForDeviceIdleUL(int uid) {
3702 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003703 }
3704
Felipe Lemef28983d2016-03-25 12:18:23 -07003705 // NOTE: since both fw_dozable and fw_powersave uses the same map
3706 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003707 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003708 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003709 SparseIntArray rules) {
3710 if (enabled) {
3711 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003712 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003713 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003714 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003715 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003716 for (int ui = users.size() - 1; ui >= 0; ui--) {
3717 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003718 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3719 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3720 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3721 updateRulesForWhitelistedAppIds(uidRules,
3722 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003723 }
3724 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003725 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003726 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003727 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3728 }
3729 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003730 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003731 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003732 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003733 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003734 }
3735
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003736 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3737 final SparseBooleanArray whitelistedAppIds, int userId) {
3738 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3739 if (whitelistedAppIds.valueAt(i)) {
3740 final int appId = whitelistedAppIds.keyAt(i);
3741 final int uid = UserHandle.getUid(userId, appId);
3742 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3743 }
3744 }
3745 }
3746
3747 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003748 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3749 * mode, and app idle).
3750 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003751 * @param deviceIdleMode if true then we don't consider
3752 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3753 * whitelisted.
3754 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003755 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003756 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003757 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003758 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3759 || mPowerSaveWhitelistAppIds.get(appId);
3760 if (!deviceIdleMode) {
3761 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3762 }
3763 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003764 }
3765
Felipe Lemef28983d2016-03-25 12:18:23 -07003766 // NOTE: since both fw_dozable and fw_powersave uses the same map
3767 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003768 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003769 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003770 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003771 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003772 chain == FIREWALL_CHAIN_DOZABLE);
3773 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003774 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003775 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003776 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003777 }
3778 }
3779 }
3780
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003781 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003782 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003783 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3784 try {
3785 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3786 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003787
Felipe Leme873a83a2016-09-07 11:34:10 -07003788 // Fully update the app idle firewall chain.
3789 final List<UserInfo> users = mUserManager.getUsers();
3790 for (int ui = users.size() - 1; ui >= 0; ui--) {
3791 UserInfo user = users.get(ui);
3792 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3793 for (int uid : idleUids) {
3794 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3795 // quick check: if this uid doesn't have INTERNET permission, it
3796 // doesn't have network access anyway, so it is a waste to mess
3797 // with it here.
3798 if (hasInternetPermissions(uid)) {
3799 uidRules.put(uid, FIREWALL_RULE_DENY);
3800 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003801 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003802 }
3803 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003804
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003805 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003806 } finally {
3807 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3808 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003809 }
3810
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003811 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003812 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003813 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003814
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003815 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3816 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3817 }
3818 try {
3819 int appId = UserHandle.getAppId(uid);
3820 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3821 && !isUidForegroundOnRestrictPowerUL(uid)) {
3822 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003823 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003824 } else {
3825 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003826 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003827 }
3828 } finally {
3829 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003830 }
3831 }
3832
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003833 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003834 * Update rules that might be changed by {@link #mRestrictBackground},
3835 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003836 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003837 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003838 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003839 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3840 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3841 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3842 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003843 try {
Felipe Leme09700462016-09-08 09:33:48 -07003844 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003845 updateRulesForRestrictPowerUL();
3846 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003847
Felipe Leme873a83a2016-09-07 11:34:10 -07003848 // If the set of restricted networks may have changed, re-evaluate those.
3849 if (restrictedNetworksChanged) {
3850 normalizePoliciesNL();
3851 updateNetworkRulesNL();
3852 }
3853 } finally {
3854 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003855 }
3856 }
3857
Felipe Leme09700462016-09-08 09:33:48 -07003858 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003859 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003860 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003861 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3862 try {
3863 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003864 updateRulesForPowerSaveUL();
3865 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3866 } finally {
3867 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3868 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003869 }
3870
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003871 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003872 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003873 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3874 try {
3875 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3876 } finally {
3877 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3878 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003879 }
3880
3881 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3882 private static final int TYPE_RESTRICT_POWER = 2;
3883 @Retention(RetentionPolicy.SOURCE)
3884 @IntDef(flag = false, value = {
3885 TYPE_RESTRICT_BACKGROUND,
3886 TYPE_RESTRICT_POWER,
3887 })
3888 public @interface RestrictType {
3889 }
3890
3891 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003892 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003893 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003894 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3895 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3896 }
3897 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003898 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003899
3900 final PackageManager pm = mContext.getPackageManager();
3901 final List<UserInfo> users;
3902 final List<ApplicationInfo> apps;
3903
3904 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3905 try {
3906 users = mUserManager.getUsers();
3907 } finally {
3908 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3909 }
3910 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3911 try {
3912 apps = pm.getInstalledApplications(
3913 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3914 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3915 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3916 } finally {
3917 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3918 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003919
Felipe Leme873a83a2016-09-07 11:34:10 -07003920 final int usersSize = users.size();
3921 final int appsSize = apps.size();
3922 for (int i = 0; i < usersSize; i++) {
3923 final UserInfo user = users.get(i);
3924 for (int j = 0; j < appsSize; j++) {
3925 final ApplicationInfo app = apps.get(j);
3926 final int uid = UserHandle.getUid(user.id, app.uid);
3927 switch (type) {
3928 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003929 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003930 break;
3931 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003932 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003933 break;
3934 default:
3935 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3936 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003937 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003938 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003939 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003940 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003941 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003942 }
3943
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003944 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003945 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003946 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003947 final int numUsers = users.size();
3948 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003949 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003950 int uid = UserHandle.getUid(user.id, appId);
3951 // Update external firewall rules.
3952 updateRuleForAppIdleUL(uid);
3953 updateRuleForDeviceIdleUL(uid);
3954 updateRuleForRestrictPowerUL(uid);
3955 // Update internal rules.
3956 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003957 }
3958 }
3959
Felipe Leme70c57c22016-03-29 10:45:13 -07003960 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3961 // methods below could be merged into a isUidValidForRules() method.
3962 private boolean isUidValidForBlacklistRules(int uid) {
3963 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003964 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003965 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003966 return true;
3967 }
3968
3969 return false;
3970 }
3971
Felipe Leme70c57c22016-03-29 10:45:13 -07003972 private boolean isUidValidForWhitelistRules(int uid) {
3973 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3974 }
3975
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003976 /**
3977 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3978 * power saving restrictions may still apply.
3979 */
3980 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003981 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003982 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3983
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003984 synchronized (mUidRulesFirstLock) {
3985 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3986 // No change.
3987 return;
3988 }
3989
3990 final long token = Binder.clearCallingIdentity();
3991 try {
3992 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3993 if (shouldWhitelist) {
3994 mAppIdleTempWhitelistAppIds.put(uid, true);
3995 } else {
3996 mAppIdleTempWhitelistAppIds.delete(uid);
3997 }
3998 updateRuleForAppIdleUL(uid);
3999 updateRulesForPowerRestrictionsUL(uid);
4000 } finally {
4001 Binder.restoreCallingIdentity(token);
4002 }
4003 }
4004 }
4005
4006 /** Return the list of UIDs currently in the app idle whitelist. */
4007 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004008 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004009 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4010
4011 synchronized (mUidRulesFirstLock) {
4012 final int len = mAppIdleTempWhitelistAppIds.size();
4013 int[] uids = new int[len];
4014 for (int i = 0; i < len; ++i) {
4015 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4016 }
4017 return uids;
4018 }
4019 }
4020
4021 /** Returns if the UID is currently considered idle. */
4022 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004023 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004024 synchronized (mUidRulesFirstLock) {
4025 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4026 // UID is temporarily whitelisted.
4027 return false;
4028 }
4029 }
4030
Amith Yamasani15e472352015-04-24 19:06:07 -07004031 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4032 final int userId = UserHandle.getUserId(uid);
4033
songjinshi0655edd2016-05-18 19:55:32 +08004034 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004035 for (String packageName : packages) {
4036 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4037 return false;
4038 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004039 }
4040 }
4041 return true;
4042 }
4043
4044 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004045 * Checks if an uid has INTERNET permissions.
4046 * <p>
4047 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004048 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004049 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004050 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004051 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004052 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004053 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004054 }
4055 } catch (RemoteException e) {
4056 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004057 return true;
4058 }
4059
4060 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004061 * Clears all state - internal and external - associated with an UID.
4062 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004063 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004064 private void onUidDeletedUL(int uid) {
4065 // First cleanup in-memory state synchronously...
4066 mUidRules.delete(uid);
4067 mUidPolicy.delete(uid);
4068 mUidFirewallStandbyRules.delete(uid);
4069 mUidFirewallDozableRules.delete(uid);
4070 mUidFirewallPowerSaveRules.delete(uid);
4071 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4072 mPowerSaveWhitelistAppIds.delete(uid);
4073 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004074 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004075
4076 // ...then update iptables asynchronously.
4077 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4078 }
4079
4080 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004081 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004082 *
Felipe Leme781ba142016-05-09 16:24:48 -07004083 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004084 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004085 * <li>Doze mode
4086 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004087 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004088 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004089 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004090 *
4091 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004092 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004093 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004094 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004095 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004096 updateRuleForDeviceIdleUL(uid);
4097 updateRuleForAppIdleUL(uid);
4098 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004099
4100 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004101 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004102
4103 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004104 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004105 }
4106
Felipe Leme70c57c22016-03-29 10:45:13 -07004107 /**
4108 * Applies network rules to bandwidth controllers based on process state and user-defined
4109 * restrictions (blacklist / whitelist).
4110 *
4111 * <p>
4112 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4113 * networks:
4114 * <ul>
4115 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4116 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4117 * also blacklisted.
4118 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004119 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004120 * <ul>
4121 *
4122 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4123 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4124 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4125 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004126 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004127 * {@link INetworkManagementService}, but this method should also be called in events (like
4128 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4129 * following rules should also be applied:
4130 *
4131 * <ul>
4132 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4133 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4134 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4135 * {@code bw_penalty_box}.
4136 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4137 * </ul>
4138 *
4139 * <p>For optimization, the rules are only applied on user apps that have internet access
4140 * permission, since there is no need to change the {@code iptables} rule if the app does not
4141 * have permission to use the internet.
4142 *
4143 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004144 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004145 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004146 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004147 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4148 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4149 "updateRulesForDataUsageRestrictionsUL: " + uid);
4150 }
4151 try {
4152 updateRulesForDataUsageRestrictionsULInner(uid);
4153 } finally {
4154 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4155 }
4156 }
4157
4158 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004159 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004160 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004161 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004162 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004163
Dianne Hackborn497175b2014-07-01 12:56:08 -07004164 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004165 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004166 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004167 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004168
Felipe Leme781ba142016-05-09 16:24:48 -07004169 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004170 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004171 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4172 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004173
Felipe Leme70c57c22016-03-29 10:45:13 -07004174 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004175 if (isRestrictedByAdmin) {
4176 newRule = RULE_REJECT_METERED;
4177 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004178 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4179 newRule = RULE_TEMPORARY_ALLOW_METERED;
4180 } else if (isWhitelisted) {
4181 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004182 }
4183 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004184 if (isBlacklisted) {
4185 newRule = RULE_REJECT_METERED;
4186 } else if (mRestrictBackground && isWhitelisted) {
4187 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004188 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004189 }
Felipe Leme781ba142016-05-09 16:24:48 -07004190 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004191
Felipe Lemef28983d2016-03-25 12:18:23 -07004192 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004193 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004194 + ": isForeground=" +isForeground
4195 + ", isBlacklisted=" + isBlacklisted
4196 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004197 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004198 + ", oldRule=" + uidRulesToString(oldRule)
4199 + ", newRule=" + uidRulesToString(newRule)
4200 + ", newUidRules=" + uidRulesToString(newUidRules)
4201 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004202 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004203
Felipe Leme46c4fc32016-05-04 09:21:43 -07004204 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004205 mUidRules.delete(uid);
4206 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004207 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004208 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004209
Felipe Leme70c57c22016-03-29 10:45:13 -07004210 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004211 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004212 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004213 // Temporarily whitelist foreground app, removing from blacklist if necessary
4214 // (since bw_penalty_box prevails over bw_happy_box).
4215
4216 setMeteredNetworkWhitelist(uid, true);
4217 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4218 // but ideally it should be just:
4219 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004220 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004221 setMeteredNetworkBlacklist(uid, false);
4222 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004223 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004224 // Remove temporary whitelist from app that is not on foreground anymore.
4225
4226 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4227 // but ideally they should be just:
4228 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4229 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004230 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004231 setMeteredNetworkWhitelist(uid, false);
4232 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004233 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004234 setMeteredNetworkBlacklist(uid, true);
4235 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004236 } else if (hasRule(newRule, RULE_REJECT_METERED)
4237 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004238 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004239 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004240 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004241 // Since blacklist prevails over whitelist, we need to handle the special case
4242 // where app is whitelisted and blacklisted at the same time (although such
4243 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004244 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004245 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004246 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4247 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004248 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004249 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004250 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004251 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004252 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4253 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004254 + ", whitelisted=" + isWhitelisted
4255 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004256 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004257 + ", newRule=" + uidRulesToString(newUidRules)
4258 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004259 }
Felipe Leme781ba142016-05-09 16:24:48 -07004260
Sudheer Shankac9d94072017-02-22 22:13:55 +00004261 // Dispatch changed rule to existing listeners.
4262 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004263 }
4264 }
4265
4266 /**
4267 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4268 * listeners in case of change.
4269 * <p>
4270 * There are 3 power-related rules that affects whether an app has background access on
4271 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4272 * restriction, it's added to the equivalent firewall chain:
4273 * <ul>
4274 * <li>App is idle: {@code fw_standby} firewall chain.
4275 * <li>Device is idle: {@code fw_dozable} firewall chain.
4276 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4277 * </ul>
4278 * <p>
4279 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4280 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4281 * <p>
4282 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4283 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004284 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004285 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004286 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4287
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004288 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004289
Sudheer Shankac9d94072017-02-22 22:13:55 +00004290 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004291 mUidRules.delete(uid);
4292 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004293 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004294 }
4295 }
4296
4297 /**
4298 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4299 *
4300 * @param uid the uid of the app to update rules for
4301 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004302 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004303 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004304 */
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004305 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004306 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4307 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004308 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004309 }
4310 try {
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004311 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004312 } finally {
4313 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4314 }
4315 }
4316
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004317 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules) {
Felipe Leme781ba142016-05-09 16:24:48 -07004318 if (!isUidValidForBlacklistRules(uid)) {
4319 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004320 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004321 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004322
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004323 final boolean isIdle = isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004324 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004325 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004326
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004327 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004328 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4329 int newRule = RULE_NONE;
4330
4331 // First step: define the new rule based on user restrictions and foreground state.
4332
4333 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4334 // by considering the foreground and non-foreground states.
4335 if (isForeground) {
4336 if (restrictMode) {
4337 newRule = RULE_ALLOW_ALL;
4338 }
4339 } else if (restrictMode) {
4340 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4341 }
4342
4343 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4344
4345 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004346 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004347 + ", isIdle: " + isIdle
4348 + ", mRestrictPower: " + mRestrictPower
4349 + ", mDeviceIdleMode: " + mDeviceIdleMode
4350 + ", isForeground=" + isForeground
4351 + ", isWhitelisted=" + isWhitelisted
4352 + ", oldRule=" + uidRulesToString(oldRule)
4353 + ", newRule=" + uidRulesToString(newRule)
4354 + ", newUidRules=" + uidRulesToString(newUidRules)
4355 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4356 }
4357
Felipe Leme781ba142016-05-09 16:24:48 -07004358 // Second step: notify listeners if state changed.
4359 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004360 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004361 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004362 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004363 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4364 } else {
4365 // All scenarios should have been covered above
4366 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4367 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004368 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004369 + ", newRule=" + uidRulesToString(newUidRules)
4370 + ", oldRule=" + uidRulesToString(oldUidRules));
4371 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004372 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004373 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004374
Sudheer Shankac9d94072017-02-22 22:13:55 +00004375 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004376 }
4377
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004378 private class AppIdleStateChangeListener
4379 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4380
4381 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004382 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4383 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004384 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004385 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4386 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004387 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004388 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004389 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004390 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004391 }
4392 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004393 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004394 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004395 }
4396
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004397 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4398 if (listener != null) {
4399 try {
4400 listener.onUidRulesChanged(uid, uidRules);
4401 } catch (RemoteException ignored) {
4402 }
4403 }
4404 }
4405
4406 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4407 String[] meteredIfaces) {
4408 if (listener != null) {
4409 try {
4410 listener.onMeteredIfacesChanged(meteredIfaces);
4411 } catch (RemoteException ignored) {
4412 }
4413 }
4414 }
4415
4416 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4417 boolean restrictBackground) {
4418 if (listener != null) {
4419 try {
4420 listener.onRestrictBackgroundChanged(restrictBackground);
4421 } catch (RemoteException ignored) {
4422 }
4423 }
4424 }
4425
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004426 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4427 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004428 if (listener != null) {
4429 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004430 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004431 } catch (RemoteException ignored) {
4432 }
4433 }
4434 }
4435
Jeff Sharkey9252b342018-01-19 07:58:35 +09004436 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
Sarah Chin7af1fd02019-09-26 11:37:13 -07004437 int overrideMask, int overrideValue) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09004438 if (listener != null) {
4439 try {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004440 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4441 } catch (RemoteException ignored) {
4442 }
4443 }
4444 }
4445
4446 private void dispatchSubscriptionPlansChanged(INetworkPolicyListener listener, int subId,
4447 SubscriptionPlan[] plans) {
4448 if (listener != null) {
4449 try {
4450 listener.onSubscriptionPlansChanged(subId, plans);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004451 } catch (RemoteException ignored) {
4452 }
4453 }
4454 }
4455
Makoto Onuki8e777332017-03-28 11:25:47 -07004456 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004457 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004458 public boolean handleMessage(Message msg) {
4459 switch (msg.what) {
4460 case MSG_RULES_CHANGED: {
4461 final int uid = msg.arg1;
4462 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004463 final int length = mListeners.beginBroadcast();
4464 for (int i = 0; i < length; i++) {
4465 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4466 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004467 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004468 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004469 return true;
4470 }
4471 case MSG_METERED_IFACES_CHANGED: {
4472 final String[] meteredIfaces = (String[]) msg.obj;
4473 final int length = mListeners.beginBroadcast();
4474 for (int i = 0; i < length; i++) {
4475 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004476 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004477 }
4478 mListeners.finishBroadcast();
4479 return true;
4480 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004481 case MSG_LIMIT_REACHED: {
4482 final String iface = (String) msg.obj;
4483
Felipe Lemef0823852016-06-08 13:43:08 -07004484 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004485 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004486 // force stats update to make sure we have
4487 // numbers that caused alert to trigger.
4488 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004489
Felipe Lemef0823852016-06-08 13:43:08 -07004490 updateNetworkEnabledNL();
4491 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004492 }
4493 }
4494 return true;
4495 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004496 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4497 final boolean restrictBackground = msg.arg1 != 0;
4498 final int length = mListeners.beginBroadcast();
4499 for (int i = 0; i < length; i++) {
4500 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004501 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004502 }
4503 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004504 final Intent intent =
4505 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4506 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4507 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4508 return true;
4509 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004510 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004511 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004512 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004513 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004514 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004515 final int length = mListeners.beginBroadcast();
4516 for (int i = 0; i < length; i++) {
4517 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004518 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004519 }
4520 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004521 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4522 if (notifyApp.booleanValue()) {
4523 broadcastRestrictBackgroundChanged(uid, notifyApp);
4524 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004525 return true;
4526 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004527 case MSG_ADVISE_PERSIST_THRESHOLD: {
4528 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004529 // make sure stats are recorded frequently enough; we aim
4530 // for 2MB threshold for 2GB/month rules.
4531 final long persistThreshold = lowestRule / 1000;
4532 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004533 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004534 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004535 case MSG_UPDATE_INTERFACE_QUOTA: {
4536 removeInterfaceQuota((String) msg.obj);
4537 // int params need to be stitched back into a long
4538 setInterfaceQuota((String) msg.obj,
4539 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4540 return true;
4541 }
4542 case MSG_REMOVE_INTERFACE_QUOTA: {
4543 removeInterfaceQuota((String) msg.obj);
4544 return true;
4545 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004546 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4547 resetUidFirewallRules(msg.arg1);
4548 return true;
4549 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004550 case MSG_SUBSCRIPTION_OVERRIDE: {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004551 final int overrideMask = msg.arg1;
4552 final int overrideValue = msg.arg2;
4553 final int subId = (int) msg.obj;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004554 final int length = mListeners.beginBroadcast();
4555 for (int i = 0; i < length; i++) {
4556 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Sarah Chin7af1fd02019-09-26 11:37:13 -07004557 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004558 }
4559 mListeners.finishBroadcast();
4560 return true;
4561 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004562 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4563 final int userId = msg.arg1;
4564 final Set<String> packageNames = (Set<String>) msg.obj;
4565 setMeteredRestrictedPackagesInternal(packageNames, userId);
4566 return true;
4567 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004568 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4569 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4570 final boolean enabled = msg.arg1 != 0;
4571 setNetworkTemplateEnabledInner(template, enabled);
4572 return true;
4573 }
Sarah Chin7af1fd02019-09-26 11:37:13 -07004574 case MSG_SUBSCRIPTION_PLANS_CHANGED: {
4575 final SubscriptionPlan[] plans = (SubscriptionPlan[]) msg.obj;
4576 final int subId = msg.arg1;
4577 final int length = mListeners.beginBroadcast();
4578 for (int i = 0; i < length; i++) {
4579 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4580 dispatchSubscriptionPlansChanged(listener, subId, plans);
4581 }
4582 mListeners.finishBroadcast();
4583 return true;
4584 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004585 default: {
4586 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004587 }
4588 }
4589 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004590 };
4591
4592 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4593 @Override
4594 public boolean handleMessage(Message msg) {
4595 switch (msg.what) {
4596 case UID_MSG_STATE_CHANGED: {
4597 final int uid = msg.arg1;
4598 final int procState = msg.arg2;
4599 final long procStateSeq = (Long) msg.obj;
4600
4601 handleUidChanged(uid, procState, procStateSeq);
4602 return true;
4603 }
4604 case UID_MSG_GONE: {
4605 final int uid = msg.arg1;
4606 handleUidGone(uid);
4607 return true;
4608 }
4609 default: {
4610 return false;
4611 }
4612 }
4613 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004614 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004615
Makoto Onuki8e777332017-03-28 11:25:47 -07004616 void handleUidChanged(int uid, int procState, long procStateSeq) {
4617 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4618 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004619 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004620 synchronized (mUidRulesFirstLock) {
4621 // We received a uid state change callback, add it to the history so that it
4622 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004623 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004624 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004625 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004626 // Updating the network rules is done, so notify AMS about this.
4627 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4628 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004629 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4630 // called from the handler, so there's no multi-threading issue.
4631 if (updated) {
4632 updateNetworkStats(uid, isUidStateForeground(procState));
4633 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004634 } finally {
4635 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4636 }
4637 }
4638
4639 void handleUidGone(int uid) {
4640 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4641 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004642 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004643 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004644 updated = removeUidStateUL(uid);
4645 }
4646 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4647 // called from the handler, so there's no multi-threading issue.
4648 if (updated) {
4649 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004650 }
4651 } finally {
4652 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4653 }
4654 }
4655
Felipe Leme57e3d312016-08-23 14:42:52 -07004656 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4657 final PackageManager pm = mContext.getPackageManager();
4658 final String[] packages = pm.getPackagesForUid(uid);
4659 if (packages != null) {
4660 final int userId = UserHandle.getUserId(uid);
4661 for (String packageName : packages) {
4662 final Intent intent =
4663 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4664 intent.setPackage(packageName);
4665 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4666 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4667 }
4668 }
4669 }
4670
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004671 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4672 // long quotaBytes split up into two ints to fit in message
4673 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4674 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4675 }
4676
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004677 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004678 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004679 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004680 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004681 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004682 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004683 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004684 }
4685 }
4686
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004687 private void removeInterfaceQuotaAsync(String iface) {
4688 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4689 }
4690
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004691 private void removeInterfaceQuota(String iface) {
4692 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004693 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004694 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004695 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004696 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004697 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004698 }
4699 }
4700
Felipe Leme70c57c22016-03-29 10:45:13 -07004701 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4702 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004703 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004704 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004705 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004706 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4707 } catch (RemoteException e) {
4708 // ignored; service lives in system_server
4709 }
4710 }
4711
4712 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4713 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4714 try {
4715 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4716 } catch (IllegalStateException e) {
4717 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004718 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004719 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004720 }
4721 }
4722
Felipe Lemebc853dd2016-09-08 13:26:55 -07004723 private static final int CHAIN_TOGGLE_NONE = 0;
4724 private static final int CHAIN_TOGGLE_ENABLE = 1;
4725 private static final int CHAIN_TOGGLE_DISABLE = 2;
4726 @Retention(RetentionPolicy.SOURCE)
4727 @IntDef(flag = false, value = {
4728 CHAIN_TOGGLE_NONE,
4729 CHAIN_TOGGLE_ENABLE,
4730 CHAIN_TOGGLE_DISABLE
4731 })
4732 public @interface ChainToggleType {
4733 }
4734
4735 /**
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004736 * Calls {@link #setUidFirewallRulesUL(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004737 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004738 *
4739 * @param chain firewall chain.
4740 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4741 * @param toggle whether the chain should be enabled, disabled, or not changed.
4742 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004743 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004744 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004745 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004746 if (uidRules != null) {
4747 setUidFirewallRulesUL(chain, uidRules);
4748 }
4749 if (toggle != CHAIN_TOGGLE_NONE) {
4750 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4751 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004752 }
4753
Amith Yamasani15e472352015-04-24 19:06:07 -07004754 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004755 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4756 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4757 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004758 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004759 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004760 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004761 int size = uidRules.size();
4762 int[] uids = new int[size];
4763 int[] rules = new int[size];
4764 for(int index = size - 1; index >= 0; --index) {
4765 uids[index] = uidRules.keyAt(index);
4766 rules[index] = uidRules.valueAt(index);
4767 }
4768 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004769 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004770 } catch (IllegalStateException e) {
4771 Log.wtf(TAG, "problem setting firewall uid rules", e);
4772 } catch (RemoteException e) {
4773 // ignored; service lives in system_server
4774 }
4775 }
4776
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004777 /**
4778 * Add or remove a uid to the firewall blacklist for all network ifaces.
4779 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004780 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004781 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4782 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4783 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004784 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004785 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004786 if (chain == FIREWALL_CHAIN_DOZABLE) {
4787 mUidFirewallDozableRules.put(uid, rule);
4788 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4789 mUidFirewallStandbyRules.put(uid, rule);
4790 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4791 mUidFirewallPowerSaveRules.put(uid, rule);
4792 }
4793
4794 try {
4795 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004796 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004797 } catch (IllegalStateException e) {
4798 Log.wtf(TAG, "problem setting firewall uid rules", e);
4799 } catch (RemoteException e) {
4800 // ignored; service lives in system_server
4801 }
4802 } finally {
4803 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004804 }
4805 }
4806
4807 /**
4808 * Add or remove a uid to the firewall blacklist for all network ifaces.
4809 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004810 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004811 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004812 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4813 mFirewallChainStates.get(chain) == enable) {
4814 // All is the same, nothing to do.
4815 return;
4816 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004817 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004818 try {
4819 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004820 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004821 } catch (IllegalStateException e) {
4822 Log.wtf(TAG, "problem enable firewall chain", e);
4823 } catch (RemoteException e) {
4824 // ignored; service lives in system_server
4825 }
4826 }
4827
Felipe Leme03e95e22016-09-09 09:25:31 -07004828 /**
4829 * Resets all firewall rules associated with an UID.
4830 */
4831 private void resetUidFirewallRules(int uid) {
4832 try {
4833 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4834 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4835 mNetworkManager
4836 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4837 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4838 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4839 } catch (IllegalStateException e) {
4840 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4841 } catch (RemoteException e) {
4842 // ignored; service lives in system_server
4843 }
4844 }
4845
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004846 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004847 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004848 return getNetworkTotalBytes(template, start, end);
4849 }
4850
4851 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004852 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004853 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004854 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004855 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004856 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004857 }
4858 }
4859
4860 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4861 try {
4862 return mNetworkStats.getNetworkUidBytes(template, start, end);
4863 } catch (RuntimeException e) {
4864 Slog.w(TAG, "Failed to read network stats: " + e);
4865 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004866 }
4867 }
4868
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004869 private boolean isBandwidthControlEnabled() {
4870 final long token = Binder.clearCallingIdentity();
4871 try {
4872 return mNetworkManager.isBandwidthControlEnabled();
4873 } catch (RemoteException e) {
4874 // ignored; service lives in system_server
4875 return false;
4876 } finally {
4877 Binder.restoreCallingIdentity(token);
4878 }
4879 }
4880
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004881 private static Intent buildAllowBackgroundDataIntent() {
4882 return new Intent(ACTION_ALLOW_BACKGROUND);
4883 }
4884
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004885 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4886 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004887 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4888 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4889 return intent;
4890 }
4891
4892 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4893 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4894 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004895 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4896 return intent;
4897 }
4898
Wei Liu546cb772016-07-21 16:19:01 -07004899 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004900 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004901 intent.setComponent(ComponentName.unflattenFromString(
4902 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004903 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4904 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4905 return intent;
4906 }
4907
Wei Liu546cb772016-07-21 16:19:01 -07004908 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004909 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004910 intent.setComponent(ComponentName.unflattenFromString(
4911 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004912 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4913 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4914 return intent;
4915 }
4916
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004917 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004918 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004919 mHandler.getLooper().getQueue().addIdleHandler(handler);
4920 }
4921
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004922 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004923 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004924 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
Kweku Adams25fa3a72019-07-12 17:00:17 -07004925 if (mRestrictBackgroundLowPowerMode == result.batterySaverEnabled) {
4926 // Nothing changed. Nothing to do.
4927 return;
4928 }
4929 mRestrictBackgroundLowPowerMode = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004930
Kweku Adams25fa3a72019-07-12 17:00:17 -07004931 boolean restrictBackground = mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004932 boolean shouldInvokeRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -07004933 // store the temporary mRestrictBackgroundChangedInBsm and update it at the end.
jackqdyulei29c82ab2017-03-10 14:09:16 -08004934 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4935
Kweku Adams25fa3a72019-07-12 17:00:17 -07004936 if (mRestrictBackgroundLowPowerMode) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004937 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4938 // turn it on.
Kweku Adams25fa3a72019-07-12 17:00:17 -07004939 shouldInvokeRestrictBackground = !mRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004940 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4941 localRestrictBgChangedInBsm = false;
4942 } else {
4943 // Try to restore the restrictBackground if it doesn't change in bsm
4944 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4945 restrictBackground = mRestrictBackgroundBeforeBsm;
4946 }
4947
4948 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004949 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004950 }
4951
4952 // Change it at last so setRestrictBackground() won't affect this variable
4953 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4954 }
4955
Jeff Sharkey1b861272011-05-22 00:34:52 -07004956 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4957 final int size = source.size();
4958 for (int i = 0; i < size; i++) {
4959 target.put(source.keyAt(i), true);
4960 }
4961 }
4962
Stuart Scottf1fb3972015-04-02 18:00:02 -07004963 @Override
4964 public void factoryReset(String subscriber) {
4965 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4966
Stuart Scotte3e314d2015-04-20 14:07:45 -07004967 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4968 return;
4969 }
4970
Stuart Scottf1fb3972015-04-02 18:00:02 -07004971 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004972 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004973 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4974 for (NetworkPolicy policy : policies) {
4975 if (policy.template.equals(template)) {
4976 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4977 policy.inferred = false;
4978 policy.clearSnooze();
4979 }
4980 }
4981 setNetworkPolicies(policies);
4982
4983 // Turn restrict background data off
4984 setRestrictBackground(false);
4985
Stuart Scotte3e314d2015-04-20 14:07:45 -07004986 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4987 // Remove app's "restrict background data" flag
4988 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4989 setUidPolicy(uid, POLICY_NONE);
4990 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004991 }
4992 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004993
Sudheer Shankab8f23162017-08-04 13:30:10 -07004994 @Override
4995 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004996 final long startTime = mStatLogger.getTime();
4997
Sudheer Shankab8f23162017-08-04 13:30:10 -07004998 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004999 final int uidRules;
5000 final boolean isBackgroundRestricted;
5001 synchronized (mUidRulesFirstLock) {
5002 uidRules = mUidRules.get(uid, RULE_NONE);
5003 isBackgroundRestricted = mRestrictBackground;
5004 }
junyulai05986c62018-08-07 19:50:45 +08005005 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5006 isBackgroundRestricted, mLogger);
5007
5008 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5009
5010 return ret;
5011 }
5012
5013 private static boolean isSystem(int uid) {
5014 return uid < Process.FIRST_APPLICATION_UID;
5015 }
5016
5017 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
5018 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5019 final int reason;
5020 // Networks are never blocked for system components
5021 if (isSystem(uid)) {
5022 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005023 }
junyulai05986c62018-08-07 19:50:45 +08005024 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5025 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005026 }
junyulai05986c62018-08-07 19:50:45 +08005027 else if (!isNetworkMetered) {
5028 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005029 }
junyulai05986c62018-08-07 19:50:45 +08005030 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5031 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005032 }
junyulai05986c62018-08-07 19:50:45 +08005033 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5034 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005035 }
junyulai05986c62018-08-07 19:50:45 +08005036 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5037 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005038 }
junyulai05986c62018-08-07 19:50:45 +08005039 else if (isBackgroundRestricted) {
5040 reason = NTWK_BLOCKED_BG_RESTRICT;
5041 }
5042 else {
5043 reason = NTWK_ALLOWED_DEFAULT;
5044 }
5045
5046 final boolean blocked;
5047 switch(reason) {
5048 case NTWK_ALLOWED_DEFAULT:
5049 case NTWK_ALLOWED_NON_METERED:
5050 case NTWK_ALLOWED_TMP_WHITELIST:
5051 case NTWK_ALLOWED_WHITELIST:
5052 case NTWK_ALLOWED_SYSTEM:
5053 blocked = false;
5054 break;
5055 case NTWK_BLOCKED_POWER:
5056 case NTWK_BLOCKED_BLACKLIST:
5057 case NTWK_BLOCKED_BG_RESTRICT:
5058 blocked = true;
5059 break;
5060 default:
5061 throw new IllegalArgumentException();
5062 }
5063 if (logger != null) {
5064 logger.networkBlocked(uid, reason);
5065 }
5066
5067 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005068 }
5069
Felipe Lemed17fda42016-04-29 11:12:45 -07005070 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5071
5072 @Override
5073 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005074 synchronized (mUidRulesFirstLock) {
5075 boolean changed = removeUserStateUL(userId, false);
5076 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005077 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005078 synchronized (mNetworkPoliciesSecondLock) {
5079 writePolicyAL();
5080 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005081 }
5082 }
5083 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005084
5085 /**
5086 * @return true if the given uid is restricted from doing networking on metered networks.
5087 */
5088 @Override
5089 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5090 final int uidRules;
5091 final boolean isBackgroundRestricted;
5092 synchronized (mUidRulesFirstLock) {
5093 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5094 isBackgroundRestricted = mRestrictBackground;
5095 }
5096 return isBackgroundRestricted
5097 && !hasRule(uidRules, RULE_ALLOW_METERED)
5098 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5099 }
5100
5101 /**
5102 * @return true if networking is blocked on the given interface for the given uid according
5103 * to current networking policies.
5104 */
5105 @Override
5106 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005107 final long startTime = mStatLogger.getTime();
5108
junyulai05986c62018-08-07 19:50:45 +08005109 final int uidRules;
5110 final boolean isBackgroundRestricted;
5111 synchronized (mUidRulesFirstLock) {
5112 uidRules = mUidRules.get(uid, RULE_NONE);
5113 isBackgroundRestricted = mRestrictBackground;
5114 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005115 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005116 synchronized (mNetworkPoliciesSecondLock) {
5117 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005118 }
junyulai05986c62018-08-07 19:50:45 +08005119 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5120 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005121
5122 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5123
5124 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005125 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005126
5127 @Override
5128 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5129 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005130 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005131 if (added) {
5132 mPowerSaveTempWhitelistAppIds.put(appId, true);
5133 } else {
5134 mPowerSaveTempWhitelistAppIds.delete(appId);
5135 }
5136 updateRulesForTempWhitelistChangeUL(appId);
5137 }
5138 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005139
5140 @Override
5141 public SubscriptionPlan getSubscriptionPlan(Network network) {
5142 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005143 final int subId = getSubIdLocked(network);
5144 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005145 }
5146 }
5147
5148 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005149 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5150 synchronized (mNetworkPoliciesSecondLock) {
5151 final int subId = findRelevantSubIdNL(template);
5152 return getPrimarySubscriptionPlanLocked(subId);
5153 }
5154 }
5155
5156 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005157 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005158 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005159 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005160 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005161 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005162 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005163 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5164 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5165 }
5166
5167 if (quotaType == QUOTA_TYPE_JOBS) {
5168 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5169 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5170 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5171 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5172 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5173 } else {
5174 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5175 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005176 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005177
5178 @Override
5179 public void onAdminDataAvailable() {
5180 mAdminDataAvailableLatch.countDown();
5181 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005182
5183 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005184 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5185 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5186 }
5187
5188 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005189 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5190 setMeteredRestrictedPackagesInternal(packageNames, userId);
5191 }
5192
5193 @Override
5194 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5195 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5196 userId, 0, packageNames).sendToTarget();
5197 }
5198 }
5199
5200 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5201 synchronized (mUidRulesFirstLock) {
5202 final Set<Integer> newRestrictedUids = new ArraySet<>();
5203 for (String packageName : packageNames) {
5204 final int uid = getUidForPackage(packageName, userId);
5205 if (uid >= 0) {
5206 newRestrictedUids.add(uid);
5207 }
5208 }
5209 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5210 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5211 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5212 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5213 }
5214 }
5215
5216 private int getUidForPackage(String packageName, int userId) {
5217 try {
5218 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5219 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5220 } catch (NameNotFoundException e) {
5221 return -1;
5222 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005223 }
5224
5225 private int parseSubId(NetworkState state) {
5226 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5227 int subId = INVALID_SUBSCRIPTION_ID;
5228 if (state != null && state.networkCapabilities != null
5229 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5230 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5231 if (spec instanceof StringNetworkSpecifier) {
5232 try {
5233 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5234 } catch (NumberFormatException e) {
5235 }
5236 }
5237 }
5238 return subId;
5239 }
5240
Andreas Gampea36dc622018-02-05 17:19:22 -08005241 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005242 private int getSubIdLocked(Network network) {
5243 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005244 }
5245
Andreas Gampea36dc622018-02-05 17:19:22 -08005246 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005247 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5248 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005249 if (!ArrayUtils.isEmpty(plans)) {
5250 for (SubscriptionPlan plan : plans) {
5251 if (plan.getCycleRule().isRecurring()) {
5252 // Recurring plans will always have an active cycle
5253 return plan;
5254 } else {
5255 // Non-recurring plans need manual test for active cycle
5256 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5257 if (cycle.contains(ZonedDateTime.now(mClock))) {
5258 return plan;
5259 }
5260 }
5261 }
5262 }
5263 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005264 }
5265
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005266 /**
5267 * This will only ever be called once - during device boot.
5268 */
5269 private void waitForAdminData() {
5270 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5271 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5272 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5273 }
5274 }
5275
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005276 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5277 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005278 if (!mNetworkManagerReady) {
5279 return;
5280 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005281 if (oldRestrictedUids == null) {
5282 for (int uid : newRestrictedUids) {
5283 updateRulesForDataUsageRestrictionsUL(uid);
5284 }
5285 return;
5286 }
5287 for (int uid : oldRestrictedUids) {
5288 if (!newRestrictedUids.contains(uid)) {
5289 updateRulesForDataUsageRestrictionsUL(uid);
5290 }
5291 }
5292 for (int uid : newRestrictedUids) {
5293 if (!oldRestrictedUids.contains(uid)) {
5294 updateRulesForDataUsageRestrictionsUL(uid);
5295 }
5296 }
5297 }
5298
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005299 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005300 private boolean isRestrictedByAdminUL(int uid) {
5301 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5302 UserHandle.getUserId(uid));
5303 return restrictedUids != null && restrictedUids.contains(uid);
5304 }
5305
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005306 private static boolean hasRule(int uidRules, int rule) {
5307 return (uidRules & rule) != 0;
5308 }
5309
Jeff Sharkey2e471452018-01-19 18:02:47 +09005310 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5311 return (val != null) ? val : new NetworkState[0];
5312 }
5313
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005314 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5315 String key, boolean defaultValue) {
5316 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5317 }
5318
Chris Wren193ae6b2017-03-31 15:17:11 -04005319 private class NotificationId {
5320 private final String mTag;
5321 private final int mId;
5322
5323 NotificationId(NetworkPolicy policy, int type) {
5324 mTag = buildNotificationTag(policy, type);
5325 mId = type;
5326 }
5327
5328 @Override
5329 public boolean equals(Object o) {
5330 if (this == o) return true;
5331 if (!(o instanceof NotificationId)) return false;
5332 NotificationId that = (NotificationId) o;
5333 return Objects.equals(mTag, that.mTag);
5334 }
5335
5336 @Override
5337 public int hashCode() {
5338 return Objects.hash(mTag);
5339 }
5340
5341 /**
5342 * Build unique tag that identifies an active {@link NetworkPolicy}
5343 * notification of a specific type, like {@link #TYPE_LIMIT}.
5344 */
5345 private String buildNotificationTag(NetworkPolicy policy, int type) {
5346 return TAG + ":" + policy.template.hashCode() + ":" + type;
5347 }
5348
5349 public String getTag() {
5350 return mTag;
5351 }
5352
5353 public int getId() {
5354 return mId;
5355 }
5356 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005357}