blob: 32d4b726f0116c37bb45ac37fbc709472c62310f [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;
Christopher Tateb909c4d52019-10-21 12:50:37 -0700232import com.android.server.usage.AppStandbyInternal;
233import com.android.server.usage.AppStandbyInternal.AppIdleStateChangeListener;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600234
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600235import libcore.io.IoUtils;
236
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238import org.xmlpull.v1.XmlSerializer;
239
240import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700241import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242import java.io.FileInputStream;
243import java.io.FileNotFoundException;
244import java.io.FileOutputStream;
245import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700246import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700247import java.lang.annotation.Retention;
248import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100249import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700250import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900251import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600252import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700253import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600254import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900255import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700256import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600257import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700258import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600259import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400260import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800261import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800262import java.util.concurrent.CountDownLatch;
263import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700265/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 * Service that maintains low-level network policy rules, using
267 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700268 * <p>
269 * Derives active rules by combining a given policy with other system status,
270 * and delivers to listeners, such as {@link ConnectivityManager}, for
271 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700272 *
273 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700274 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700275 * <ul>
276 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
277 * rules).
278 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
279 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700280 * </ul>
281 *
282 * <p>
283 * As such, methods that require synchronization have the following prefixes:
284 * <ul>
285 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
286 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000287 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
288 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700289 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700290 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700292 static final String TAG = NetworkPolicyLogger.TAG;
293 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
294 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700295
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900296 /**
297 * No opportunistic quota could be calculated from user data plan or data settings.
298 */
299 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
300
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 private static final int VERSION_INIT = 1;
302 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700303 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800304 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800305 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800306 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700307 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700308 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700309 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700310 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600311 private static final int VERSION_ADDED_CYCLE = 11;
312 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400315 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400317 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400319 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900320 @VisibleForTesting
321 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700322
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 private static final String TAG_POLICY_LIST = "policy-list";
324 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600325 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700326 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700327 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800328 private static final String TAG_WHITELIST = "whitelist";
329 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800330 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331
332 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700333 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
335 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700336 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600337 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
338 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
339 private static final String ATTR_CYCLE_START = "cycleStart";
340 private static final String ATTR_CYCLE_END = "cycleEnd";
341 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private static final String ATTR_WARNING_BYTES = "warningBytes";
343 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700344 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800345 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
346 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800347 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700348 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700349 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700350 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700351 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600352 private static final String ATTR_SUB_ID = "subId";
353 private static final String ATTR_TITLE = "title";
354 private static final String ATTR_SUMMARY = "summary";
355 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
356 private static final String ATTR_USAGE_BYTES = "usageBytes";
357 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600358 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800360 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800361 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800362 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800363 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700364 private static final String ACTION_SNOOZE_RAPID =
365 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700366
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800367 /**
Sudheer Shankab2ed1c32019-10-07 11:42:59 -0700368 * Indicates the maximum wait time for admin data to be available.
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800369 */
370 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
371
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600372 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
373 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
374 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
375 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
376
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700377 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700378 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800379 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800380 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700381 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700382 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
383 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700384 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700385 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900386 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800387 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700388 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Sarah Chin7af1fd02019-09-26 11:37:13 -0700389 private static final int MSG_SUBSCRIPTION_PLANS_CHANGED = 19;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700390
Makoto Onuki8e777332017-03-28 11:25:47 -0700391 private static final int UID_MSG_STATE_CHANGED = 100;
392 private static final int UID_MSG_GONE = 101;
393
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600394 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
395
Jeff Sharkey75279902011-05-24 18:39:45 -0700396 private final Context mContext;
397 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700398 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700399 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700400 private UsageStatsManagerInternal mUsageStats;
Christopher Tateb909c4d52019-10-21 12:50:37 -0700401 private AppStandbyInternal mAppStandby;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700402 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700403 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700404 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700405
406 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700407 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700408 private IDeviceIdleController mDeviceIdleController;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700409
410 /** Current cached value of the current Battery Saver mode's setting for restrict background. */
jackqdyulei29c82ab2017-03-10 14:09:16 -0800411 @GuardedBy("mUidRulesFirstLock")
Kweku Adams25fa3a72019-07-12 17:00:17 -0700412 private boolean mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800413
414 // Store the status of restrict background before turning on battery saver.
415 // Used to restore mRestrictBackground when battery saver is turned off.
416 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700417
Sudheer Shanka543339f2017-07-28 15:18:07 -0700418 // Denotes the status of restrict background read from disk.
419 private boolean mLoadedRestrictBackground;
420
Felipe Lemef0823852016-06-08 13:43:08 -0700421 // See main javadoc for instructions on how to use these locks.
422 final Object mUidRulesFirstLock = new Object();
423 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700424
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700425 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
426 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700427
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
429 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
430 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800431 // Store whether user flipped restrict background in battery saver mode
432 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700433
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700434 private final boolean mSuppressDefaultPolicy;
435
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800436 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
437
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700438 private volatile boolean mNetworkManagerReady;
439
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700440 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600441 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700443
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600445 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600446 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600447 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600448 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600449 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600450
Jeff Sharkey9252b342018-01-19 07:58:35 +0900451 /** Map from subId to daily opportunistic quota. */
452 @GuardedBy("mNetworkPoliciesSecondLock")
453 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
454
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700455 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700456 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700457 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700459
Felipe Lemef0823852016-06-08 13:43:08 -0700460 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700461 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700462 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700463 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800465 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700466
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700467 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700468 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700469 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
470
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800471 // "Power save mode" is the concept used in the DeviceIdleController that includes various
472 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
473 // and "battery saver" are not equivalent.
474
Jeff Sharkey32566012014-12-02 18:30:14 -0800475 /**
476 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700477 * in power save mode, except device idle (doze) still applies.
478 * TODO: An int array might be sufficient
479 */
Felipe Lemef0823852016-06-08 13:43:08 -0700480 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700481 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
482
483 /**
484 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800485 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700486 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800487 */
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700489 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700490
Felipe Lemef0823852016-06-08 13:43:08 -0700491 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700492 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
493
Felipe Lemeb85a6372016-01-14 16:16:16 -0800494 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800495 * UIDs that have been white-listed temporarily to be able to have network access despite being
496 * idle. Other power saving restrictions still apply.
497 */
498 @GuardedBy("mUidRulesFirstLock")
499 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
500
501 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800502 * UIDs that have been initially white-listed by system to avoid restricted background.
503 */
Felipe Lemef0823852016-06-08 13:43:08 -0700504 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800505 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
506 new SparseBooleanArray();
507
508 /**
509 * UIDs that have been initially white-listed by system to avoid restricted background,
510 * but later revoked by user.
511 */
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800513 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
514 new SparseBooleanArray();
515
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700516 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700517 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800518 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700519 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700520 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800521 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700522
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700523 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700524 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400525 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700526
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700527 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700528 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800529 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700530
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600531 /** Map from network ID to last observed meteredness state */
532 @GuardedBy("mNetworkPoliciesSecondLock")
533 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900534 /** Map from network ID to last observed roaming state */
535 @GuardedBy("mNetworkPoliciesSecondLock")
536 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
537
Jeff Sharkey9252b342018-01-19 07:58:35 +0900538 /** Map from netId to subId as of last update */
539 @GuardedBy("mNetworkPoliciesSecondLock")
540 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
541
Jeff Sharkey146bb332018-04-18 15:42:57 -0600542 /** Map from subId to subscriberId as of last update */
543 @GuardedBy("mNetworkPoliciesSecondLock")
544 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
545 /** Set of all merged subscriberId as of last update */
546 @GuardedBy("mNetworkPoliciesSecondLock")
Malcolm Chen07fcb5b2019-07-02 22:29:35 -0700547 private List<String[]> mMergedSubscriberIds = new ArrayList<>();
Jeff Sharkey146bb332018-04-18 15:42:57 -0600548
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800549 /**
550 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
551 * userId to restricted uids which belong to that user.
552 */
553 @GuardedBy("mUidRulesFirstLock")
554 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
555
Jeff Sharkey32566012014-12-02 18:30:14 -0800556 private final RemoteCallbackList<INetworkPolicyListener>
557 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700558
Dianne Hackborn497175b2014-07-01 12:56:08 -0700559 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700560 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800561 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700562
563 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700564
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700565 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700566 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700567
Svet Ganov16a16892015-04-16 10:32:04 -0700568 private final AppOpsManager mAppOps;
569
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800570 private final IPackageManager mIPm;
571
Sudheer Shankae7361852017-03-07 11:51:46 -0800572 private ActivityManagerInternal mActivityManagerInternal;
573
Sudheer Shanka352dc572017-09-22 17:09:38 -0700574 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800575
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700576 // TODO: keep whitelist of system-critical services that should never have
577 // rules enforced, such as system, phone, and radio UIDs.
578
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700579 // TODO: migrate notifications to SystemUI
580
Makoto Onuki49392d32018-04-11 13:51:02 -0700581
582 interface Stats {
583 int UPDATE_NETWORK_ENABLED = 0;
584 int IS_UID_NETWORKING_BLOCKED = 1;
585
586 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
587 }
588
589 public final StatLogger mStatLogger = new StatLogger(new String[] {
590 "updateNetworkEnabledNL()",
591 "isUidNetworkingBlocked()",
592 });
593
Jeff Sharkey75279902011-05-24 18:39:45 -0700594 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700595 INetworkManagementService networkManagement) {
596 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
597 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598 }
599
Jeff Sharkey9911a282018-02-14 22:29:11 -0700600 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700601 return new File(Environment.getDataDirectory(), "system");
602 }
603
Jeff Sharkey9911a282018-02-14 22:29:11 -0700604 private static @NonNull Clock getDefaultClock() {
605 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
606 Clock.systemUTC());
607 }
608
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700609 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700610 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
611 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700612 mContext = checkNotNull(context, "missing context");
613 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700614 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700615 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700616 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700617 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700618 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700619 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700620 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700621
Amith Yamasani450a16b2013-09-18 16:28:50 -0700622 HandlerThread thread = new HandlerThread(TAG);
623 thread.start();
624 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700625
Makoto Onuki8e777332017-03-28 11:25:47 -0700626 // We create another thread for the UID events, which are more time-critical.
627 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
628 /*allowIo=*/ false);
629 mUidEventThread.start();
630 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
631
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700632 mSuppressDefaultPolicy = suppressDefaultPolicy;
633
Dianne Hackborne17b4452018-01-10 13:15:40 -0800634 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700635
636 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800637
Felipe Lemed17fda42016-04-29 11:12:45 -0700638 // Expose private service for system components to use.
639 LocalServices.addService(NetworkPolicyManagerInternal.class,
640 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700641 }
642
643 public void bindConnectivityManager(IConnectivityManager connManager) {
644 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700645 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700646
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700647 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700648 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700649 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700650 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
651 mPowerSaveWhitelistExceptIdleAppIds.clear();
652 if (whitelist != null) {
653 for (int uid : whitelist) {
654 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
655 }
656 }
657 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700658 mPowerSaveWhitelistAppIds.clear();
659 if (whitelist != null) {
660 for (int uid : whitelist) {
661 mPowerSaveWhitelistAppIds.put(uid, true);
662 }
663 }
664 } catch (RemoteException e) {
665 }
666 }
667
Felipe Lemea9505cc2016-02-26 10:28:41 -0800668 /**
669 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
670 * revoke the whitelist.
671 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700672 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800673 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700674 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700675 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800676 final List<UserInfo> users = mUserManager.getUsers();
677 final int numberUsers = users.size();
678
Felipe Lemea110eec2016-04-29 09:58:06 -0700679 boolean changed = false;
680 for (int i = 0; i < numberUsers; i++) {
681 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700682 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700683 }
684 return changed;
685 }
686
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700687 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700688 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700689 final SystemConfig sysConfig = SystemConfig.getInstance();
690 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800691 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
692 boolean changed = false;
693 for (int i = 0; i < allowDataUsage.size(); i++) {
694 final String pkg = allowDataUsage.valueAt(i);
695 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700696 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
697 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800698 final ApplicationInfo app;
699 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700700 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800701 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700702 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
703 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 continue;
705 }
706 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700707 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
708 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800709 continue;
710 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700711 final int uid = UserHandle.getUid(userId, app.uid);
712 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
713 if (LOGD)
714 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
715 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800716 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700717 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700718 if (LOGD)
719 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
720 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700721 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700722 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800723 }
724 }
725 return changed;
726 }
727
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800728 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700729 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800730 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800732 // Boost thread's priority during system server init
733 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 if (!isBandwidthControlEnabled()) {
735 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
736 return;
737 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700738
Felipe Leme873a83a2016-09-07 11:34:10 -0700739 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Christopher Tateb909c4d52019-10-21 12:50:37 -0700740 mAppStandby = LocalServices.getService(AppStandbyInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700741 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700742
Felipe Leme873a83a2016-09-07 11:34:10 -0700743 synchronized (mUidRulesFirstLock) {
744 synchronized (mNetworkPoliciesSecondLock) {
745 updatePowerSaveWhitelistUL();
746 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
747 mPowerManagerInternal.registerLowPowerModeObserver(
748 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800749 @Override
750 public int getServiceType() {
751 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700752 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800753
754 @Override
755 public void onLowPowerModeChanged(PowerSaveState result) {
756 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800757 if (LOGD) {
758 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
759 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800760 synchronized (mUidRulesFirstLock) {
761 if (mRestrictPower != enabled) {
762 mRestrictPower = enabled;
763 updateRulesForRestrictPowerUL();
764 }
765 }
766 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800767 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800768 mRestrictPower = mPowerManagerInternal.getLowPowerState(
769 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700770
771 mSystemReady = true;
772
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800773 waitForAdminData();
774
Felipe Leme873a83a2016-09-07 11:34:10 -0700775 // read policy from disk
776 readPolicyAL();
777
jackqdyulei29c82ab2017-03-10 14:09:16 -0800778 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700779 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700780 mRestrictBackgroundLowPowerMode = mPowerManagerInternal
781 .getLowPowerState(ServiceType.DATA_SAVER).batterySaverEnabled;
782 if (mRestrictBackgroundLowPowerMode && !mLoadedRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -0700783 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800784 }
785 mPowerManagerInternal.registerLowPowerModeObserver(
786 new PowerManagerInternal.LowPowerModeListener() {
787 @Override
788 public int getServiceType() {
789 return ServiceType.DATA_SAVER;
790 }
791
792 @Override
793 public void onLowPowerModeChanged(PowerSaveState result) {
794 synchronized (mUidRulesFirstLock) {
795 updateRestrictBackgroundByLowPowerModeUL(result);
796 }
797 }
798 });
799
Felipe Leme873a83a2016-09-07 11:34:10 -0700800 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
801 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700802 }
Felipe Lemef0823852016-06-08 13:43:08 -0700803
Kweku Adamsdf33ae12019-10-08 11:51:41 -0700804 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, true);
Sudheer Shanka543339f2017-07-28 15:18:07 -0700805 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700806 updateRulesForGlobalChangeAL(false);
807 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700808 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800809 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700810
Sudheer Shankae7361852017-03-07 11:51:46 -0800811 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 try {
813 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000814 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700815 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700816 mNetworkManager.registerObserver(mAlertObserver);
817 } catch (RemoteException e) {
818 // ignored; both services live in system_server
819 }
820
821 // listen for changes to power save whitelist
822 final IntentFilter whitelistFilter = new IntentFilter(
823 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
824 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
825
Felipe Leme873a83a2016-09-07 11:34:10 -0700826 // watch for network interfaces to be claimed
827 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
828 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
829
830 // listen for package changes to update policy
831 final IntentFilter packageFilter = new IntentFilter();
832 packageFilter.addAction(ACTION_PACKAGE_ADDED);
833 packageFilter.addDataScheme("package");
834 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
835
836 // listen for UID changes to update policy
837 mContext.registerReceiver(
838 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
839
840 // listen for user changes to update policy
841 final IntentFilter userFilter = new IntentFilter();
842 userFilter.addAction(ACTION_USER_ADDED);
843 userFilter.addAction(ACTION_USER_REMOVED);
844 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
845
846 // listen for stats update events
847 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
848 mContext.registerReceiver(
849 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
850
851 // listen for restrict background changes from notifications
852 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
853 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
854
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700855 // Listen for snooze from notifications
856 mContext.registerReceiver(mSnoozeReceiver,
857 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
858 mContext.registerReceiver(mSnoozeReceiver,
859 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700860
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600861 // listen for configured wifi networks to be loaded
862 final IntentFilter wifiFilter =
863 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
864 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700865
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700866 // listen for carrier config changes to update data cycle information
867 final IntentFilter carrierConfigFilter = new IntentFilter(
868 ACTION_CARRIER_CONFIG_CHANGED);
869 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
870
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600871 // listen for meteredness changes
872 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
873 new NetworkRequest.Builder().build(), mNetworkCallback);
874
Christopher Tateb909c4d52019-10-21 12:50:37 -0700875 mAppStandby.addListener(new NetPolicyAppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600876
877 // Listen for subscriber changes
878 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
879 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
880 @Override
881 public void onSubscriptionsChanged() {
882 updateNetworksInternal();
883 }
884 });
885
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800886 // tell systemReady() that the service has been initialized
887 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700888 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800889 // Restore the default priority after init is done
890 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700891 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700892 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700893 }
894
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800895 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700896 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800897 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
898 mHandler.post(() -> initService(initCompleteSignal));
899 return initCompleteSignal;
900 }
901
902 public void systemReady(CountDownLatch initCompleteSignal) {
903 // wait for initService to complete
904 try {
905 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
906 throw new IllegalStateException("Service " + TAG +" init timeout");
907 }
908 } catch (InterruptedException e) {
909 Thread.currentThread().interrupt();
910 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
911 }
912 }
913
Sudheer Shankac9d94072017-02-22 22:13:55 +0000914 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Hui Yu26969322019-08-21 14:56:35 -0700915 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq,
916 int capability) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700917 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
918 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700919 }
920
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700921 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700922 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700923 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700924
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700925 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700926 }
927
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700928 @Override public void onUidIdle(int uid, boolean disabled) {
929 }
930
931 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700932 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700933 };
934
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700935 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700936 @Override
937 public void onReceive(Context context, Intent intent) {
938 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700939 synchronized (mUidRulesFirstLock) {
940 updatePowerSaveWhitelistUL();
941 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700942 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700943 }
944 }
945 };
946
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700947 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700948 @Override
949 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700950 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700951
952 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700953 final int uid = intent.getIntExtra(EXTRA_UID, -1);
954 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700955
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700956 if (ACTION_PACKAGE_ADDED.equals(action)) {
957 // update rules for UID, since it might be subject to
958 // global background data policy
959 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700960 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700961 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700962 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700963 }
964 }
965 };
966
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700967 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700968 @Override
969 public void onReceive(Context context, Intent intent) {
970 // on background handler thread, and UID_REMOVED is protected
971
972 final int uid = intent.getIntExtra(EXTRA_UID, -1);
973 if (uid == -1) return;
974
975 // remove any policy and update rules to clean up
976 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700977 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700978 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700979 synchronized (mNetworkPoliciesSecondLock) {
980 writePolicyAL();
981 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700982 }
983 }
984 };
985
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700986 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700987 @Override
988 public void onReceive(Context context, Intent intent) {
989 // on background handler thread, and USER_ADDED and USER_REMOVED
990 // broadcasts are protected
991
992 final String action = intent.getAction();
993 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
994 if (userId == -1) return;
995
Amith Yamasani15e472352015-04-24 19:06:07 -0700996 switch (action) {
997 case ACTION_USER_REMOVED:
998 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700999 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001000 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -07001001 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -07001002 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001003 // Removing outside removeUserStateUL since that can also be called when
1004 // user resets app preferences.
1005 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001006 if (action == ACTION_USER_ADDED) {
1007 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001008 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001009 }
1010 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001011 synchronized (mNetworkPoliciesSecondLock) {
1012 updateRulesForGlobalChangeAL(true);
1013 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001014 }
1015 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001016 }
1017 }
1018 };
1019
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001020 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001021 * Receiver that watches for {@link INetworkStatsService} updates, which we
1022 * use to check against {@link NetworkPolicy#warningBytes}.
1023 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001024 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025 @Override
1026 public void onReceive(Context context, Intent intent) {
1027 // on background handler thread, and verified
1028 // READ_NETWORK_USAGE_HISTORY permission above.
1029
Felipe Lemef0823852016-06-08 13:43:08 -07001030 synchronized (mNetworkPoliciesSecondLock) {
1031 updateNetworkEnabledNL();
1032 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001033 }
1034 }
1035 };
1036
1037 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001038 * Receiver that watches for {@link Notification} control of
1039 * {@link #mRestrictBackground}.
1040 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001041 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001042 @Override
1043 public void onReceive(Context context, Intent intent) {
1044 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1045 // permission above.
1046
1047 setRestrictBackground(false);
1048 }
1049 };
1050
1051 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001052 * Receiver that watches for {@link Notification} control of
1053 * {@link NetworkPolicy#lastWarningSnooze}.
1054 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001055 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001056 @Override
1057 public void onReceive(Context context, Intent intent) {
1058 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1059 // permission above.
1060
1061 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001062 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1063 performSnooze(template, TYPE_WARNING);
1064 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1065 performSnooze(template, TYPE_RAPID);
1066 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001067 }
1068 };
1069
1070 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001071 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001072 * we can perform upgrade logic. After initial upgrade logic, it updates
1073 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001074 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001075 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001076 @Override
1077 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001078 synchronized (mUidRulesFirstLock) {
1079 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001080 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001081 }
1082 }
1083 // Only need to perform upgrade logic once
1084 mContext.unregisterReceiver(this);
1085 }
1086 };
1087
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001088 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1089 Network network) {
1090 final boolean lastValue = lastValues.get(network.netId, false);
1091 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1092 if (changed) {
1093 lastValues.put(network.netId, newValue);
1094 }
1095 return changed;
1096 }
1097
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001098 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1099 @Override
1100 public void onCapabilitiesChanged(Network network,
1101 NetworkCapabilities networkCapabilities) {
1102 if (network == null || networkCapabilities == null) return;
1103
1104 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001105 final boolean newMetered = !networkCapabilities
1106 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001107 final boolean meteredChanged = updateCapabilityChange(
1108 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001109
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001110 final boolean newRoaming = !networkCapabilities
1111 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1112 final boolean roamingChanged = updateCapabilityChange(
1113 mNetworkRoaming, newRoaming, network);
1114
1115 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001116 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001117 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001118 }
1119 }
1120 }
1121 };
1122
1123 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001124 * Observer that watches for {@link INetworkManagementService} alerts.
1125 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001126 final private INetworkManagementEventObserver mAlertObserver
1127 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 @Override
1129 public void limitReached(String limitName, String iface) {
1130 // only someone like NMS should be calling us
1131 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1132
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001133 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1134 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001135 }
1136 }
1137 };
1138
1139 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001140 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1141 * to show visible notifications as needed.
1142 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001143 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001144 void updateNotificationsNL() {
1145 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001146 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001147
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001148 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001149 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001151
1152 // TODO: when switching to kernel notifications, compute next future
1153 // cycle boundary to recompute notifications.
1154
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001155 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001156 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001157 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1158 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001159 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001160
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001161 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001162 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001163 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001164
Jeff Sharkey53313d72017-07-13 16:47:32 -06001165 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1166 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001167 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1168 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1169 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001170
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001171 // Carrier might want to manage notifications themselves
1172 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001173 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1174 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1175 // Don't show notifications until we confirm that the loaded config is from an
1176 // identified carrier, which may want to manage their own notifications. This method
1177 // should be called every time the carrier config changes anyways, and there's no
1178 // reason to alert if there isn't a carrier.
1179 return;
1180 }
1181
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001182 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1183 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1184 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1185 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1186 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1187 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1188
1189 // Notify when data usage is over warning
1190 if (notifyWarning) {
1191 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1192 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1193 if (!snoozedThisCycle) {
1194 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1195 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001196 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001197 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001198
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001199 // Notify when data usage is over limit
1200 if (notifyLimit) {
1201 if (policy.isOverLimit(totalBytes)) {
1202 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1203 if (snoozedThisCycle) {
1204 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1205 } else {
1206 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1207 notifyOverLimitNL(policy.template);
1208 }
1209 } else {
1210 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001211 }
1212 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001213
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001214 // Warn if average usage over last 4 days is on track to blow pretty
1215 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001216 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001217 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001218 final long recentStart = now - recentDuration;
1219 final long recentEnd = now;
1220 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001221
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001222 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001223 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001224 final long alertBytes = (policy.limitBytes * 3) / 2;
1225
1226 if (LOGD) {
1227 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1228 + projectedBytes + " alert " + alertBytes);
1229 }
1230
1231 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1232 - DateUtils.DAY_IN_MILLIS;
1233 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001234 enqueueNotification(policy, TYPE_RAPID, 0,
1235 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001236 }
1237 }
1238 }
1239
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001241 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001242 final NotificationId notificationId = beforeNotifs.valueAt(i);
1243 if (!mActiveNotifs.contains(notificationId)) {
1244 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001245 }
1246 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001247
1248 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001249 }
1250
1251 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001252 * Attempt to find a specific app to blame for rapid data usage during the
1253 * given time period.
1254 */
1255 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1256 long start, long end) {
1257 long totalBytes = 0;
1258 long maxBytes = 0;
1259 int maxUid = 0;
1260
1261 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1262 NetworkStats.Entry entry = null;
1263 for (int i = 0; i < stats.size(); i++) {
1264 entry = stats.getValues(i, entry);
1265 final long bytes = entry.rxBytes + entry.txBytes;
1266 totalBytes += bytes;
1267 if (bytes > maxBytes) {
1268 maxBytes = bytes;
1269 maxUid = entry.uid;
1270 }
1271 }
1272
1273 // Only point blame if the majority of usage was done by a single app.
1274 // TODO: support shared UIDs
1275 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1276 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001277 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001278 try {
1279 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1280 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1281 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1282 } catch (NameNotFoundException ignored) {
1283 }
1284 }
1285 }
1286
1287 return null;
1288 }
1289
1290 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001291 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001292 * current device state, such as when
1293 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1294 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001295 *
1296 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1297 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001298 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001299 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001300 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001301 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001302 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1303 final int subId = mSubIdToSubscriberId.keyAt(i);
1304 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001305 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1306 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1307 true);
1308 if (template.matches(probeIdent)) {
1309 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001310 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001311 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001312 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001313 }
1314
1315 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001316 * Notify that given {@link NetworkTemplate} is over
1317 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1318 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001319 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001320 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001321 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001322 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001323 mOverLimitNotified.add(template);
1324 }
1325 }
1326
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001327 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001328 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001329 mOverLimitNotified.remove(template);
1330 }
1331
1332 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001333 * Show notification for combined {@link NetworkPolicy} and specific type,
1334 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1335 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001336 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1337 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001338 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001339 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001340 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001341 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001342 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001343 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001344 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001345
1346 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001347 final CharSequence title;
1348 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001349 switch (type) {
1350 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001351 title = res.getText(R.string.data_usage_warning_title);
1352 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001353 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001354
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001355 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001356
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001357 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1358 builder.setDeleteIntent(PendingIntent.getBroadcast(
1359 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1360
Wei Liu546cb772016-07-21 16:19:01 -07001361 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001362 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001363 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001364 builder.setContentIntent(PendingIntent.getActivityAsUser(
1365 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1366 /* options= */ null, UserHandle.CURRENT));
1367 } else {
1368 builder.setContentIntent(PendingIntent.getActivity(
1369 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1370 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001371 break;
1372 }
1373 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001374 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001375 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001376 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001377 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001378 case MATCH_WIFI:
1379 title = res.getText(R.string.data_usage_wifi_limit_title);
1380 break;
1381 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001382 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001383 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001384 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001385
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001386 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001387 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001388
Wei Liu546cb772016-07-21 16:19:01 -07001389 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001390 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001391 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001392 builder.setContentIntent(PendingIntent.getActivityAsUser(
1393 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1394 /* options= */ null, UserHandle.CURRENT));
1395 } else {
1396 builder.setContentIntent(PendingIntent.getActivity(
1397 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1398 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 break;
1400 }
1401 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001402 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001403 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001404 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1405 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001406 case MATCH_WIFI:
1407 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1408 break;
1409 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001410 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001411 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001412 final long overBytes = totalBytes - policy.limitBytes;
1413 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001414 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001415
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001416 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001417 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001418 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001419
Wei Liu546cb772016-07-21 16:19:01 -07001420 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001421 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001422 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001423 builder.setContentIntent(PendingIntent.getActivityAsUser(
1424 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1425 /* options= */ null, UserHandle.CURRENT));
1426 } else {
1427 builder.setContentIntent(PendingIntent.getActivity(
1428 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1429 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001430 break;
1431 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001432 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001433 title = res.getText(R.string.data_usage_rapid_title);
1434 if (rapidBlame != null) {
1435 body = res.getString(R.string.data_usage_rapid_app_body,
1436 rapidBlame.loadLabel(mContext.getPackageManager()));
1437 } else {
1438 body = res.getString(R.string.data_usage_rapid_body);
1439 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001440
Jeff Sharkey2e471452018-01-19 18:02:47 +09001441 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001442
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001443 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1444 builder.setDeleteIntent(PendingIntent.getBroadcast(
1445 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1446
1447 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001448 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001449 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001450 builder.setContentIntent(PendingIntent.getActivityAsUser(
1451 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1452 /* options= */ null, UserHandle.CURRENT));
1453 } else {
1454 builder.setContentIntent(PendingIntent.getActivity(
1455 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1456 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001457 break;
1458 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001459 default: {
1460 return;
1461 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001462 }
1463
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001464 builder.setTicker(title);
1465 builder.setContentTitle(title);
1466 builder.setContentText(body);
1467 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001468
1469 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1470 notificationId.getId(), builder.build(), UserHandle.ALL);
1471 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001472 }
1473
Chris Wren193ae6b2017-03-31 15:17:11 -04001474 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001475 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1476 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001477 }
1478
1479 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001481 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001483 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484 @Override
1485 public void onReceive(Context context, Intent intent) {
1486 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1487 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001488 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001489 }
1490 };
1491
Jeff Sharkey146bb332018-04-18 15:42:57 -06001492 private void updateNetworksInternal() {
1493 // Get all of our cross-process communication with telephony out of
1494 // the way before we acquire internal locks.
1495 updateSubscriptions();
1496
1497 synchronized (mUidRulesFirstLock) {
1498 synchronized (mNetworkPoliciesSecondLock) {
1499 ensureActiveMobilePolicyAL();
1500 normalizePoliciesNL();
1501 updateNetworkEnabledNL();
1502 updateNetworkRulesNL();
1503 updateNotificationsNL();
1504 }
1505 }
1506 }
1507
Jeff Sharkey2e471452018-01-19 18:02:47 +09001508 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001509 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001510 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001511 final CountDownLatch latch = new CountDownLatch(1);
1512 mHandler.post(() -> {
1513 latch.countDown();
1514 });
1515 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001516 }
1517
Sudheer Shankac0f85c12019-10-12 15:01:44 -07001518 @VisibleForTesting
1519 Handler getHandlerForTesting() {
1520 return mHandler;
1521 }
1522
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001523 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001524 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1525 * if necessary.
1526 *
1527 * @param subId that has its associated NetworkPolicy updated if necessary
1528 * @return if any policies were updated
1529 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001530 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001531 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001532 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001533
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001534 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001535 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001536 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001537 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001538 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1539 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1540 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001541 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1542 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001543 }
1544 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001545 return policyUpdated;
1546 }
1547
1548 /**
1549 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1550 *
1551 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1552 * to do so, it returns the fallback value.
1553 *
1554 * @param config The CarrierConfig to read the value from.
1555 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1556 * @return cycleDay to use in the mobile NetworkPolicy.
1557 */
1558 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001559 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001560 int fallbackCycleDay) {
1561 if (config == null) {
1562 return fallbackCycleDay;
1563 }
1564 int cycleDay =
1565 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1566 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1567 return fallbackCycleDay;
1568 }
1569 // validate cycleDay value
1570 final Calendar cal = Calendar.getInstance();
1571 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1572 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1573 Slog.e(TAG, "Invalid date in "
1574 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1575 return fallbackCycleDay;
1576 }
1577 return cycleDay;
1578 }
1579
1580 /**
1581 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1582 *
1583 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1584 * to do so, it returns the fallback value.
1585 *
1586 * @param config The CarrierConfig to read the value from.
1587 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1588 * @return warningBytes to use in the mobile NetworkPolicy.
1589 */
1590 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001591 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001592 long fallbackWarningBytes) {
1593 if (config == null) {
1594 return fallbackWarningBytes;
1595 }
1596 long warningBytes =
1597 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1598
1599 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1600 return WARNING_DISABLED;
1601 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1602 return getPlatformDefaultWarningBytes();
1603 } else if (warningBytes < 0) {
1604 Slog.e(TAG, "Invalid value in "
1605 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1606 + "non-negative value but got: " + warningBytes);
1607 return fallbackWarningBytes;
1608 }
1609
1610 return warningBytes;
1611 }
1612
1613 /**
1614 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1615 *
1616 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1617 * to do so, it returns the fallback value.
1618 *
1619 * @param config The CarrierConfig to read the value from.
1620 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1621 * @return limitBytes to use in the mobile NetworkPolicy.
1622 */
1623 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001624 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001625 long fallbackLimitBytes) {
1626 if (config == null) {
1627 return fallbackLimitBytes;
1628 }
1629 long limitBytes =
1630 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1631
1632 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1633 return LIMIT_DISABLED;
1634 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1635 return getPlatformDefaultLimitBytes();
1636 } else if (limitBytes < 0) {
1637 Slog.e(TAG, "Invalid value in "
1638 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1639 + "non-negative value but got: " + limitBytes);
1640 return fallbackLimitBytes;
1641 }
1642 return limitBytes;
1643 }
1644
1645 /**
1646 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1647 */
1648 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1649 @Override
1650 public void onReceive(Context context, Intent intent) {
1651 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1652 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1653
1654 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1655 return;
1656 }
1657 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001658
1659 // Get all of our cross-process communication with telephony out of
1660 // the way before we acquire internal locks.
1661 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001662
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001663 synchronized (mUidRulesFirstLock) {
1664 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001665 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1666 if (subscriberId != null) {
1667 ensureActiveMobilePolicyAL(subId, subscriberId);
1668 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1669 } else {
1670 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1671 }
1672
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001673 // update network and notification rules, as the data cycle changed and it's
1674 // possible that we should be triggering warnings/limits now
1675 handleNetworkPoliciesUpdateAL(true);
1676 }
1677 }
1678 }
1679 };
1680
1681 /**
1682 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1683 * one has been updated.
1684 *
1685 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1686 * update.
1687 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001688 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001689 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1690 if (shouldNormalizePolicies) {
1691 normalizePoliciesNL();
1692 }
1693 updateNetworkEnabledNL();
1694 updateNetworkRulesNL();
1695 updateNotificationsNL();
1696 writePolicyAL();
1697 }
1698
1699 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001700 * Proactively control network data connections when they exceed
1701 * {@link NetworkPolicy#limitBytes}.
1702 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001703 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001704 void updateNetworkEnabledNL() {
1705 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001706 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001707
1708 // TODO: reset any policy-disabled networks when any policy is removed
1709 // completely, which is currently rare case.
1710
Makoto Onuki49392d32018-04-11 13:51:02 -07001711 final long startTime = mStatLogger.getTime();
1712
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001713 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1714 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001715 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001716 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001717 setNetworkTemplateEnabled(policy.template, true);
1718 continue;
1719 }
1720
Jeff Sharkey53313d72017-07-13 16:47:32 -06001721 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1722 .cycleIterator(policy).next();
1723 final long start = cycle.first.toInstant().toEpochMilli();
1724 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001725 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001726
1727 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001728 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1729 && policy.lastLimitSnooze < start;
1730 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001731
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001732 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001733 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001734
1735 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001736 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001737 }
1738
1739 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001740 * Proactively disable networks that match the given
1741 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001742 */
1743 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001744 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1745 // held. Call it via the handler.
1746 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1747 .sendToTarget();
1748 }
1749
1750 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001751 // TODO: reach into ConnectivityManager to proactively disable bringing
1752 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001753
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001754 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001755 // If mobile data usage hits the limit or if the user resumes the data, we need to
1756 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001757
Jeff Sharkey146bb332018-04-18 15:42:57 -06001758 final IntArray matchingSubIds = new IntArray();
1759 synchronized (mNetworkPoliciesSecondLock) {
1760 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1761 final int subId = mSubIdToSubscriberId.keyAt(i);
1762 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1763
1764 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1765 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1766 true);
1767 // Template is matched when subscriber id matches.
1768 if (template.matches(probeIdent)) {
1769 matchingSubIds.add(subId);
1770 }
Jack Yu8781b682016-07-08 14:28:51 -07001771 }
1772 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001773
1774 // Only talk with telephony outside of locks
1775 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1776 for (int i = 0; i < matchingSubIds.size(); i++) {
1777 final int subId = matchingSubIds.get(i);
1778 tm.setPolicyDataEnabled(enabled, subId);
1779 }
Jack Yu8781b682016-07-08 14:28:51 -07001780 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001781 }
1782
1783 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001784 * Collect all ifaces from a {@link NetworkState} into the given set.
1785 */
1786 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1787 final String baseIface = state.linkProperties.getInterfaceName();
1788 if (baseIface != null) {
1789 ifaces.add(baseIface);
1790 }
1791 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1792 final String stackedIface = stackedLink.getInterfaceName();
1793 if (stackedIface != null) {
1794 ifaces.add(stackedIface);
1795 }
1796 }
1797 }
1798
1799 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001800 * Examine all currently active subscriptions from
1801 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1802 * internal data structures.
1803 * <p>
1804 * Callers <em>must not</em> hold any locks when this method called.
1805 */
1806 void updateSubscriptions() {
1807 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1808 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1809
1810 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1811 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1812
1813 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001814 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001815
1816 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1817 for (int subId : subIds) {
1818 final String subscriberId = tm.getSubscriberId(subId);
1819 if (!TextUtils.isEmpty(subscriberId)) {
1820 subIdToSubscriberId.put(subId, subscriberId);
1821 } else {
1822 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1823 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001824
1825 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1826 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1827 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001828 }
1829
1830 synchronized (mNetworkPoliciesSecondLock) {
1831 mSubIdToSubscriberId.clear();
1832 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1833 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1834 subIdToSubscriberId.valueAt(i));
1835 }
1836
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001837 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001838 }
1839
1840 Trace.traceEnd(TRACE_TAG_NETWORK);
1841 }
1842
1843 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 * Examine all connected {@link NetworkState}, looking for
1845 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1846 * remaining quota based on usage cycle and historical stats.
1847 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001848 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001849 void updateNetworkRulesNL() {
1850 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001851 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001852
1853 final NetworkState[] states;
1854 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001855 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001856 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001857 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001858 return;
1859 }
1860
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001861 // First, generate identities of all connected networks so we can
1862 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001863 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001864 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001865 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001866 if (state.network != null) {
1867 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1868 }
Wei Liub8eaf452016-01-25 10:32:27 -08001869 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001870 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1871 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001872 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001873 }
1874 }
1875
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001876 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001877 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001878
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001879 // For every well-defined policy, compute remaining data based on
1880 // current cycle and historical stats, and push to kernel.
1881 final ArraySet<String> matchingIfaces = new ArraySet<>();
1882 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1883 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1884
1885 // Collect all ifaces that match this policy
1886 matchingIfaces.clear();
1887 for (int j = identified.size() - 1; j >= 0; j--) {
1888 if (policy.template.matches(identified.valueAt(j))) {
1889 collectIfaces(matchingIfaces, identified.keyAt(j));
1890 }
1891 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001892
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001893 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001894 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001895 }
1896
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001897 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001898 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001899 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001900 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001901 if (hasLimit && policy.hasCycle()) {
1902 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1903 .cycleIterator(policy).next();
1904 final long start = cycle.first.toInstant().toEpochMilli();
1905 final long end = cycle.second.toInstant().toEpochMilli();
1906 final long totalBytes = getTotalBytes(policy.template, start, end);
1907
1908 if (policy.lastLimitSnooze >= start) {
1909 // snoozing past quota, but we still need to restrict apps,
1910 // so push really high quota.
1911 quotaBytes = Long.MAX_VALUE;
1912 } else {
1913 // remaining "quota" bytes are based on total usage in
1914 // current cycle. kernel doesn't like 0-byte rules, so we
1915 // set 1-byte quota and disable the radio later.
1916 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1917 }
1918 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001919 // metered network, but no policy limit; we still need to
1920 // restrict apps, so push really high quota.
1921 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001922 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001923
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001924 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001925 // TODO: switch to shared quota once NMS supports
1926 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001927 }
1928
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001929 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1930 final String iface = matchingIfaces.valueAt(j);
1931 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001932 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001933 }
1934 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001935
1936 // keep track of lowest warning or limit of active policies
1937 if (hasWarning && policy.warningBytes < lowestRule) {
1938 lowestRule = policy.warningBytes;
1939 }
1940 if (hasLimit && policy.limitBytes < lowestRule) {
1941 lowestRule = policy.limitBytes;
1942 }
1943 }
1944
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001945 // One final pass to catch any metered ifaces that don't have explicitly
1946 // defined policies; typically Wi-Fi networks.
1947 for (NetworkState state : states) {
1948 if (state.networkInfo != null && state.networkInfo.isConnected()
1949 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1950 matchingIfaces.clear();
1951 collectIfaces(matchingIfaces, state);
1952 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1953 final String iface = matchingIfaces.valueAt(j);
1954 if (!newMeteredIfaces.contains(iface)) {
1955 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1956 newMeteredIfaces.add(iface);
1957 }
1958 }
1959 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001960 }
1961
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001962 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001963 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1964 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001965 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001966 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001967 }
1968 }
1969 mMeteredIfaces = newMeteredIfaces;
1970
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001971 final ContentResolver cr = mContext.getContentResolver();
1972 final boolean quotaEnabled = Settings.Global.getInt(cr,
1973 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1974 final long quotaUnlimited = Settings.Global.getLong(cr,
1975 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1976 final float quotaLimited = Settings.Global.getFloat(cr,
1977 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1978
Jeff Sharkey9252b342018-01-19 07:58:35 +09001979 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001980 mSubscriptionOpportunisticQuota.clear();
1981 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001982 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001983 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001984 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001985 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001986 if (plan == null) continue;
1987
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001988 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001989 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001990 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1991 // Clamp to 0 when roaming
1992 quotaBytes = 0;
1993 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001994 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001995 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001996 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001997 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001998 } else {
1999 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06002000 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
2001 final long start = cycle.getLower().toInstant().toEpochMilli();
2002 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002003 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06002004 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002005 .truncatedTo(ChronoUnit.DAYS)
2006 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09002007 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002008 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
2009 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09002010 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002011 // Number of remaining days including current day
2012 final long remainingDays =
2013 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002014
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002015 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002016 }
2017
2018 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2019 }
2020
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002021 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002022 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002023
2024 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002025
2026 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002027 }
2028
2029 /**
2030 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2031 * have at least a default mobile policy defined.
2032 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002033 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002034 private void ensureActiveMobilePolicyAL() {
2035 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002036 if (mSuppressDefaultPolicy) return;
2037
Jeff Sharkey146bb332018-04-18 15:42:57 -06002038 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2039 final int subId = mSubIdToSubscriberId.keyAt(i);
2040 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002041
Hugo Benichi446c9c92017-04-10 09:41:10 +09002042 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002043 }
2044 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002045
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002046 /**
2047 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2048 * have at least a default mobile policy defined.
2049 *
2050 * @param subId to build a default policy for
2051 * @param subscriberId that we check for an existing policy
2052 * @return true if a mobile network policy was added, or false one already existed.
2053 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002054 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002055 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002056 // Poke around to see if we already have a policy
2057 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002058 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002059 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2060 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2061 if (template.matches(probeIdent)) {
2062 if (LOGD) {
2063 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2064 + NetworkIdentity.scrubSubscriberId(subscriberId));
2065 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002066 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002067 }
2068 }
2069
Jeff Sharkey32566012014-12-02 18:30:14 -08002070 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2071 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002072 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002073 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002074 return true;
2075 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002076
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002077 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002078 final int dataWarningConfig = mContext.getResources().getInteger(
2079 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002080 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002081 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002082 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002083 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002084 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002085 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002086
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002087 private long getPlatformDefaultLimitBytes() {
2088 return LIMIT_DISABLED;
2089 }
2090
2091 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002092 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002093 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002094 final RecurrenceRule cycleRule = NetworkPolicy
2095 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002096 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002097 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2098 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2099 synchronized (mUidRulesFirstLock) {
2100 synchronized (mNetworkPoliciesSecondLock) {
2101 updateDefaultMobilePolicyAL(subId, policy);
2102 }
2103 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002104 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002105 }
2106
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002107 /**
2108 * Update the given {@link NetworkPolicy} based on any carrier-provided
2109 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2110 * Leaves policy untouched if the user has modified it.
2111 *
2112 * @return if the policy was modified
2113 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002114 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002115 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2116 if (!policy.inferred) {
2117 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2118 return false;
2119 }
2120
2121 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2122 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2123 policy.lastLimitSnooze, policy.metered, policy.inferred);
2124
2125 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2126 if (!ArrayUtils.isEmpty(plans)) {
2127 final SubscriptionPlan plan = plans[0];
2128 policy.cycleRule = plan.getCycleRule();
2129 final long planLimitBytes = plan.getDataLimitBytes();
2130 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2131 policy.warningBytes = getPlatformDefaultWarningBytes();
2132 policy.limitBytes = getPlatformDefaultLimitBytes();
2133 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2134 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2135 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2136 } else {
2137 policy.warningBytes = (planLimitBytes * 9) / 10;
2138 switch (plan.getDataLimitBehavior()) {
2139 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2140 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2141 policy.limitBytes = planLimitBytes;
2142 break;
2143 default:
2144 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2145 break;
2146 }
2147 }
2148 } else {
2149 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2150 final int currentCycleDay;
2151 if (policy.cycleRule.isMonthly()) {
2152 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2153 } else {
2154 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2155 }
2156 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2157 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2158 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2159 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2160 }
2161
2162 if (policy.equals(original)) {
2163 return false;
2164 } else {
2165 Slog.d(TAG, "Updated " + original + " to " + policy);
2166 return true;
2167 }
2168 }
2169
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002170 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002171 private void readPolicyAL() {
2172 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173
2174 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002175 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002176 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002177 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002178 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179
2180 FileInputStream fis = null;
2181 try {
2182 fis = mPolicyFile.openRead();
2183 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002184 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002185
Felipe Leme46b451f2016-08-19 08:46:17 -07002186 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2187 // to skip UIDs that were explicitly blacklisted.
2188 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2189
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002190 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002191 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002192 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002193 while ((type = in.next()) != END_DOCUMENT) {
2194 final String tag = in.getName();
2195 if (type == START_TAG) {
2196 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002197 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002198 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002199 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2200 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002201 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2202 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2203 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002204 final String networkId;
2205 if (version >= VERSION_ADDED_NETWORK_ID) {
2206 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2207 } else {
2208 networkId = null;
2209 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002210 final RecurrenceRule cycleRule;
2211 if (version >= VERSION_ADDED_CYCLE) {
2212 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2213 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2214 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2215 cycleRule = new RecurrenceRule(
2216 RecurrenceRule.convertZonedDateTime(start),
2217 RecurrenceRule.convertZonedDateTime(end),
2218 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002219 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002220 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2221 final String cycleTimezone;
2222 if (version >= VERSION_ADDED_TIMEZONE) {
2223 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2224 } else {
2225 cycleTimezone = "UTC";
2226 }
2227 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002228 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002229 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2230 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002231 final long lastLimitSnooze;
2232 if (version >= VERSION_SPLIT_SNOOZE) {
2233 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2234 } else if (version >= VERSION_ADDED_SNOOZE) {
2235 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002236 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002237 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002238 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002239 final boolean metered;
2240 if (version >= VERSION_ADDED_METERED) {
2241 metered = readBooleanAttribute(in, ATTR_METERED);
2242 } else {
2243 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002244 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002245 metered = true;
2246 break;
2247 default:
2248 metered = false;
2249 }
2250 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002251 final long lastWarningSnooze;
2252 if (version >= VERSION_SPLIT_SNOOZE) {
2253 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2254 } else {
2255 lastWarningSnooze = SNOOZE_NEVER;
2256 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002257 final boolean inferred;
2258 if (version >= VERSION_ADDED_INFERRED) {
2259 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2260 } else {
2261 inferred = false;
2262 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002263
Jeff Sharkey32566012014-12-02 18:30:14 -08002264 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2265 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002266 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002267 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2268 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002269 lastLimitSnooze, metered, inferred));
2270 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002271
2272 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2273 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2274 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2275 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2276 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2277 RecurrenceRule.convertZonedDateTime(start),
2278 RecurrenceRule.convertZonedDateTime(end),
2279 RecurrenceRule.convertPeriod(period));
2280 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2281 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2282
2283 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2284 SubscriptionPlan.BYTES_UNKNOWN);
2285 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2286 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2287 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2288 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2289 builder.setDataLimit(limitBytes, limitBehavior);
2290 }
2291
2292 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2293 SubscriptionPlan.BYTES_UNKNOWN);
2294 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2295 SubscriptionPlan.TIME_UNKNOWN);
2296 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2297 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2298 builder.setDataUsage(usageBytes, usageTime);
2299 }
2300
2301 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2302 final SubscriptionPlan plan = builder.build();
2303 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2304 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2305
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002306 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2307 mSubscriptionPlansOwner.put(subId, ownerPackage);
2308
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002309 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002310 final int uid = readIntAttribute(in, ATTR_UID);
2311 final int policy = readIntAttribute(in, ATTR_POLICY);
2312
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002313 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002314 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002315 } else {
2316 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2317 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002318 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002319 final int appId = readIntAttribute(in, ATTR_APP_ID);
2320 final int policy = readIntAttribute(in, ATTR_POLICY);
2321
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002322 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002323 // app policy is deprecated so this is only used in pre system user split.
2324 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002325 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002326 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002327 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002328 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002329 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002330 } else if (TAG_WHITELIST.equals(tag)) {
2331 insideWhitelist = true;
2332 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2333 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002334 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002335 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2336 final int uid = readIntAttribute(in, ATTR_UID);
2337 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002338 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002339 } else if (type == END_TAG) {
2340 if (TAG_WHITELIST.equals(tag)) {
2341 insideWhitelist = false;
2342 }
2343
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002344 }
2345 }
2346
Felipe Leme46b451f2016-08-19 08:46:17 -07002347 final int size = whitelistedRestrictBackground.size();
2348 for (int i = 0; i < size; i++) {
2349 final int uid = whitelistedRestrictBackground.keyAt(i);
2350 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2351 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2352 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2353 + " because its policy is " + uidPoliciesToString(policy));
2354 continue;
2355 }
2356 if (UserHandle.isApp(uid)) {
2357 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2358 if (LOGV)
2359 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2360 setUidPolicyUncheckedUL(uid, newPolicy, false);
2361 } else {
2362 Slog.w(TAG, "unable to update policy on UID " + uid);
2363 }
2364 }
2365
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002366 } catch (FileNotFoundException e) {
2367 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002368 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002369 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002370 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002371 } finally {
2372 IoUtils.closeQuietly(fis);
2373 }
2374 }
2375
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002376 /**
2377 * Upgrade legacy background data flags, notifying listeners of one last
2378 * change to always-true.
2379 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002380 private void upgradeDefaultBackgroundDataUL() {
2381 // This method is only called when we're unable to find the network policy flag, which
2382 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002383
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002384 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002385 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002386 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2387
2388 // NOTE: We used to read the legacy setting here :
2389 //
2390 // final int legacyFlagValue = Settings.Secure.getInt(
2391 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2392 //
2393 // This is no longer necessary because we will never upgrade directly from Gingerbread
2394 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2395 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002396 }
2397
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002398 /**
2399 * Perform upgrade step of moving any user-defined meterness overrides over
2400 * into {@link WifiConfiguration}.
2401 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002402 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002403 private void upgradeWifiMeteredOverrideAL() {
2404 boolean modified = false;
2405 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2406 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2407 for (int i = 0; i < mNetworkPolicy.size(); ) {
2408 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2409 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2410 && !policy.inferred) {
2411 mNetworkPolicy.removeAt(i);
2412 modified = true;
2413
2414 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2415 for (WifiConfiguration config : configs) {
2416 if (Objects.equals(resolveNetworkId(config), networkId)) {
2417 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2418 config.meteredOverride = policy.metered
2419 ? WifiConfiguration.METERED_OVERRIDE_METERED
2420 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2421 wm.updateNetwork(config);
2422 }
2423 }
2424 } else {
2425 i++;
2426 }
2427 }
2428 if (modified) {
2429 writePolicyAL();
2430 }
2431 }
2432
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002433 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002434 void writePolicyAL() {
2435 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002436
2437 FileOutputStream fos = null;
2438 try {
2439 fos = mPolicyFile.startWrite();
2440
2441 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002442 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002443 out.startDocument(null, true);
2444
2445 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002446 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002447 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002448
2449 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002450 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2451 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002452 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002453 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002454
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002455 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002456 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2457 final String subscriberId = template.getSubscriberId();
2458 if (subscriberId != null) {
2459 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002460 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002461 final String networkId = template.getNetworkId();
2462 if (networkId != null) {
2463 out.attribute(null, ATTR_NETWORK_ID, networkId);
2464 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002465 writeStringAttribute(out, ATTR_CYCLE_START,
2466 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2467 writeStringAttribute(out, ATTR_CYCLE_END,
2468 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2469 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2470 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002471 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2472 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002473 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2474 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002475 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002476 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002477 out.endTag(null, TAG_NETWORK_POLICY);
2478 }
2479
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002480 // write all known subscription plans
2481 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2482 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002483 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002484 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2485 if (ArrayUtils.isEmpty(plans)) continue;
2486
2487 for (SubscriptionPlan plan : plans) {
2488 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2489 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002490 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002491 final RecurrenceRule cycleRule = plan.getCycleRule();
2492 writeStringAttribute(out, ATTR_CYCLE_START,
2493 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2494 writeStringAttribute(out, ATTR_CYCLE_END,
2495 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2496 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2497 RecurrenceRule.convertPeriod(cycleRule.period));
2498 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2499 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2500 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2501 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2502 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2503 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2504 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2505 }
2506 }
2507
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002508 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002509 for (int i = 0; i < mUidPolicy.size(); i++) {
2510 final int uid = mUidPolicy.keyAt(i);
2511 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002512
Jeff Sharkey497e4432011-06-14 17:27:29 -07002513 // skip writing empty policies
2514 if (policy == POLICY_NONE) continue;
2515
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002516 out.startTag(null, TAG_UID_POLICY);
2517 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002518 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002519 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002520 }
2521
2522 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002523
2524 // write all whitelists
2525 out.startTag(null, TAG_WHITELIST);
2526
Felipe Lemea9505cc2016-02-26 10:28:41 -08002527 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002528 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002529 for (int i = 0; i < size; i++) {
2530 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2531 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2532 writeIntAttribute(out, ATTR_UID, uid);
2533 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2534 }
2535
Felipe Lemeb85a6372016-01-14 16:16:16 -08002536 out.endTag(null, TAG_WHITELIST);
2537
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002538 out.endDocument();
2539
2540 mPolicyFile.finishWrite(fos);
2541 } catch (IOException e) {
2542 if (fos != null) {
2543 mPolicyFile.failWrite(fos);
2544 }
2545 }
2546 }
2547
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002548 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002549 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002550 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002551
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002552 if (!UserHandle.isApp(uid)) {
2553 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002554 }
Felipe Lemef0823852016-06-08 13:43:08 -07002555 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002556 final long token = Binder.clearCallingIdentity();
2557 try {
2558 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2559 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002560 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002561 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002565 }
2566 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002567 }
2568
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002569 @Override
2570 public void addUidPolicy(int uid, int policy) {
2571 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002572
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002573 if (!UserHandle.isApp(uid)) {
2574 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2575 }
2576
Felipe Lemef0823852016-06-08 13:43:08 -07002577 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002578 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2579 policy |= oldPolicy;
2580 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002581 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002582 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002583 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002584 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002585 }
2586
2587 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002588 public void removeUidPolicy(int uid, int policy) {
2589 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2590
2591 if (!UserHandle.isApp(uid)) {
2592 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2593 }
2594
Felipe Lemef0823852016-06-08 13:43:08 -07002595 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002596 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2597 policy = oldPolicy & ~policy;
2598 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002599 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002600 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002601 }
2602 }
2603 }
2604
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002605 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002606 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002607 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002608
Felipe Leme57e3d312016-08-23 14:42:52 -07002609 final boolean notifyApp;
2610 if (!isUidValidForWhitelistRules(uid)) {
2611 notifyApp = false;
2612 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002613 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2614 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2615 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2616 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002617 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2618 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002619 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2620 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2621 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2622 if (LOGD)
2623 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2624 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2625 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002626 notifyApp = wasBlocked != isBlocked;
2627 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002628 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2629 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002630 if (persist) {
2631 synchronized (mNetworkPoliciesSecondLock) {
2632 writePolicyAL();
2633 }
2634 }
Felipe Leme923845f2016-03-02 13:42:48 -08002635 }
2636
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002637 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002638 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002639 if (policy == POLICY_NONE) {
2640 mUidPolicy.delete(uid);
2641 } else {
2642 mUidPolicy.put(uid, policy);
2643 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002644
2645 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002646 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002647 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002648 synchronized (mNetworkPoliciesSecondLock) {
2649 writePolicyAL();
2650 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002651 }
2652 }
2653
2654 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002655 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002656 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2657
Felipe Lemef0823852016-06-08 13:43:08 -07002658 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002659 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002660 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002661 }
2662
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002663 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002664 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002665 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2666
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002667 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002668 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002669 for (int i = 0; i < mUidPolicy.size(); i++) {
2670 final int uid = mUidPolicy.keyAt(i);
2671 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002672 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2673 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002674 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002675 }
2676 }
2677 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002678 return uids;
2679 }
2680
2681 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002682 * Removes any persistable state associated with given {@link UserHandle}, persisting
2683 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002684 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002685 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002686 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002687
Sudheer Shanka352dc572017-09-22 17:09:38 -07002688 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002689 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002690
Felipe Lemea110eec2016-04-29 09:58:06 -07002691 // Remove entries from revoked default restricted background UID whitelist
2692 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2693 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2694 if (UserHandle.getUserId(uid) == userId) {
2695 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002696 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002697 }
2698 }
2699
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002700 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002701 int[] uids = new int[0];
2702 for (int i = 0; i < mUidPolicy.size(); i++) {
2703 final int uid = mUidPolicy.keyAt(i);
2704 if (UserHandle.getUserId(uid) == userId) {
2705 uids = appendInt(uids, uid);
2706 }
2707 }
2708
2709 if (uids.length > 0) {
2710 for (int uid : uids) {
2711 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002712 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002713 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002714 }
Felipe Lemef0823852016-06-08 13:43:08 -07002715 synchronized (mNetworkPoliciesSecondLock) {
2716 updateRulesForGlobalChangeAL(true);
2717 if (writePolicy && changed) {
2718 writePolicyAL();
2719 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002720 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002721 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002722 }
2723
2724 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002725 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002726 // TODO: create permission for observing network policy
2727 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002728 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002729 }
2730
2731 @Override
2732 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002733 // TODO: create permission for observing network policy
2734 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002735 mListeners.unregister(listener);
2736 }
2737
Jeff Sharkey1b861272011-05-22 00:34:52 -07002738 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002739 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002740 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2741
Felipe Leme6a05eee2016-02-19 14:43:51 -08002742 final long token = Binder.clearCallingIdentity();
2743 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002744 synchronized (mUidRulesFirstLock) {
2745 synchronized (mNetworkPoliciesSecondLock) {
2746 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002747 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002748 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002752 }
2753 }
2754
Hugo Benichi446c9c92017-04-10 09:41:10 +09002755 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002756 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002757 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2758 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002759 }
2760
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002761 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002762 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002763 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002764 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002765 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2766 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2767 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002768 } catch (SecurityException e) {
2769 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002770
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002771 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2772 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2773 return new NetworkPolicy[0];
2774 }
Svet Ganov16a16892015-04-16 10:32:04 -07002775 }
2776
Felipe Lemef0823852016-06-08 13:43:08 -07002777 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002778 final int size = mNetworkPolicy.size();
2779 final NetworkPolicy[] policies = new NetworkPolicy[size];
2780 for (int i = 0; i < size; i++) {
2781 policies[i] = mNetworkPolicy.valueAt(i);
2782 }
2783 return policies;
2784 }
2785 }
2786
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002787 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002788 private void normalizePoliciesNL() {
2789 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002790 }
2791
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002792 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002793 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002794 mNetworkPolicy.clear();
2795 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002796 if (policy == null) {
2797 continue;
2798 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002799 // When two normalized templates conflict, prefer the most
2800 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002801 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002802 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2803 if (existing == null || existing.compareTo(policy) > 0) {
2804 if (existing != null) {
2805 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2806 }
2807 mNetworkPolicy.put(policy.template, policy);
2808 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002809 }
2810 }
2811
2812 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002813 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002814 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002815
2816 final long token = Binder.clearCallingIdentity();
2817 try {
2818 performSnooze(template, TYPE_LIMIT);
2819 } finally {
2820 Binder.restoreCallingIdentity(token);
2821 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002822 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002823
Dianne Hackborn497175b2014-07-01 12:56:08 -07002824 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002825 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002826 synchronized (mUidRulesFirstLock) {
2827 synchronized (mNetworkPoliciesSecondLock) {
2828 // find and snooze local policy that matches
2829 final NetworkPolicy policy = mNetworkPolicy.get(template);
2830 if (policy == null) {
2831 throw new IllegalArgumentException("unable to find policy for " + template);
2832 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002833
Felipe Lemef0823852016-06-08 13:43:08 -07002834 switch (type) {
2835 case TYPE_WARNING:
2836 policy.lastWarningSnooze = currentTime;
2837 break;
2838 case TYPE_LIMIT:
2839 policy.lastLimitSnooze = currentTime;
2840 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002841 case TYPE_RAPID:
2842 policy.lastRapidSnooze = currentTime;
2843 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002844 default:
2845 throw new IllegalArgumentException("unexpected type");
2846 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002847
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002848 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002849 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002850 }
2851 }
2852
2853 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002854 public void onTetheringChanged(String iface, boolean tethering) {
2855 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002856 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002857 if (mRestrictBackground && tethering) {
2858 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2859 setRestrictBackground(false);
2860 }
2861 }
2862 }
2863
2864 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002865 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002866 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002867 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002868 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2869 final long token = Binder.clearCallingIdentity();
2870 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002871 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002872 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002873 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002874 } finally {
2875 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002876 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002877 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002878 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002879 }
2880 }
2881
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002882 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002883 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002884 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002885 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002886 if (restrictBackground == mRestrictBackground) {
2887 // Ideally, UI should never allow this scenario...
2888 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002889 return;
2890 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002891 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2892 final boolean oldRestrictBackground = mRestrictBackground;
2893 mRestrictBackground = restrictBackground;
2894 // Must whitelist foreground apps before turning data saver mode on.
2895 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2896 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2897 updateRulesForRestrictBackgroundUL();
2898 try {
2899 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2900 Slog.e(TAG,
2901 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2902 mRestrictBackground = oldRestrictBackground;
2903 // TODO: if it knew the foreground apps (see TODO above), it could call
2904 // updateRulesForRestrictBackgroundUL() again to restore state.
2905 return;
2906 }
2907 } catch (RemoteException e) {
2908 // ignored; service lives in system_server
2909 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002910
Sudheer Shanka543339f2017-07-28 15:18:07 -07002911 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002912 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002913
Kweku Adams25fa3a72019-07-12 17:00:17 -07002914 if (mRestrictBackgroundLowPowerMode) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002915 mRestrictBackgroundChangedInBsm = true;
2916 }
2917 synchronized (mNetworkPoliciesSecondLock) {
2918 updateNotificationsNL();
2919 writePolicyAL();
2920 }
2921 } finally {
2922 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002923 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002924 }
2925
2926 private void sendRestrictBackgroundChangedMsg() {
2927 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2928 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2929 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002930 }
2931
Felipe Lemeb85a6372016-01-14 16:16:16 -08002932 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002933 public int getRestrictBackgroundByCaller() {
2934 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2935 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002936
Felipe Lemef0823852016-06-08 13:43:08 -07002937 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002938 // Must clear identity because getUidPolicy() is restricted to system.
2939 final long token = Binder.clearCallingIdentity();
2940 final int policy;
2941 try {
2942 policy = getUidPolicy(uid);
2943 } finally {
2944 Binder.restoreCallingIdentity(token);
2945 }
2946 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2947 // App is blacklisted.
2948 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2949 }
Felipe Leme1b103232016-01-22 09:44:57 -08002950 if (!mRestrictBackground) {
2951 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2952 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002953 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002954 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2955 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2956 }
2957 }
2958
2959 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002960 public boolean getRestrictBackground() {
2961 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2962
Felipe Lemef0823852016-06-08 13:43:08 -07002963 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002964 return mRestrictBackground;
2965 }
2966 }
2967
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002968 @Override
2969 public void setDeviceIdleMode(boolean enabled) {
2970 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002971 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2972 try {
2973 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002974 if (mDeviceIdleMode == enabled) {
2975 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002976 }
Felipe Lemeea014392016-09-06 13:59:54 -07002977 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002978 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002979 if (mSystemReady) {
2980 // Device idle change means we need to rebuild rules for all
2981 // known apps, so do a global refresh.
2982 updateRulesForRestrictPowerUL();
2983 }
2984 }
2985 if (enabled) {
2986 EventLogTags.writeDeviceIdleOnPhase("net");
2987 } else {
2988 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002989 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002990 } finally {
2991 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002992 }
2993 }
2994
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002995 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002996 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2997 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002998 final long token = Binder.clearCallingIdentity();
2999 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003000 final WifiManager wm = mContext.getSystemService(WifiManager.class);
3001 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
3002 for (WifiConfiguration config : configs) {
3003 if (Objects.equals(resolveNetworkId(config), networkId)) {
3004 config.meteredOverride = meteredOverride;
3005 wm.updateNetwork(config);
3006 }
3007 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003008 } finally {
3009 Binder.restoreCallingIdentity(token);
3010 }
3011 }
3012
Jeff Sharkey46645002011-07-27 21:11:21 -07003013 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003014 @Deprecated
3015 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3016 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3017 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3018 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003019 }
3020
Jeff Sharkey53313d72017-07-13 16:47:32 -06003021 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3022 // Verify they're not lying about package name
3023 mAppOps.checkPackage(callingUid, callingPackage);
3024
Jeff Sharkey53313d72017-07-13 16:47:32 -06003025 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003026 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003027 final long token = Binder.clearCallingIdentity();
3028 try {
3029 si = mContext.getSystemService(SubscriptionManager.class)
3030 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003031 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003032 } finally {
3033 Binder.restoreCallingIdentity(token);
3034 }
3035
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003036 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003037 if (si != null) {
3038 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3039 return;
3040 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003041 }
3042
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003043 // Second check: has the CarrierService delegated access?
3044 if (config != null) {
3045 final String overridePackage = config
3046 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3047 if (!TextUtils.isEmpty(overridePackage)
3048 && Objects.equals(overridePackage, callingPackage)) {
3049 return;
3050 }
3051 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003052
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003053 // Third check: is caller the fallback/default CarrierService?
3054 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3055 if (!TextUtils.isEmpty(defaultPackage)
3056 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003057 return;
3058 }
3059
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003060 // Fourth check: is caller a testing app?
3061 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3062 if (!TextUtils.isEmpty(testPackage)
3063 && Objects.equals(testPackage, callingPackage)) {
3064 return;
3065 }
3066
3067 // Fifth check: is caller a legacy testing app?
3068 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3069 if (!TextUtils.isEmpty(legacyTestPackage)
3070 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003071 return;
3072 }
3073
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003074 // Final check: does the caller hold a permission?
3075 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003076 }
3077
Sarah Chin7af1fd02019-09-26 11:37:13 -07003078 private void enforceSubscriptionPlanValidity(SubscriptionPlan[] plans) {
3079 // nothing to check if no plans
3080 if (plans.length == 0) {
3081 return;
3082 }
3083
3084 long applicableNetworkTypes = 0;
3085 boolean allNetworks = false;
3086 for (SubscriptionPlan plan : plans) {
3087 if (plan.getNetworkTypes() == null) {
3088 allNetworks = true;
3089 } else {
3090 if ((applicableNetworkTypes & plan.getNetworkTypesBitMask()) != 0) {
3091 throw new IllegalArgumentException(
3092 "Multiple subscription plans defined for a single network type.");
3093 } else {
3094 applicableNetworkTypes |= plan.getNetworkTypesBitMask();
3095 }
3096 }
3097 }
3098
3099 // ensure at least one plan applies for every network type
3100 if (!allNetworks) {
3101 throw new IllegalArgumentException(
3102 "No generic subscription plan that applies to all network types.");
3103 }
3104 }
3105
Jeff Sharkey53313d72017-07-13 16:47:32 -06003106 @Override
3107 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3108 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3109
Jeff Sharkey53313d72017-07-13 16:47:32 -06003110 final String fake = SystemProperties.get("fw.fake_plan");
3111 if (!TextUtils.isEmpty(fake)) {
3112 final List<SubscriptionPlan> plans = new ArrayList<>();
3113 if ("month_hard".equals(fake)) {
3114 plans.add(SubscriptionPlan.Builder
3115 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3116 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003117 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3118 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3119 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3120 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3121 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003122 plans.add(SubscriptionPlan.Builder
3123 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3124 .setTitle("G-Mobile Happy")
3125 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3126 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3127 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3128 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3129 .build());
3130 plans.add(SubscriptionPlan.Builder
3131 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3132 .setTitle("G-Mobile, Charged after limit")
3133 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3134 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3135 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3136 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3137 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003138 } else if ("month_soft".equals(fake)) {
3139 plans.add(SubscriptionPlan.Builder
3140 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3141 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3142 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3143 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003144 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3145 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3146 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3147 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3148 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003149 plans.add(SubscriptionPlan.Builder
3150 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3151 .setTitle("G-Mobile, Throttled after limit")
3152 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3153 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3154 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3155 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3156 .build());
3157 plans.add(SubscriptionPlan.Builder
3158 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3159 .setTitle("G-Mobile, No data connection after limit")
3160 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3161 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3162 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3163 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3164 .build());
3165
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003166 } else if ("month_over".equals(fake)) {
3167 plans.add(SubscriptionPlan.Builder
3168 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3169 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3170 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3171 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3172 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3173 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3174 .build());
3175 plans.add(SubscriptionPlan.Builder
3176 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3177 .setTitle("G-Mobile, Throttled after limit")
3178 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3179 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3180 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3181 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3182 .build());
3183 plans.add(SubscriptionPlan.Builder
3184 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3185 .setTitle("G-Mobile, No data connection after limit")
3186 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3187 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3188 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3189 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3190 .build());
3191
Jeff Sharkey53313d72017-07-13 16:47:32 -06003192 } else if ("month_none".equals(fake)) {
3193 plans.add(SubscriptionPlan.Builder
3194 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3195 .setTitle("G-Mobile")
3196 .build());
3197 } else if ("prepaid".equals(fake)) {
3198 plans.add(SubscriptionPlan.Builder
3199 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3200 ZonedDateTime.now().plusDays(10))
3201 .setTitle("G-Mobile")
3202 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3203 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3204 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3205 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3206 .build());
3207 } else if ("prepaid_crazy".equals(fake)) {
3208 plans.add(SubscriptionPlan.Builder
3209 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3210 ZonedDateTime.now().plusDays(10))
3211 .setTitle("G-Mobile Anytime")
3212 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3213 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3214 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3215 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3216 .build());
3217 plans.add(SubscriptionPlan.Builder
3218 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3219 ZonedDateTime.now().plusDays(20))
3220 .setTitle("G-Mobile Nickel Nights")
3221 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003222 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3223 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003224 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3225 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3226 .build());
3227 plans.add(SubscriptionPlan.Builder
3228 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3229 ZonedDateTime.now().plusDays(20))
3230 .setTitle("G-Mobile Bonus 3G")
3231 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003232 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003233 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3234 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3235 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3236 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003237 } else if ("unlimited".equals(fake)) {
3238 plans.add(SubscriptionPlan.Builder
3239 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3240 ZonedDateTime.now().plusDays(10))
3241 .setTitle("G-Mobile Awesome")
3242 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3243 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3244 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3245 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3246 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003247 }
3248 return plans.toArray(new SubscriptionPlan[plans.size()]);
3249 }
3250
Jeff Sharkey4635f102017-09-01 11:27:13 -06003251 synchronized (mNetworkPoliciesSecondLock) {
3252 // Only give out plan details to the package that defined them,
3253 // so that we don't risk leaking plans between apps. We always
3254 // let in core system components (like the Settings app).
3255 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3256 if (Objects.equals(ownerPackage, callingPackage)
3257 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3258 return mSubscriptionPlans.get(subId);
3259 } else {
3260 Log.w(TAG, "Not returning plans because caller " + callingPackage
3261 + " doesn't match owner " + ownerPackage);
3262 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003263 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003264 }
3265 }
3266
3267 @Override
3268 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3269 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003270 enforceSubscriptionPlanValidity(plans);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003271
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003272 for (SubscriptionPlan plan : plans) {
3273 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003274 }
3275
3276 final long token = Binder.clearCallingIdentity();
3277 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003278 synchronized (mUidRulesFirstLock) {
3279 synchronized (mNetworkPoliciesSecondLock) {
3280 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003281 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003282
Jeff Sharkey146bb332018-04-18 15:42:57 -06003283 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3284 if (subscriberId != null) {
3285 ensureActiveMobilePolicyAL(subId, subscriberId);
3286 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3287 } else {
3288 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3289 }
3290
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003291 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003292 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003293 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003294
3295 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3296 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3297 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3298 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003299 mHandler.sendMessage(
3300 mHandler.obtainMessage(MSG_SUBSCRIPTION_PLANS_CHANGED, subId, 0, plans));
Jeff Sharkey53313d72017-07-13 16:47:32 -06003301 } finally {
3302 Binder.restoreCallingIdentity(token);
3303 }
3304 }
3305
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003306 /**
3307 * Only visible for testing purposes. This doesn't give any access to
3308 * existing plans; it simply lets the debug package define new plans.
3309 */
3310 void setSubscriptionPlansOwner(int subId, String packageName) {
3311 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3312 }
3313
Jeff Sharkey53313d72017-07-13 16:47:32 -06003314 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003315 public String getSubscriptionPlansOwner(int subId) {
3316 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3317 throw new SecurityException();
3318 }
3319
3320 synchronized (mNetworkPoliciesSecondLock) {
3321 return mSubscriptionPlansOwner.get(subId);
3322 }
3323 }
3324
3325 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003326 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
Sarah Chin7af1fd02019-09-26 11:37:13 -07003327 long timeoutMillis, String callingPackage) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003328 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3329
3330 // We can only override when carrier told us about plans
3331 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003332 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3333 if (plan == null
3334 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003335 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003336 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003337 }
3338 }
3339
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003340 // Only allow overrides when feature is enabled. However, we always
3341 // allow disabling of overrides for safety reasons.
3342 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3343 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3344 if (overrideEnabled || overrideValue == 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003345 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3346 overrideMask, overrideValue, subId));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003347 if (timeoutMillis > 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003348 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3349 overrideMask, 0, subId), timeoutMillis);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003350 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003351 }
3352 }
3353
3354 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003355 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003356 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003357
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003358 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3359
Dianne Hackborn497175b2014-07-01 12:56:08 -07003360 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003361 for (String arg : args) {
3362 argSet.add(arg);
3363 }
3364
Felipe Lemef0823852016-06-08 13:43:08 -07003365 synchronized (mUidRulesFirstLock) {
3366 synchronized (mNetworkPoliciesSecondLock) {
3367 if (argSet.contains("--unsnooze")) {
3368 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3369 mNetworkPolicy.valueAt(i).clearSnooze();
3370 }
3371
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003372 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003373
3374 fout.println("Cleared snooze timestamps");
3375 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003376 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003377
Felipe Lemef0823852016-06-08 13:43:08 -07003378 fout.print("System ready: "); fout.println(mSystemReady);
3379 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3380 fout.print("Restrict power: "); fout.println(mRestrictPower);
3381 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003382 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3383
3384 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003385 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003386 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003387 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3388 fout.println(mNetworkPolicy.valueAt(i).toString());
3389 }
3390 fout.decreaseIndent();
3391
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003392 fout.println();
3393 fout.println("Subscription plans:");
3394 fout.increaseIndent();
3395 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3396 final int subId = mSubscriptionPlans.keyAt(i);
3397 fout.println("Subscriber ID " + subId + ":");
3398 fout.increaseIndent();
3399 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3400 if (!ArrayUtils.isEmpty(plans)) {
3401 for (SubscriptionPlan plan : plans) {
3402 fout.println(plan);
3403 }
3404 }
3405 fout.decreaseIndent();
3406 }
3407 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003408
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003409 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003410 fout.println("Active subscriptions:");
3411 fout.increaseIndent();
3412 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3413 final int subId = mSubIdToSubscriberId.keyAt(i);
3414 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3415
3416 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3417 }
3418 fout.decreaseIndent();
3419
3420 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003421 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3422 fout.println("Merged subscriptions: " + Arrays.toString(
3423 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3424 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003425
3426 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003427 fout.println("Policy for UIDs:");
3428 fout.increaseIndent();
3429 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003430 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003431 final int uid = mUidPolicy.keyAt(i);
3432 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003433 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003434 fout.print(uid);
3435 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003436 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003437 fout.println();
3438 }
3439 fout.decreaseIndent();
3440
3441 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3442 if (size > 0) {
3443 fout.println("Power save whitelist (except idle) app ids:");
3444 fout.increaseIndent();
3445 for (int i = 0; i < size; i++) {
3446 fout.print("UID=");
3447 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3448 fout.print(": ");
3449 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3450 fout.println();
3451 }
3452 fout.decreaseIndent();
3453 }
3454
3455 size = mPowerSaveWhitelistAppIds.size();
3456 if (size > 0) {
3457 fout.println("Power save whitelist app ids:");
3458 fout.increaseIndent();
3459 for (int i = 0; i < size; i++) {
3460 fout.print("UID=");
3461 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3462 fout.print(": ");
3463 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3464 fout.println();
3465 }
3466 fout.decreaseIndent();
3467 }
3468
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003469 size = mAppIdleTempWhitelistAppIds.size();
3470 if (size > 0) {
3471 fout.println("App idle whitelist app ids:");
3472 fout.increaseIndent();
3473 for (int i = 0; i < size; i++) {
3474 fout.print("UID=");
3475 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3476 fout.print(": ");
3477 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3478 fout.println();
3479 }
3480 fout.decreaseIndent();
3481 }
3482
Felipe Lemef0823852016-06-08 13:43:08 -07003483 size = mDefaultRestrictBackgroundWhitelistUids.size();
3484 if (size > 0) {
3485 fout.println("Default restrict background whitelist uids:");
3486 fout.increaseIndent();
3487 for (int i = 0; i < size; i++) {
3488 fout.print("UID=");
3489 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3490 fout.println();
3491 }
3492 fout.decreaseIndent();
3493 }
3494
3495 size = mRestrictBackgroundWhitelistRevokedUids.size();
3496 if (size > 0) {
3497 fout.println("Default restrict background whitelist uids revoked by users:");
3498 fout.increaseIndent();
3499 for (int i = 0; i < size; i++) {
3500 fout.print("UID=");
3501 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3502 fout.println();
3503 }
3504 fout.decreaseIndent();
3505 }
3506
3507 final SparseBooleanArray knownUids = new SparseBooleanArray();
3508 collectKeys(mUidState, knownUids);
3509 collectKeys(mUidRules, knownUids);
3510
3511 fout.println("Status for all known UIDs:");
3512 fout.increaseIndent();
3513 size = knownUids.size();
3514 for (int i = 0; i < size; i++) {
3515 final int uid = knownUids.keyAt(i);
3516 fout.print("UID=");
3517 fout.print(uid);
3518
3519 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3520 fout.print(" state=");
3521 fout.print(state);
3522 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3523 fout.print(" (fg)");
3524 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003525 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003526 ? " (fg svc)" : " (bg)");
3527 }
3528
3529 final int uidRules = mUidRules.get(uid, RULE_NONE);
3530 fout.print(" rules=");
3531 fout.print(uidRulesToString(uidRules));
3532 fout.println();
3533 }
3534 fout.decreaseIndent();
3535
3536 fout.println("Status for just UIDs with rules:");
3537 fout.increaseIndent();
3538 size = mUidRules.size();
3539 for (int i = 0; i < size; i++) {
3540 final int uid = mUidRules.keyAt(i);
3541 fout.print("UID=");
3542 fout.print(uid);
3543 final int uidRules = mUidRules.get(uid, RULE_NONE);
3544 fout.print(" rules=");
3545 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003546 fout.println();
3547 }
3548 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003549
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003550 fout.println("Admin restricted uids for metered data:");
3551 fout.increaseIndent();
3552 size = mMeteredRestrictedUids.size();
3553 for (int i = 0; i < size; ++i) {
3554 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3555 fout.println(mMeteredRestrictedUids.valueAt(i));
3556 }
3557 fout.decreaseIndent();
3558
Makoto Onuki49392d32018-04-11 13:51:02 -07003559 fout.println();
3560 mStatLogger.dump(fout);
3561
Sudheer Shanka352dc572017-09-22 17:09:38 -07003562 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003563 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003564 }
3565 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003566
3567 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003568 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003569 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003570 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003571 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003572 }
3573
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003574 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003575 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003576 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003577 return isUidStateForeground(
3578 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003579 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003580 }
3581
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003582 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003583 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003584 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003585 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003586 }
3587
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003588 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003589 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003590 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3591 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3592 }
3593
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003594 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003595 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003596 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003597 }
3598
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003599 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003600 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003601 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003602 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003603 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003604 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003605 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003606 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3607 try {
3608 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3609 if (oldUidState != uidState) {
3610 // state changed, push updated rules
3611 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003612 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3613 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3614 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003615 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003616 if (mDeviceIdleMode) {
3617 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003618 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003619 if (mRestrictPower) {
3620 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003621 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003622 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003623 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003624 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003625 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003626 } finally {
3627 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003628 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003629 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003630 }
3631
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003632 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003633 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003634 final int index = mUidState.indexOfKey(uid);
3635 if (index >= 0) {
3636 final int oldUidState = mUidState.valueAt(index);
3637 mUidState.removeAt(index);
3638 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003639 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003640 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003641 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003642 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003643 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003644 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003645 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003646 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003647 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003648 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003649 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003650 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003651 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003652 }
3653
Felipe Lemef28983d2016-03-25 12:18:23 -07003654 // adjust stats accounting based on foreground status
3655 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003656 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3657 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3658 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3659 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003660 try {
3661 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003662 } finally {
3663 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003664 }
3665 }
3666
Sudheer Shankac9d94072017-02-22 22:13:55 +00003667 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3668 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003669 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003670 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003671 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003672 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003673 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003674 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003675 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003676 }
3677
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003678 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003679 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003680 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3681 try {
3682 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3683 mUidFirewallPowerSaveRules);
3684 } finally {
3685 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3686 }
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 updateRuleForRestrictPowerUL(int uid) {
3691 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003692 }
3693
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003694 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003695 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003696 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3697 try {
3698 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3699 mUidFirewallDozableRules);
3700 } finally {
3701 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3702 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003703 }
3704
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003705 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003706 void updateRuleForDeviceIdleUL(int uid) {
3707 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003708 }
3709
Felipe Lemef28983d2016-03-25 12:18:23 -07003710 // NOTE: since both fw_dozable and fw_powersave uses the same map
3711 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003712 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003713 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003714 SparseIntArray rules) {
3715 if (enabled) {
3716 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003717 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003718 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003719 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003720 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003721 for (int ui = users.size() - 1; ui >= 0; ui--) {
3722 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003723 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3724 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3725 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3726 updateRulesForWhitelistedAppIds(uidRules,
3727 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003728 }
3729 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003730 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003731 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003732 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3733 }
3734 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003735 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003736 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003737 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003738 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003739 }
3740
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003741 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3742 final SparseBooleanArray whitelistedAppIds, int userId) {
3743 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3744 if (whitelistedAppIds.valueAt(i)) {
3745 final int appId = whitelistedAppIds.keyAt(i);
3746 final int uid = UserHandle.getUid(userId, appId);
3747 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3748 }
3749 }
3750 }
3751
3752 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003753 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3754 * mode, and app idle).
3755 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003756 * @param deviceIdleMode if true then we don't consider
3757 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3758 * whitelisted.
3759 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003760 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003761 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003762 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003763 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3764 || mPowerSaveWhitelistAppIds.get(appId);
3765 if (!deviceIdleMode) {
3766 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3767 }
3768 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003769 }
3770
Felipe Lemef28983d2016-03-25 12:18:23 -07003771 // NOTE: since both fw_dozable and fw_powersave uses the same map
3772 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003773 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003774 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003775 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003776 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003777 chain == FIREWALL_CHAIN_DOZABLE);
3778 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003779 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003780 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003781 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003782 }
3783 }
3784 }
3785
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003786 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003787 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003788 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3789 try {
3790 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3791 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003792
Felipe Leme873a83a2016-09-07 11:34:10 -07003793 // Fully update the app idle firewall chain.
3794 final List<UserInfo> users = mUserManager.getUsers();
3795 for (int ui = users.size() - 1; ui >= 0; ui--) {
3796 UserInfo user = users.get(ui);
3797 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3798 for (int uid : idleUids) {
3799 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3800 // quick check: if this uid doesn't have INTERNET permission, it
3801 // doesn't have network access anyway, so it is a waste to mess
3802 // with it here.
3803 if (hasInternetPermissions(uid)) {
3804 uidRules.put(uid, FIREWALL_RULE_DENY);
3805 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003806 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003807 }
3808 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003809
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003810 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003811 } finally {
3812 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3813 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003814 }
3815
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003816 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003817 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003818 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003819
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003820 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3821 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3822 }
3823 try {
3824 int appId = UserHandle.getAppId(uid);
3825 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3826 && !isUidForegroundOnRestrictPowerUL(uid)) {
3827 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003828 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003829 } else {
3830 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003831 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003832 }
3833 } finally {
3834 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003835 }
3836 }
3837
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003838 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003839 * Update rules that might be changed by {@link #mRestrictBackground},
3840 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003841 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003842 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003843 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003844 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3845 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3846 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3847 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003848 try {
Felipe Leme09700462016-09-08 09:33:48 -07003849 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003850 updateRulesForRestrictPowerUL();
3851 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003852
Felipe Leme873a83a2016-09-07 11:34:10 -07003853 // If the set of restricted networks may have changed, re-evaluate those.
3854 if (restrictedNetworksChanged) {
3855 normalizePoliciesNL();
3856 updateNetworkRulesNL();
3857 }
3858 } finally {
3859 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003860 }
3861 }
3862
Felipe Leme09700462016-09-08 09:33:48 -07003863 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003864 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003865 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003866 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3867 try {
3868 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003869 updateRulesForPowerSaveUL();
3870 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3871 } finally {
3872 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3873 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003874 }
3875
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003876 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003877 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003878 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3879 try {
3880 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3881 } finally {
3882 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3883 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003884 }
3885
3886 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3887 private static final int TYPE_RESTRICT_POWER = 2;
3888 @Retention(RetentionPolicy.SOURCE)
3889 @IntDef(flag = false, value = {
3890 TYPE_RESTRICT_BACKGROUND,
3891 TYPE_RESTRICT_POWER,
3892 })
3893 public @interface RestrictType {
3894 }
3895
3896 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003897 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003898 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003899 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3900 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3901 }
3902 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003903 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003904
3905 final PackageManager pm = mContext.getPackageManager();
3906 final List<UserInfo> users;
3907 final List<ApplicationInfo> apps;
3908
3909 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3910 try {
3911 users = mUserManager.getUsers();
3912 } finally {
3913 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3914 }
3915 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3916 try {
3917 apps = pm.getInstalledApplications(
3918 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3919 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3920 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3921 } finally {
3922 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3923 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003924
Felipe Leme873a83a2016-09-07 11:34:10 -07003925 final int usersSize = users.size();
3926 final int appsSize = apps.size();
3927 for (int i = 0; i < usersSize; i++) {
3928 final UserInfo user = users.get(i);
3929 for (int j = 0; j < appsSize; j++) {
3930 final ApplicationInfo app = apps.get(j);
3931 final int uid = UserHandle.getUid(user.id, app.uid);
3932 switch (type) {
3933 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003934 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003935 break;
3936 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003937 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003938 break;
3939 default:
3940 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3941 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003942 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003943 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003944 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003945 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003946 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003947 }
3948
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003949 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003950 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003951 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003952 final int numUsers = users.size();
3953 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003954 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003955 int uid = UserHandle.getUid(user.id, appId);
3956 // Update external firewall rules.
3957 updateRuleForAppIdleUL(uid);
3958 updateRuleForDeviceIdleUL(uid);
3959 updateRuleForRestrictPowerUL(uid);
3960 // Update internal rules.
3961 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003962 }
3963 }
3964
Felipe Leme70c57c22016-03-29 10:45:13 -07003965 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3966 // methods below could be merged into a isUidValidForRules() method.
3967 private boolean isUidValidForBlacklistRules(int uid) {
3968 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003969 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003970 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003971 return true;
3972 }
3973
3974 return false;
3975 }
3976
Felipe Leme70c57c22016-03-29 10:45:13 -07003977 private boolean isUidValidForWhitelistRules(int uid) {
3978 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3979 }
3980
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003981 /**
3982 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3983 * power saving restrictions may still apply.
3984 */
3985 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003986 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003987 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3988
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003989 synchronized (mUidRulesFirstLock) {
3990 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3991 // No change.
3992 return;
3993 }
3994
3995 final long token = Binder.clearCallingIdentity();
3996 try {
3997 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3998 if (shouldWhitelist) {
3999 mAppIdleTempWhitelistAppIds.put(uid, true);
4000 } else {
4001 mAppIdleTempWhitelistAppIds.delete(uid);
4002 }
4003 updateRuleForAppIdleUL(uid);
4004 updateRulesForPowerRestrictionsUL(uid);
4005 } finally {
4006 Binder.restoreCallingIdentity(token);
4007 }
4008 }
4009 }
4010
4011 /** Return the list of UIDs currently in the app idle whitelist. */
4012 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004013 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004014 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4015
4016 synchronized (mUidRulesFirstLock) {
4017 final int len = mAppIdleTempWhitelistAppIds.size();
4018 int[] uids = new int[len];
4019 for (int i = 0; i < len; ++i) {
4020 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4021 }
4022 return uids;
4023 }
4024 }
4025
4026 /** Returns if the UID is currently considered idle. */
4027 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004028 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004029 synchronized (mUidRulesFirstLock) {
4030 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4031 // UID is temporarily whitelisted.
4032 return false;
4033 }
4034 }
4035
Amith Yamasani15e472352015-04-24 19:06:07 -07004036 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4037 final int userId = UserHandle.getUserId(uid);
4038
songjinshi0655edd2016-05-18 19:55:32 +08004039 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004040 for (String packageName : packages) {
4041 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4042 return false;
4043 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004044 }
4045 }
4046 return true;
4047 }
4048
4049 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004050 * Checks if an uid has INTERNET permissions.
4051 * <p>
4052 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004053 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004054 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004055 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004056 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004057 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004058 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004059 }
4060 } catch (RemoteException e) {
4061 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004062 return true;
4063 }
4064
4065 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004066 * Clears all state - internal and external - associated with an UID.
4067 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004068 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004069 private void onUidDeletedUL(int uid) {
4070 // First cleanup in-memory state synchronously...
4071 mUidRules.delete(uid);
4072 mUidPolicy.delete(uid);
4073 mUidFirewallStandbyRules.delete(uid);
4074 mUidFirewallDozableRules.delete(uid);
4075 mUidFirewallPowerSaveRules.delete(uid);
4076 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4077 mPowerSaveWhitelistAppIds.delete(uid);
4078 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004079 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004080
4081 // ...then update iptables asynchronously.
4082 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4083 }
4084
4085 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004086 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004087 *
Felipe Leme781ba142016-05-09 16:24:48 -07004088 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004089 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004090 * <li>Doze mode
4091 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004092 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004093 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004094 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004095 *
4096 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004097 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004098 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004099 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004100 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004101 updateRuleForDeviceIdleUL(uid);
4102 updateRuleForAppIdleUL(uid);
4103 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004104
4105 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004106 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004107
4108 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004109 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004110 }
4111
Felipe Leme70c57c22016-03-29 10:45:13 -07004112 /**
4113 * Applies network rules to bandwidth controllers based on process state and user-defined
4114 * restrictions (blacklist / whitelist).
4115 *
4116 * <p>
4117 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4118 * networks:
4119 * <ul>
4120 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4121 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4122 * also blacklisted.
4123 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004124 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004125 * <ul>
4126 *
4127 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4128 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4129 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4130 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004131 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004132 * {@link INetworkManagementService}, but this method should also be called in events (like
4133 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4134 * following rules should also be applied:
4135 *
4136 * <ul>
4137 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4138 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4139 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4140 * {@code bw_penalty_box}.
4141 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4142 * </ul>
4143 *
4144 * <p>For optimization, the rules are only applied on user apps that have internet access
4145 * permission, since there is no need to change the {@code iptables} rule if the app does not
4146 * have permission to use the internet.
4147 *
4148 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004149 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004150 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004151 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004152 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4153 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4154 "updateRulesForDataUsageRestrictionsUL: " + uid);
4155 }
4156 try {
4157 updateRulesForDataUsageRestrictionsULInner(uid);
4158 } finally {
4159 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4160 }
4161 }
4162
4163 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004164 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004165 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004166 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004167 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004168
Dianne Hackborn497175b2014-07-01 12:56:08 -07004169 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004170 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004171 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004172 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004173
Felipe Leme781ba142016-05-09 16:24:48 -07004174 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004175 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004176 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4177 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004178
Felipe Leme70c57c22016-03-29 10:45:13 -07004179 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004180 if (isRestrictedByAdmin) {
4181 newRule = RULE_REJECT_METERED;
4182 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004183 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4184 newRule = RULE_TEMPORARY_ALLOW_METERED;
4185 } else if (isWhitelisted) {
4186 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004187 }
4188 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004189 if (isBlacklisted) {
4190 newRule = RULE_REJECT_METERED;
4191 } else if (mRestrictBackground && isWhitelisted) {
4192 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004193 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004194 }
Felipe Leme781ba142016-05-09 16:24:48 -07004195 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004196
Felipe Lemef28983d2016-03-25 12:18:23 -07004197 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004198 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004199 + ": isForeground=" +isForeground
4200 + ", isBlacklisted=" + isBlacklisted
4201 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004202 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004203 + ", oldRule=" + uidRulesToString(oldRule)
4204 + ", newRule=" + uidRulesToString(newRule)
4205 + ", newUidRules=" + uidRulesToString(newUidRules)
4206 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004207 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004208
Felipe Leme46c4fc32016-05-04 09:21:43 -07004209 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004210 mUidRules.delete(uid);
4211 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004212 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004213 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004214
Felipe Leme70c57c22016-03-29 10:45:13 -07004215 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004216 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004217 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004218 // Temporarily whitelist foreground app, removing from blacklist if necessary
4219 // (since bw_penalty_box prevails over bw_happy_box).
4220
4221 setMeteredNetworkWhitelist(uid, true);
4222 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4223 // but ideally it should be just:
4224 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004225 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004226 setMeteredNetworkBlacklist(uid, false);
4227 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004228 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004229 // Remove temporary whitelist from app that is not on foreground anymore.
4230
4231 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4232 // but ideally they should be just:
4233 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4234 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004235 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004236 setMeteredNetworkWhitelist(uid, false);
4237 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004238 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004239 setMeteredNetworkBlacklist(uid, true);
4240 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004241 } else if (hasRule(newRule, RULE_REJECT_METERED)
4242 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004243 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004244 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004245 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004246 // Since blacklist prevails over whitelist, we need to handle the special case
4247 // where app is whitelisted and blacklisted at the same time (although such
4248 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004249 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004250 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004251 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4252 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004253 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004254 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004255 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004256 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004257 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4258 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004259 + ", whitelisted=" + isWhitelisted
4260 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004261 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004262 + ", newRule=" + uidRulesToString(newUidRules)
4263 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004264 }
Felipe Leme781ba142016-05-09 16:24:48 -07004265
Sudheer Shankac9d94072017-02-22 22:13:55 +00004266 // Dispatch changed rule to existing listeners.
4267 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004268 }
4269 }
4270
4271 /**
4272 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4273 * listeners in case of change.
4274 * <p>
4275 * There are 3 power-related rules that affects whether an app has background access on
4276 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4277 * restriction, it's added to the equivalent firewall chain:
4278 * <ul>
4279 * <li>App is idle: {@code fw_standby} firewall chain.
4280 * <li>Device is idle: {@code fw_dozable} firewall chain.
4281 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4282 * </ul>
4283 * <p>
4284 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4285 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4286 * <p>
4287 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4288 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004289 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004290 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004291 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4292
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004293 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004294
Sudheer Shankac9d94072017-02-22 22:13:55 +00004295 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004296 mUidRules.delete(uid);
4297 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004298 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004299 }
4300 }
4301
4302 /**
4303 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4304 *
4305 * @param uid the uid of the app to update rules for
4306 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004307 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004308 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004309 */
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004310 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004311 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4312 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004313 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004314 }
4315 try {
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004316 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004317 } finally {
4318 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4319 }
4320 }
4321
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004322 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules) {
Felipe Leme781ba142016-05-09 16:24:48 -07004323 if (!isUidValidForBlacklistRules(uid)) {
4324 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004325 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004326 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004327
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004328 final boolean isIdle = isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004329 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004330 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004331
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004332 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004333 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4334 int newRule = RULE_NONE;
4335
4336 // First step: define the new rule based on user restrictions and foreground state.
4337
4338 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4339 // by considering the foreground and non-foreground states.
4340 if (isForeground) {
4341 if (restrictMode) {
4342 newRule = RULE_ALLOW_ALL;
4343 }
4344 } else if (restrictMode) {
4345 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4346 }
4347
4348 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4349
4350 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004351 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004352 + ", isIdle: " + isIdle
4353 + ", mRestrictPower: " + mRestrictPower
4354 + ", mDeviceIdleMode: " + mDeviceIdleMode
4355 + ", isForeground=" + isForeground
4356 + ", isWhitelisted=" + isWhitelisted
4357 + ", oldRule=" + uidRulesToString(oldRule)
4358 + ", newRule=" + uidRulesToString(newRule)
4359 + ", newUidRules=" + uidRulesToString(newUidRules)
4360 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4361 }
4362
Felipe Leme781ba142016-05-09 16:24:48 -07004363 // Second step: notify listeners if state changed.
4364 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004365 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004366 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004367 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004368 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4369 } else {
4370 // All scenarios should have been covered above
4371 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4372 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004373 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004374 + ", newRule=" + uidRulesToString(newUidRules)
4375 + ", oldRule=" + uidRulesToString(oldUidRules));
4376 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004377 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004378 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004379
Sudheer Shankac9d94072017-02-22 22:13:55 +00004380 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004381 }
4382
Christopher Tateb909c4d52019-10-21 12:50:37 -07004383 private class NetPolicyAppIdleStateChangeListener extends AppIdleStateChangeListener {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004384 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004385 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4386 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004387 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004388 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4389 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004390 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004391 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004392 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004393 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004394 }
4395 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004396 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004397 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004398 }
4399
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004400 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4401 if (listener != null) {
4402 try {
4403 listener.onUidRulesChanged(uid, uidRules);
4404 } catch (RemoteException ignored) {
4405 }
4406 }
4407 }
4408
4409 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4410 String[] meteredIfaces) {
4411 if (listener != null) {
4412 try {
4413 listener.onMeteredIfacesChanged(meteredIfaces);
4414 } catch (RemoteException ignored) {
4415 }
4416 }
4417 }
4418
4419 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4420 boolean restrictBackground) {
4421 if (listener != null) {
4422 try {
4423 listener.onRestrictBackgroundChanged(restrictBackground);
4424 } catch (RemoteException ignored) {
4425 }
4426 }
4427 }
4428
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004429 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4430 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004431 if (listener != null) {
4432 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004433 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004434 } catch (RemoteException ignored) {
4435 }
4436 }
4437 }
4438
Jeff Sharkey9252b342018-01-19 07:58:35 +09004439 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
Sarah Chin7af1fd02019-09-26 11:37:13 -07004440 int overrideMask, int overrideValue) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09004441 if (listener != null) {
4442 try {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004443 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4444 } catch (RemoteException ignored) {
4445 }
4446 }
4447 }
4448
4449 private void dispatchSubscriptionPlansChanged(INetworkPolicyListener listener, int subId,
4450 SubscriptionPlan[] plans) {
4451 if (listener != null) {
4452 try {
4453 listener.onSubscriptionPlansChanged(subId, plans);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004454 } catch (RemoteException ignored) {
4455 }
4456 }
4457 }
4458
Makoto Onuki8e777332017-03-28 11:25:47 -07004459 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004460 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004461 public boolean handleMessage(Message msg) {
4462 switch (msg.what) {
4463 case MSG_RULES_CHANGED: {
4464 final int uid = msg.arg1;
4465 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004466 final int length = mListeners.beginBroadcast();
4467 for (int i = 0; i < length; i++) {
4468 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4469 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004470 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004471 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004472 return true;
4473 }
4474 case MSG_METERED_IFACES_CHANGED: {
4475 final String[] meteredIfaces = (String[]) msg.obj;
4476 final int length = mListeners.beginBroadcast();
4477 for (int i = 0; i < length; i++) {
4478 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004479 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004480 }
4481 mListeners.finishBroadcast();
4482 return true;
4483 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004484 case MSG_LIMIT_REACHED: {
4485 final String iface = (String) msg.obj;
4486
Felipe Lemef0823852016-06-08 13:43:08 -07004487 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004488 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004489 // force stats update to make sure we have
4490 // numbers that caused alert to trigger.
4491 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004492
Felipe Lemef0823852016-06-08 13:43:08 -07004493 updateNetworkEnabledNL();
4494 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004495 }
4496 }
4497 return true;
4498 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004499 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4500 final boolean restrictBackground = msg.arg1 != 0;
4501 final int length = mListeners.beginBroadcast();
4502 for (int i = 0; i < length; i++) {
4503 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004504 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004505 }
4506 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004507 final Intent intent =
4508 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4509 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4510 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4511 return true;
4512 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004513 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004514 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004515 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004516 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004517 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004518 final int length = mListeners.beginBroadcast();
4519 for (int i = 0; i < length; i++) {
4520 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004521 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004522 }
4523 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004524 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4525 if (notifyApp.booleanValue()) {
4526 broadcastRestrictBackgroundChanged(uid, notifyApp);
4527 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004528 return true;
4529 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004530 case MSG_ADVISE_PERSIST_THRESHOLD: {
4531 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004532 // make sure stats are recorded frequently enough; we aim
4533 // for 2MB threshold for 2GB/month rules.
4534 final long persistThreshold = lowestRule / 1000;
4535 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004536 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004537 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004538 case MSG_UPDATE_INTERFACE_QUOTA: {
4539 removeInterfaceQuota((String) msg.obj);
4540 // int params need to be stitched back into a long
4541 setInterfaceQuota((String) msg.obj,
4542 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4543 return true;
4544 }
4545 case MSG_REMOVE_INTERFACE_QUOTA: {
4546 removeInterfaceQuota((String) msg.obj);
4547 return true;
4548 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004549 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4550 resetUidFirewallRules(msg.arg1);
4551 return true;
4552 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004553 case MSG_SUBSCRIPTION_OVERRIDE: {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004554 final int overrideMask = msg.arg1;
4555 final int overrideValue = msg.arg2;
4556 final int subId = (int) msg.obj;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004557 final int length = mListeners.beginBroadcast();
4558 for (int i = 0; i < length; i++) {
4559 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Sarah Chin7af1fd02019-09-26 11:37:13 -07004560 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004561 }
4562 mListeners.finishBroadcast();
4563 return true;
4564 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004565 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4566 final int userId = msg.arg1;
4567 final Set<String> packageNames = (Set<String>) msg.obj;
4568 setMeteredRestrictedPackagesInternal(packageNames, userId);
4569 return true;
4570 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004571 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4572 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4573 final boolean enabled = msg.arg1 != 0;
4574 setNetworkTemplateEnabledInner(template, enabled);
4575 return true;
4576 }
Sarah Chin7af1fd02019-09-26 11:37:13 -07004577 case MSG_SUBSCRIPTION_PLANS_CHANGED: {
4578 final SubscriptionPlan[] plans = (SubscriptionPlan[]) msg.obj;
4579 final int subId = msg.arg1;
4580 final int length = mListeners.beginBroadcast();
4581 for (int i = 0; i < length; i++) {
4582 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4583 dispatchSubscriptionPlansChanged(listener, subId, plans);
4584 }
4585 mListeners.finishBroadcast();
4586 return true;
4587 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004588 default: {
4589 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004590 }
4591 }
4592 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004593 };
4594
4595 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4596 @Override
4597 public boolean handleMessage(Message msg) {
4598 switch (msg.what) {
4599 case UID_MSG_STATE_CHANGED: {
4600 final int uid = msg.arg1;
4601 final int procState = msg.arg2;
4602 final long procStateSeq = (Long) msg.obj;
4603
4604 handleUidChanged(uid, procState, procStateSeq);
4605 return true;
4606 }
4607 case UID_MSG_GONE: {
4608 final int uid = msg.arg1;
4609 handleUidGone(uid);
4610 return true;
4611 }
4612 default: {
4613 return false;
4614 }
4615 }
4616 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004617 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004618
Makoto Onuki8e777332017-03-28 11:25:47 -07004619 void handleUidChanged(int uid, int procState, long procStateSeq) {
4620 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4621 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004622 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004623 synchronized (mUidRulesFirstLock) {
4624 // We received a uid state change callback, add it to the history so that it
4625 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004626 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004627 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004628 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004629 // Updating the network rules is done, so notify AMS about this.
4630 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4631 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004632 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4633 // called from the handler, so there's no multi-threading issue.
4634 if (updated) {
4635 updateNetworkStats(uid, isUidStateForeground(procState));
4636 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004637 } finally {
4638 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4639 }
4640 }
4641
4642 void handleUidGone(int uid) {
4643 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4644 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004645 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004646 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004647 updated = removeUidStateUL(uid);
4648 }
4649 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4650 // called from the handler, so there's no multi-threading issue.
4651 if (updated) {
4652 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004653 }
4654 } finally {
4655 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4656 }
4657 }
4658
Felipe Leme57e3d312016-08-23 14:42:52 -07004659 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4660 final PackageManager pm = mContext.getPackageManager();
4661 final String[] packages = pm.getPackagesForUid(uid);
4662 if (packages != null) {
4663 final int userId = UserHandle.getUserId(uid);
4664 for (String packageName : packages) {
4665 final Intent intent =
4666 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4667 intent.setPackage(packageName);
4668 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4669 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4670 }
4671 }
4672 }
4673
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004674 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4675 // long quotaBytes split up into two ints to fit in message
4676 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4677 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4678 }
4679
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004680 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004681 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004682 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004683 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004684 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004685 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004686 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004687 }
4688 }
4689
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004690 private void removeInterfaceQuotaAsync(String iface) {
4691 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4692 }
4693
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004694 private void removeInterfaceQuota(String iface) {
4695 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004696 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004697 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004698 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004699 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004700 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004701 }
4702 }
4703
Felipe Leme70c57c22016-03-29 10:45:13 -07004704 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4705 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004706 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004707 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004708 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004709 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4710 } catch (RemoteException e) {
4711 // ignored; service lives in system_server
4712 }
4713 }
4714
4715 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4716 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4717 try {
4718 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4719 } catch (IllegalStateException e) {
4720 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004721 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004722 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004723 }
4724 }
4725
Felipe Lemebc853dd2016-09-08 13:26:55 -07004726 private static final int CHAIN_TOGGLE_NONE = 0;
4727 private static final int CHAIN_TOGGLE_ENABLE = 1;
4728 private static final int CHAIN_TOGGLE_DISABLE = 2;
4729 @Retention(RetentionPolicy.SOURCE)
4730 @IntDef(flag = false, value = {
4731 CHAIN_TOGGLE_NONE,
4732 CHAIN_TOGGLE_ENABLE,
4733 CHAIN_TOGGLE_DISABLE
4734 })
4735 public @interface ChainToggleType {
4736 }
4737
4738 /**
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004739 * Calls {@link #setUidFirewallRulesUL(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004740 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004741 *
4742 * @param chain firewall chain.
4743 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4744 * @param toggle whether the chain should be enabled, disabled, or not changed.
4745 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004746 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004747 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004748 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004749 if (uidRules != null) {
4750 setUidFirewallRulesUL(chain, uidRules);
4751 }
4752 if (toggle != CHAIN_TOGGLE_NONE) {
4753 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4754 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004755 }
4756
Amith Yamasani15e472352015-04-24 19:06:07 -07004757 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004758 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4759 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4760 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004761 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004762 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004763 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004764 int size = uidRules.size();
4765 int[] uids = new int[size];
4766 int[] rules = new int[size];
4767 for(int index = size - 1; index >= 0; --index) {
4768 uids[index] = uidRules.keyAt(index);
4769 rules[index] = uidRules.valueAt(index);
4770 }
4771 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004772 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004773 } catch (IllegalStateException e) {
4774 Log.wtf(TAG, "problem setting firewall uid rules", e);
4775 } catch (RemoteException e) {
4776 // ignored; service lives in system_server
4777 }
4778 }
4779
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004780 /**
4781 * Add or remove a uid to the firewall blacklist for all network ifaces.
4782 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004783 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004784 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4785 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4786 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004787 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004788 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004789 if (chain == FIREWALL_CHAIN_DOZABLE) {
4790 mUidFirewallDozableRules.put(uid, rule);
4791 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4792 mUidFirewallStandbyRules.put(uid, rule);
4793 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4794 mUidFirewallPowerSaveRules.put(uid, rule);
4795 }
4796
4797 try {
4798 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004799 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004800 } catch (IllegalStateException e) {
4801 Log.wtf(TAG, "problem setting firewall uid rules", e);
4802 } catch (RemoteException e) {
4803 // ignored; service lives in system_server
4804 }
4805 } finally {
4806 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004807 }
4808 }
4809
4810 /**
4811 * Add or remove a uid to the firewall blacklist for all network ifaces.
4812 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004813 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004814 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004815 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4816 mFirewallChainStates.get(chain) == enable) {
4817 // All is the same, nothing to do.
4818 return;
4819 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004820 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004821 try {
4822 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004823 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004824 } catch (IllegalStateException e) {
4825 Log.wtf(TAG, "problem enable firewall chain", e);
4826 } catch (RemoteException e) {
4827 // ignored; service lives in system_server
4828 }
4829 }
4830
Felipe Leme03e95e22016-09-09 09:25:31 -07004831 /**
4832 * Resets all firewall rules associated with an UID.
4833 */
4834 private void resetUidFirewallRules(int uid) {
4835 try {
4836 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4837 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4838 mNetworkManager
4839 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4840 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4841 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4842 } catch (IllegalStateException e) {
4843 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4844 } catch (RemoteException e) {
4845 // ignored; service lives in system_server
4846 }
4847 }
4848
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004849 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004850 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004851 return getNetworkTotalBytes(template, start, end);
4852 }
4853
4854 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004855 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004856 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004857 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004858 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004859 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004860 }
4861 }
4862
4863 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4864 try {
4865 return mNetworkStats.getNetworkUidBytes(template, start, end);
4866 } catch (RuntimeException e) {
4867 Slog.w(TAG, "Failed to read network stats: " + e);
4868 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004869 }
4870 }
4871
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004872 private boolean isBandwidthControlEnabled() {
4873 final long token = Binder.clearCallingIdentity();
4874 try {
4875 return mNetworkManager.isBandwidthControlEnabled();
4876 } catch (RemoteException e) {
4877 // ignored; service lives in system_server
4878 return false;
4879 } finally {
4880 Binder.restoreCallingIdentity(token);
4881 }
4882 }
4883
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004884 private static Intent buildAllowBackgroundDataIntent() {
4885 return new Intent(ACTION_ALLOW_BACKGROUND);
4886 }
4887
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004888 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4889 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004890 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4891 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4892 return intent;
4893 }
4894
4895 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4896 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4897 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004898 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4899 return intent;
4900 }
4901
Wei Liu546cb772016-07-21 16:19:01 -07004902 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004903 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004904 intent.setComponent(ComponentName.unflattenFromString(
4905 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004906 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4907 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4908 return intent;
4909 }
4910
Wei Liu546cb772016-07-21 16:19:01 -07004911 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004912 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004913 intent.setComponent(ComponentName.unflattenFromString(
4914 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004915 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4916 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4917 return intent;
4918 }
4919
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004920 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004921 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004922 mHandler.getLooper().getQueue().addIdleHandler(handler);
4923 }
4924
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004925 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004926 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004927 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
Kweku Adams25fa3a72019-07-12 17:00:17 -07004928 if (mRestrictBackgroundLowPowerMode == result.batterySaverEnabled) {
4929 // Nothing changed. Nothing to do.
4930 return;
4931 }
4932 mRestrictBackgroundLowPowerMode = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004933
Kweku Adams25fa3a72019-07-12 17:00:17 -07004934 boolean restrictBackground = mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004935 boolean shouldInvokeRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -07004936 // store the temporary mRestrictBackgroundChangedInBsm and update it at the end.
jackqdyulei29c82ab2017-03-10 14:09:16 -08004937 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4938
Kweku Adams25fa3a72019-07-12 17:00:17 -07004939 if (mRestrictBackgroundLowPowerMode) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004940 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4941 // turn it on.
Kweku Adams25fa3a72019-07-12 17:00:17 -07004942 shouldInvokeRestrictBackground = !mRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004943 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4944 localRestrictBgChangedInBsm = false;
4945 } else {
4946 // Try to restore the restrictBackground if it doesn't change in bsm
4947 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4948 restrictBackground = mRestrictBackgroundBeforeBsm;
4949 }
4950
4951 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004952 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004953 }
4954
4955 // Change it at last so setRestrictBackground() won't affect this variable
4956 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4957 }
4958
Jeff Sharkey1b861272011-05-22 00:34:52 -07004959 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4960 final int size = source.size();
4961 for (int i = 0; i < size; i++) {
4962 target.put(source.keyAt(i), true);
4963 }
4964 }
4965
Stuart Scottf1fb3972015-04-02 18:00:02 -07004966 @Override
4967 public void factoryReset(String subscriber) {
4968 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4969
Stuart Scotte3e314d2015-04-20 14:07:45 -07004970 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4971 return;
4972 }
4973
Stuart Scottf1fb3972015-04-02 18:00:02 -07004974 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004975 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004976 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4977 for (NetworkPolicy policy : policies) {
4978 if (policy.template.equals(template)) {
4979 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4980 policy.inferred = false;
4981 policy.clearSnooze();
4982 }
4983 }
4984 setNetworkPolicies(policies);
4985
4986 // Turn restrict background data off
4987 setRestrictBackground(false);
4988
Stuart Scotte3e314d2015-04-20 14:07:45 -07004989 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4990 // Remove app's "restrict background data" flag
4991 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4992 setUidPolicy(uid, POLICY_NONE);
4993 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004994 }
4995 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004996
Sudheer Shankab8f23162017-08-04 13:30:10 -07004997 @Override
4998 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004999 final long startTime = mStatLogger.getTime();
5000
Sudheer Shankab8f23162017-08-04 13:30:10 -07005001 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07005002 final int uidRules;
5003 final boolean isBackgroundRestricted;
5004 synchronized (mUidRulesFirstLock) {
5005 uidRules = mUidRules.get(uid, RULE_NONE);
5006 isBackgroundRestricted = mRestrictBackground;
5007 }
junyulai05986c62018-08-07 19:50:45 +08005008 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5009 isBackgroundRestricted, mLogger);
5010
5011 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5012
5013 return ret;
5014 }
5015
5016 private static boolean isSystem(int uid) {
5017 return uid < Process.FIRST_APPLICATION_UID;
5018 }
5019
5020 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
5021 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5022 final int reason;
5023 // Networks are never blocked for system components
5024 if (isSystem(uid)) {
5025 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005026 }
junyulai05986c62018-08-07 19:50:45 +08005027 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5028 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005029 }
junyulai05986c62018-08-07 19:50:45 +08005030 else if (!isNetworkMetered) {
5031 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005032 }
junyulai05986c62018-08-07 19:50:45 +08005033 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5034 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005035 }
junyulai05986c62018-08-07 19:50:45 +08005036 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5037 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005038 }
junyulai05986c62018-08-07 19:50:45 +08005039 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5040 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005041 }
junyulai05986c62018-08-07 19:50:45 +08005042 else if (isBackgroundRestricted) {
5043 reason = NTWK_BLOCKED_BG_RESTRICT;
5044 }
5045 else {
5046 reason = NTWK_ALLOWED_DEFAULT;
5047 }
5048
5049 final boolean blocked;
5050 switch(reason) {
5051 case NTWK_ALLOWED_DEFAULT:
5052 case NTWK_ALLOWED_NON_METERED:
5053 case NTWK_ALLOWED_TMP_WHITELIST:
5054 case NTWK_ALLOWED_WHITELIST:
5055 case NTWK_ALLOWED_SYSTEM:
5056 blocked = false;
5057 break;
5058 case NTWK_BLOCKED_POWER:
5059 case NTWK_BLOCKED_BLACKLIST:
5060 case NTWK_BLOCKED_BG_RESTRICT:
5061 blocked = true;
5062 break;
5063 default:
5064 throw new IllegalArgumentException();
5065 }
5066 if (logger != null) {
5067 logger.networkBlocked(uid, reason);
5068 }
5069
5070 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005071 }
5072
Felipe Lemed17fda42016-04-29 11:12:45 -07005073 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5074
5075 @Override
5076 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005077 synchronized (mUidRulesFirstLock) {
5078 boolean changed = removeUserStateUL(userId, false);
5079 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005080 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005081 synchronized (mNetworkPoliciesSecondLock) {
5082 writePolicyAL();
5083 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005084 }
5085 }
5086 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005087
5088 /**
5089 * @return true if the given uid is restricted from doing networking on metered networks.
5090 */
5091 @Override
5092 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5093 final int uidRules;
5094 final boolean isBackgroundRestricted;
5095 synchronized (mUidRulesFirstLock) {
5096 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5097 isBackgroundRestricted = mRestrictBackground;
5098 }
5099 return isBackgroundRestricted
5100 && !hasRule(uidRules, RULE_ALLOW_METERED)
5101 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5102 }
5103
5104 /**
5105 * @return true if networking is blocked on the given interface for the given uid according
5106 * to current networking policies.
5107 */
5108 @Override
5109 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005110 final long startTime = mStatLogger.getTime();
5111
junyulai05986c62018-08-07 19:50:45 +08005112 final int uidRules;
5113 final boolean isBackgroundRestricted;
5114 synchronized (mUidRulesFirstLock) {
5115 uidRules = mUidRules.get(uid, RULE_NONE);
5116 isBackgroundRestricted = mRestrictBackground;
5117 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005118 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005119 synchronized (mNetworkPoliciesSecondLock) {
5120 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005121 }
junyulai05986c62018-08-07 19:50:45 +08005122 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5123 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005124
5125 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5126
5127 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005128 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005129
5130 @Override
5131 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5132 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005133 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005134 if (added) {
5135 mPowerSaveTempWhitelistAppIds.put(appId, true);
5136 } else {
5137 mPowerSaveTempWhitelistAppIds.delete(appId);
5138 }
5139 updateRulesForTempWhitelistChangeUL(appId);
5140 }
5141 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005142
5143 @Override
5144 public SubscriptionPlan getSubscriptionPlan(Network network) {
5145 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005146 final int subId = getSubIdLocked(network);
5147 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005148 }
5149 }
5150
5151 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005152 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5153 synchronized (mNetworkPoliciesSecondLock) {
5154 final int subId = findRelevantSubIdNL(template);
5155 return getPrimarySubscriptionPlanLocked(subId);
5156 }
5157 }
5158
5159 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005160 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005161 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005162 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005163 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005164 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005165 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005166 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5167 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5168 }
5169
5170 if (quotaType == QUOTA_TYPE_JOBS) {
5171 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5172 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5173 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5174 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5175 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5176 } else {
5177 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5178 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005179 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005180
5181 @Override
5182 public void onAdminDataAvailable() {
5183 mAdminDataAvailableLatch.countDown();
5184 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005185
5186 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005187 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5188 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5189 }
5190
5191 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005192 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5193 setMeteredRestrictedPackagesInternal(packageNames, userId);
5194 }
5195
5196 @Override
5197 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5198 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5199 userId, 0, packageNames).sendToTarget();
5200 }
5201 }
5202
5203 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5204 synchronized (mUidRulesFirstLock) {
5205 final Set<Integer> newRestrictedUids = new ArraySet<>();
5206 for (String packageName : packageNames) {
5207 final int uid = getUidForPackage(packageName, userId);
5208 if (uid >= 0) {
5209 newRestrictedUids.add(uid);
5210 }
5211 }
5212 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5213 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5214 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5215 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5216 }
5217 }
5218
5219 private int getUidForPackage(String packageName, int userId) {
5220 try {
5221 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5222 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5223 } catch (NameNotFoundException e) {
5224 return -1;
5225 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005226 }
5227
5228 private int parseSubId(NetworkState state) {
5229 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5230 int subId = INVALID_SUBSCRIPTION_ID;
5231 if (state != null && state.networkCapabilities != null
5232 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5233 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5234 if (spec instanceof StringNetworkSpecifier) {
5235 try {
5236 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5237 } catch (NumberFormatException e) {
5238 }
5239 }
5240 }
5241 return subId;
5242 }
5243
Andreas Gampea36dc622018-02-05 17:19:22 -08005244 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005245 private int getSubIdLocked(Network network) {
5246 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005247 }
5248
Andreas Gampea36dc622018-02-05 17:19:22 -08005249 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005250 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5251 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005252 if (!ArrayUtils.isEmpty(plans)) {
5253 for (SubscriptionPlan plan : plans) {
5254 if (plan.getCycleRule().isRecurring()) {
5255 // Recurring plans will always have an active cycle
5256 return plan;
5257 } else {
5258 // Non-recurring plans need manual test for active cycle
5259 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5260 if (cycle.contains(ZonedDateTime.now(mClock))) {
5261 return plan;
5262 }
5263 }
5264 }
5265 }
5266 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005267 }
5268
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005269 /**
5270 * This will only ever be called once - during device boot.
5271 */
5272 private void waitForAdminData() {
5273 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5274 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5275 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5276 }
5277 }
5278
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005279 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5280 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005281 if (!mNetworkManagerReady) {
5282 return;
5283 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005284 if (oldRestrictedUids == null) {
5285 for (int uid : newRestrictedUids) {
5286 updateRulesForDataUsageRestrictionsUL(uid);
5287 }
5288 return;
5289 }
5290 for (int uid : oldRestrictedUids) {
5291 if (!newRestrictedUids.contains(uid)) {
5292 updateRulesForDataUsageRestrictionsUL(uid);
5293 }
5294 }
5295 for (int uid : newRestrictedUids) {
5296 if (!oldRestrictedUids.contains(uid)) {
5297 updateRulesForDataUsageRestrictionsUL(uid);
5298 }
5299 }
5300 }
5301
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005302 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005303 private boolean isRestrictedByAdminUL(int uid) {
5304 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5305 UserHandle.getUserId(uid));
5306 return restrictedUids != null && restrictedUids.contains(uid);
5307 }
5308
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005309 private static boolean hasRule(int uidRules, int rule) {
5310 return (uidRules & rule) != 0;
5311 }
5312
Jeff Sharkey2e471452018-01-19 18:02:47 +09005313 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5314 return (val != null) ? val : new NetworkState[0];
5315 }
5316
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005317 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5318 String key, boolean defaultValue) {
5319 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5320 }
5321
Chris Wren193ae6b2017-03-31 15:17:11 -04005322 private class NotificationId {
5323 private final String mTag;
5324 private final int mId;
5325
5326 NotificationId(NetworkPolicy policy, int type) {
5327 mTag = buildNotificationTag(policy, type);
5328 mId = type;
5329 }
5330
5331 @Override
5332 public boolean equals(Object o) {
5333 if (this == o) return true;
5334 if (!(o instanceof NotificationId)) return false;
5335 NotificationId that = (NotificationId) o;
5336 return Objects.equals(mTag, that.mTag);
5337 }
5338
5339 @Override
5340 public int hashCode() {
5341 return Objects.hash(mTag);
5342 }
5343
5344 /**
5345 * Build unique tag that identifies an active {@link NetworkPolicy}
5346 * notification of a specific type, like {@link #TYPE_LIMIT}.
5347 */
5348 private String buildNotificationTag(NetworkPolicy policy, int type) {
5349 return TAG + ":" + policy.template.hashCode() + ":" + type;
5350 }
5351
5352 public String getTag() {
5353 return mTag;
5354 }
5355
5356 public int getId() {
5357 return mId;
5358 }
5359 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005360}