blob: 3b14d50f3c07ca49c536b26aaf00166f1984deba [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 /**
368 * Indicates the maximum wait time for admin data to be available;
369 */
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() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700915 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700916 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
917 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700918 }
919
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700920 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700921 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700922 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700923
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700924 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700925 }
926
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700927 @Override public void onUidIdle(int uid, boolean disabled) {
928 }
929
930 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700931 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700932 };
933
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700934 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700935 @Override
936 public void onReceive(Context context, Intent intent) {
937 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700938 synchronized (mUidRulesFirstLock) {
939 updatePowerSaveWhitelistUL();
940 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700941 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700942 }
943 }
944 };
945
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700946 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700947 @Override
948 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700949 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700950
951 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700952 final int uid = intent.getIntExtra(EXTRA_UID, -1);
953 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700954
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700955 if (ACTION_PACKAGE_ADDED.equals(action)) {
956 // update rules for UID, since it might be subject to
957 // global background data policy
958 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700959 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700960 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700961 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700962 }
963 }
964 };
965
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700966 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700967 @Override
968 public void onReceive(Context context, Intent intent) {
969 // on background handler thread, and UID_REMOVED is protected
970
971 final int uid = intent.getIntExtra(EXTRA_UID, -1);
972 if (uid == -1) return;
973
974 // remove any policy and update rules to clean up
975 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700976 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700977 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700978 synchronized (mNetworkPoliciesSecondLock) {
979 writePolicyAL();
980 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700981 }
982 }
983 };
984
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700985 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700986 @Override
987 public void onReceive(Context context, Intent intent) {
988 // on background handler thread, and USER_ADDED and USER_REMOVED
989 // broadcasts are protected
990
991 final String action = intent.getAction();
992 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
993 if (userId == -1) return;
994
Amith Yamasani15e472352015-04-24 19:06:07 -0700995 switch (action) {
996 case ACTION_USER_REMOVED:
997 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700998 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800999 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -07001000 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -07001001 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001002 // Removing outside removeUserStateUL since that can also be called when
1003 // user resets app preferences.
1004 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001005 if (action == ACTION_USER_ADDED) {
1006 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001007 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001008 }
1009 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001010 synchronized (mNetworkPoliciesSecondLock) {
1011 updateRulesForGlobalChangeAL(true);
1012 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001013 }
1014 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001015 }
1016 }
1017 };
1018
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001019 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 * Receiver that watches for {@link INetworkStatsService} updates, which we
1021 * use to check against {@link NetworkPolicy#warningBytes}.
1022 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001023 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024 @Override
1025 public void onReceive(Context context, Intent intent) {
1026 // on background handler thread, and verified
1027 // READ_NETWORK_USAGE_HISTORY permission above.
1028
Felipe Lemef0823852016-06-08 13:43:08 -07001029 synchronized (mNetworkPoliciesSecondLock) {
1030 updateNetworkEnabledNL();
1031 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001032 }
1033 }
1034 };
1035
1036 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001037 * Receiver that watches for {@link Notification} control of
1038 * {@link #mRestrictBackground}.
1039 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001040 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001041 @Override
1042 public void onReceive(Context context, Intent intent) {
1043 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1044 // permission above.
1045
1046 setRestrictBackground(false);
1047 }
1048 };
1049
1050 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 * Receiver that watches for {@link Notification} control of
1052 * {@link NetworkPolicy#lastWarningSnooze}.
1053 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001054 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001055 @Override
1056 public void onReceive(Context context, Intent intent) {
1057 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1058 // permission above.
1059
1060 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001061 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1062 performSnooze(template, TYPE_WARNING);
1063 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1064 performSnooze(template, TYPE_RAPID);
1065 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001066 }
1067 };
1068
1069 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001070 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001071 * we can perform upgrade logic. After initial upgrade logic, it updates
1072 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001073 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001074 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001075 @Override
1076 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001077 synchronized (mUidRulesFirstLock) {
1078 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001079 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001080 }
1081 }
1082 // Only need to perform upgrade logic once
1083 mContext.unregisterReceiver(this);
1084 }
1085 };
1086
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001087 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1088 Network network) {
1089 final boolean lastValue = lastValues.get(network.netId, false);
1090 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1091 if (changed) {
1092 lastValues.put(network.netId, newValue);
1093 }
1094 return changed;
1095 }
1096
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001097 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1098 @Override
1099 public void onCapabilitiesChanged(Network network,
1100 NetworkCapabilities networkCapabilities) {
1101 if (network == null || networkCapabilities == null) return;
1102
1103 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001104 final boolean newMetered = !networkCapabilities
1105 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001106 final boolean meteredChanged = updateCapabilityChange(
1107 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001108
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001109 final boolean newRoaming = !networkCapabilities
1110 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1111 final boolean roamingChanged = updateCapabilityChange(
1112 mNetworkRoaming, newRoaming, network);
1113
1114 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001115 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001116 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001117 }
1118 }
1119 }
1120 };
1121
1122 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 * Observer that watches for {@link INetworkManagementService} alerts.
1124 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001125 final private INetworkManagementEventObserver mAlertObserver
1126 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 @Override
1128 public void limitReached(String limitName, String iface) {
1129 // only someone like NMS should be calling us
1130 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1131
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001132 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1133 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001134 }
1135 }
1136 };
1137
1138 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001139 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1140 * to show visible notifications as needed.
1141 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001142 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001143 void updateNotificationsNL() {
1144 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001145 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001148 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001149 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150
1151 // TODO: when switching to kernel notifications, compute next future
1152 // cycle boundary to recompute notifications.
1153
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001154 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001155 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001156 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1157 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001158 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001159
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001160 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001161 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001162 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163
Jeff Sharkey53313d72017-07-13 16:47:32 -06001164 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1165 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001166 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1167 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1168 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001169
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001170 // Carrier might want to manage notifications themselves
1171 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001172 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1173 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1174 // Don't show notifications until we confirm that the loaded config is from an
1175 // identified carrier, which may want to manage their own notifications. This method
1176 // should be called every time the carrier config changes anyways, and there's no
1177 // reason to alert if there isn't a carrier.
1178 return;
1179 }
1180
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001181 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1182 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1183 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1184 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1185 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1186 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1187
1188 // Notify when data usage is over warning
1189 if (notifyWarning) {
1190 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1191 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1192 if (!snoozedThisCycle) {
1193 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1194 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001196 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001198 // Notify when data usage is over limit
1199 if (notifyLimit) {
1200 if (policy.isOverLimit(totalBytes)) {
1201 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1202 if (snoozedThisCycle) {
1203 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1204 } else {
1205 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1206 notifyOverLimitNL(policy.template);
1207 }
1208 } else {
1209 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001210 }
1211 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001212
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001213 // Warn if average usage over last 4 days is on track to blow pretty
1214 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001215 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001216 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001217 final long recentStart = now - recentDuration;
1218 final long recentEnd = now;
1219 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001220
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001221 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001222 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001223 final long alertBytes = (policy.limitBytes * 3) / 2;
1224
1225 if (LOGD) {
1226 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1227 + projectedBytes + " alert " + alertBytes);
1228 }
1229
1230 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1231 - DateUtils.DAY_IN_MILLIS;
1232 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001233 enqueueNotification(policy, TYPE_RAPID, 0,
1234 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001235 }
1236 }
1237 }
1238
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001240 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001241 final NotificationId notificationId = beforeNotifs.valueAt(i);
1242 if (!mActiveNotifs.contains(notificationId)) {
1243 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001244 }
1245 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001246
1247 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001248 }
1249
1250 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001251 * Attempt to find a specific app to blame for rapid data usage during the
1252 * given time period.
1253 */
1254 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1255 long start, long end) {
1256 long totalBytes = 0;
1257 long maxBytes = 0;
1258 int maxUid = 0;
1259
1260 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1261 NetworkStats.Entry entry = null;
1262 for (int i = 0; i < stats.size(); i++) {
1263 entry = stats.getValues(i, entry);
1264 final long bytes = entry.rxBytes + entry.txBytes;
1265 totalBytes += bytes;
1266 if (bytes > maxBytes) {
1267 maxBytes = bytes;
1268 maxUid = entry.uid;
1269 }
1270 }
1271
1272 // Only point blame if the majority of usage was done by a single app.
1273 // TODO: support shared UIDs
1274 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1275 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001276 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001277 try {
1278 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1279 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1280 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1281 } catch (NameNotFoundException ignored) {
1282 }
1283 }
1284 }
1285
1286 return null;
1287 }
1288
1289 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001290 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001291 * current device state, such as when
1292 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1293 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001294 *
1295 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1296 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001297 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001298 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001299 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001300 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001301 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1302 final int subId = mSubIdToSubscriberId.keyAt(i);
1303 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001304 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1305 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1306 true);
1307 if (template.matches(probeIdent)) {
1308 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001309 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001310 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001311 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001312 }
1313
1314 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 * Notify that given {@link NetworkTemplate} is over
1316 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1317 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001318 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001319 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001320 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001321 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001322 mOverLimitNotified.add(template);
1323 }
1324 }
1325
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001326 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001327 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001328 mOverLimitNotified.remove(template);
1329 }
1330
1331 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001332 * Show notification for combined {@link NetworkPolicy} and specific type,
1333 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1334 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001335 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1336 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001337 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001338 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001339 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001340 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001341 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001342 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001343 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001344
1345 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001346 final CharSequence title;
1347 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348 switch (type) {
1349 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001350 title = res.getText(R.string.data_usage_warning_title);
1351 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001352 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001353
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001354 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001355
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001356 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1357 builder.setDeleteIntent(PendingIntent.getBroadcast(
1358 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1359
Wei Liu546cb772016-07-21 16:19:01 -07001360 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001361 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001362 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001363 builder.setContentIntent(PendingIntent.getActivityAsUser(
1364 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1365 /* options= */ null, UserHandle.CURRENT));
1366 } else {
1367 builder.setContentIntent(PendingIntent.getActivity(
1368 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1369 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001370 break;
1371 }
1372 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001373 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001374 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001375 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001376 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001377 case MATCH_WIFI:
1378 title = res.getText(R.string.data_usage_wifi_limit_title);
1379 break;
1380 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001381 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001382 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001383 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001384
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001385 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001386 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001387
Wei Liu546cb772016-07-21 16:19:01 -07001388 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001389 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001390 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001391 builder.setContentIntent(PendingIntent.getActivityAsUser(
1392 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1393 /* options= */ null, UserHandle.CURRENT));
1394 } else {
1395 builder.setContentIntent(PendingIntent.getActivity(
1396 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1397 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001398 break;
1399 }
1400 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001401 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001402 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001403 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1404 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001405 case MATCH_WIFI:
1406 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1407 break;
1408 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001409 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001410 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001411 final long overBytes = totalBytes - policy.limitBytes;
1412 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001413 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001414
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001415 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001416 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001417 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001418
Wei Liu546cb772016-07-21 16:19:01 -07001419 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001420 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001421 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001422 builder.setContentIntent(PendingIntent.getActivityAsUser(
1423 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1424 /* options= */ null, UserHandle.CURRENT));
1425 } else {
1426 builder.setContentIntent(PendingIntent.getActivity(
1427 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1428 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001429 break;
1430 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001431 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001432 title = res.getText(R.string.data_usage_rapid_title);
1433 if (rapidBlame != null) {
1434 body = res.getString(R.string.data_usage_rapid_app_body,
1435 rapidBlame.loadLabel(mContext.getPackageManager()));
1436 } else {
1437 body = res.getString(R.string.data_usage_rapid_body);
1438 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001439
Jeff Sharkey2e471452018-01-19 18:02:47 +09001440 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001441
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001442 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1443 builder.setDeleteIntent(PendingIntent.getBroadcast(
1444 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1445
1446 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001447 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001448 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001449 builder.setContentIntent(PendingIntent.getActivityAsUser(
1450 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1451 /* options= */ null, UserHandle.CURRENT));
1452 } else {
1453 builder.setContentIntent(PendingIntent.getActivity(
1454 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1455 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001456 break;
1457 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001458 default: {
1459 return;
1460 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001461 }
1462
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001463 builder.setTicker(title);
1464 builder.setContentTitle(title);
1465 builder.setContentText(body);
1466 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001467
1468 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1469 notificationId.getId(), builder.build(), UserHandle.ALL);
1470 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001471 }
1472
Chris Wren193ae6b2017-03-31 15:17:11 -04001473 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001474 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1475 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001476 }
1477
1478 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001479 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001480 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001481 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001482 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483 @Override
1484 public void onReceive(Context context, Intent intent) {
1485 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1486 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001487 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001488 }
1489 };
1490
Jeff Sharkey146bb332018-04-18 15:42:57 -06001491 private void updateNetworksInternal() {
1492 // Get all of our cross-process communication with telephony out of
1493 // the way before we acquire internal locks.
1494 updateSubscriptions();
1495
1496 synchronized (mUidRulesFirstLock) {
1497 synchronized (mNetworkPoliciesSecondLock) {
1498 ensureActiveMobilePolicyAL();
1499 normalizePoliciesNL();
1500 updateNetworkEnabledNL();
1501 updateNetworkRulesNL();
1502 updateNotificationsNL();
1503 }
1504 }
1505 }
1506
Jeff Sharkey2e471452018-01-19 18:02:47 +09001507 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001508 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001509 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001510 final CountDownLatch latch = new CountDownLatch(1);
1511 mHandler.post(() -> {
1512 latch.countDown();
1513 });
1514 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001515 }
1516
Sudheer Shankac0f85c12019-10-12 15:01:44 -07001517 @VisibleForTesting
1518 Handler getHandlerForTesting() {
1519 return mHandler;
1520 }
1521
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001523 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1524 * if necessary.
1525 *
1526 * @param subId that has its associated NetworkPolicy updated if necessary
1527 * @return if any policies were updated
1528 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001529 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001530 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001531 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001532
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001533 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001534 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001535 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001536 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001537 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1538 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1539 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001540 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1541 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001542 }
1543 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001544 return policyUpdated;
1545 }
1546
1547 /**
1548 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1549 *
1550 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1551 * to do so, it returns the fallback value.
1552 *
1553 * @param config The CarrierConfig to read the value from.
1554 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1555 * @return cycleDay to use in the mobile NetworkPolicy.
1556 */
1557 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001558 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001559 int fallbackCycleDay) {
1560 if (config == null) {
1561 return fallbackCycleDay;
1562 }
1563 int cycleDay =
1564 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1565 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1566 return fallbackCycleDay;
1567 }
1568 // validate cycleDay value
1569 final Calendar cal = Calendar.getInstance();
1570 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1571 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1572 Slog.e(TAG, "Invalid date in "
1573 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1574 return fallbackCycleDay;
1575 }
1576 return cycleDay;
1577 }
1578
1579 /**
1580 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1581 *
1582 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1583 * to do so, it returns the fallback value.
1584 *
1585 * @param config The CarrierConfig to read the value from.
1586 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1587 * @return warningBytes to use in the mobile NetworkPolicy.
1588 */
1589 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001590 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001591 long fallbackWarningBytes) {
1592 if (config == null) {
1593 return fallbackWarningBytes;
1594 }
1595 long warningBytes =
1596 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1597
1598 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1599 return WARNING_DISABLED;
1600 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1601 return getPlatformDefaultWarningBytes();
1602 } else if (warningBytes < 0) {
1603 Slog.e(TAG, "Invalid value in "
1604 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1605 + "non-negative value but got: " + warningBytes);
1606 return fallbackWarningBytes;
1607 }
1608
1609 return warningBytes;
1610 }
1611
1612 /**
1613 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1614 *
1615 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1616 * to do so, it returns the fallback value.
1617 *
1618 * @param config The CarrierConfig to read the value from.
1619 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1620 * @return limitBytes to use in the mobile NetworkPolicy.
1621 */
1622 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001623 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001624 long fallbackLimitBytes) {
1625 if (config == null) {
1626 return fallbackLimitBytes;
1627 }
1628 long limitBytes =
1629 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1630
1631 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1632 return LIMIT_DISABLED;
1633 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1634 return getPlatformDefaultLimitBytes();
1635 } else if (limitBytes < 0) {
1636 Slog.e(TAG, "Invalid value in "
1637 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1638 + "non-negative value but got: " + limitBytes);
1639 return fallbackLimitBytes;
1640 }
1641 return limitBytes;
1642 }
1643
1644 /**
1645 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1646 */
1647 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1648 @Override
1649 public void onReceive(Context context, Intent intent) {
1650 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1651 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1652
1653 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1654 return;
1655 }
1656 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001657
1658 // Get all of our cross-process communication with telephony out of
1659 // the way before we acquire internal locks.
1660 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001661
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001662 synchronized (mUidRulesFirstLock) {
1663 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001664 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1665 if (subscriberId != null) {
1666 ensureActiveMobilePolicyAL(subId, subscriberId);
1667 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1668 } else {
1669 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1670 }
1671
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001672 // update network and notification rules, as the data cycle changed and it's
1673 // possible that we should be triggering warnings/limits now
1674 handleNetworkPoliciesUpdateAL(true);
1675 }
1676 }
1677 }
1678 };
1679
1680 /**
1681 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1682 * one has been updated.
1683 *
1684 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1685 * update.
1686 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001687 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001688 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1689 if (shouldNormalizePolicies) {
1690 normalizePoliciesNL();
1691 }
1692 updateNetworkEnabledNL();
1693 updateNetworkRulesNL();
1694 updateNotificationsNL();
1695 writePolicyAL();
1696 }
1697
1698 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001699 * Proactively control network data connections when they exceed
1700 * {@link NetworkPolicy#limitBytes}.
1701 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001702 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001703 void updateNetworkEnabledNL() {
1704 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001705 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001706
1707 // TODO: reset any policy-disabled networks when any policy is removed
1708 // completely, which is currently rare case.
1709
Makoto Onuki49392d32018-04-11 13:51:02 -07001710 final long startTime = mStatLogger.getTime();
1711
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001712 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1713 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001714 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001715 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001716 setNetworkTemplateEnabled(policy.template, true);
1717 continue;
1718 }
1719
Jeff Sharkey53313d72017-07-13 16:47:32 -06001720 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1721 .cycleIterator(policy).next();
1722 final long start = cycle.first.toInstant().toEpochMilli();
1723 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001724 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001725
1726 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001727 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1728 && policy.lastLimitSnooze < start;
1729 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001730
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001731 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001732 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001733
1734 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001735 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001736 }
1737
1738 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001739 * Proactively disable networks that match the given
1740 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001741 */
1742 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001743 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1744 // held. Call it via the handler.
1745 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1746 .sendToTarget();
1747 }
1748
1749 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001750 // TODO: reach into ConnectivityManager to proactively disable bringing
1751 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001752
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001753 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001754 // If mobile data usage hits the limit or if the user resumes the data, we need to
1755 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001756
Jeff Sharkey146bb332018-04-18 15:42:57 -06001757 final IntArray matchingSubIds = new IntArray();
1758 synchronized (mNetworkPoliciesSecondLock) {
1759 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1760 final int subId = mSubIdToSubscriberId.keyAt(i);
1761 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1762
1763 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1764 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1765 true);
1766 // Template is matched when subscriber id matches.
1767 if (template.matches(probeIdent)) {
1768 matchingSubIds.add(subId);
1769 }
Jack Yu8781b682016-07-08 14:28:51 -07001770 }
1771 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001772
1773 // Only talk with telephony outside of locks
1774 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1775 for (int i = 0; i < matchingSubIds.size(); i++) {
1776 final int subId = matchingSubIds.get(i);
1777 tm.setPolicyDataEnabled(enabled, subId);
1778 }
Jack Yu8781b682016-07-08 14:28:51 -07001779 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001780 }
1781
1782 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001783 * Collect all ifaces from a {@link NetworkState} into the given set.
1784 */
1785 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1786 final String baseIface = state.linkProperties.getInterfaceName();
1787 if (baseIface != null) {
1788 ifaces.add(baseIface);
1789 }
1790 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1791 final String stackedIface = stackedLink.getInterfaceName();
1792 if (stackedIface != null) {
1793 ifaces.add(stackedIface);
1794 }
1795 }
1796 }
1797
1798 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001799 * Examine all currently active subscriptions from
1800 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1801 * internal data structures.
1802 * <p>
1803 * Callers <em>must not</em> hold any locks when this method called.
1804 */
1805 void updateSubscriptions() {
1806 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1807 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1808
1809 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1810 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1811
1812 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001813 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001814
1815 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1816 for (int subId : subIds) {
1817 final String subscriberId = tm.getSubscriberId(subId);
1818 if (!TextUtils.isEmpty(subscriberId)) {
1819 subIdToSubscriberId.put(subId, subscriberId);
1820 } else {
1821 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1822 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001823
1824 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1825 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1826 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001827 }
1828
1829 synchronized (mNetworkPoliciesSecondLock) {
1830 mSubIdToSubscriberId.clear();
1831 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1832 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1833 subIdToSubscriberId.valueAt(i));
1834 }
1835
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001836 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001837 }
1838
1839 Trace.traceEnd(TRACE_TAG_NETWORK);
1840 }
1841
1842 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001843 * Examine all connected {@link NetworkState}, looking for
1844 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1845 * remaining quota based on usage cycle and historical stats.
1846 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001847 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001848 void updateNetworkRulesNL() {
1849 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001850 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851
1852 final NetworkState[] states;
1853 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001854 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001855 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001856 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001857 return;
1858 }
1859
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001860 // First, generate identities of all connected networks so we can
1861 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001862 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001863 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001864 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001865 if (state.network != null) {
1866 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1867 }
Wei Liub8eaf452016-01-25 10:32:27 -08001868 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001869 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1870 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001871 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001872 }
1873 }
1874
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001875 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001876 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001877
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001878 // For every well-defined policy, compute remaining data based on
1879 // current cycle and historical stats, and push to kernel.
1880 final ArraySet<String> matchingIfaces = new ArraySet<>();
1881 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1882 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1883
1884 // Collect all ifaces that match this policy
1885 matchingIfaces.clear();
1886 for (int j = identified.size() - 1; j >= 0; j--) {
1887 if (policy.template.matches(identified.valueAt(j))) {
1888 collectIfaces(matchingIfaces, identified.keyAt(j));
1889 }
1890 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001891
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001892 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001893 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001894 }
1895
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001896 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001897 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001898 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001899 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001900 if (hasLimit && policy.hasCycle()) {
1901 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1902 .cycleIterator(policy).next();
1903 final long start = cycle.first.toInstant().toEpochMilli();
1904 final long end = cycle.second.toInstant().toEpochMilli();
1905 final long totalBytes = getTotalBytes(policy.template, start, end);
1906
1907 if (policy.lastLimitSnooze >= start) {
1908 // snoozing past quota, but we still need to restrict apps,
1909 // so push really high quota.
1910 quotaBytes = Long.MAX_VALUE;
1911 } else {
1912 // remaining "quota" bytes are based on total usage in
1913 // current cycle. kernel doesn't like 0-byte rules, so we
1914 // set 1-byte quota and disable the radio later.
1915 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1916 }
1917 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001918 // metered network, but no policy limit; we still need to
1919 // restrict apps, so push really high quota.
1920 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001921 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001922
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001923 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001924 // TODO: switch to shared quota once NMS supports
1925 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001926 }
1927
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001928 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1929 final String iface = matchingIfaces.valueAt(j);
1930 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001931 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001932 }
1933 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001934
1935 // keep track of lowest warning or limit of active policies
1936 if (hasWarning && policy.warningBytes < lowestRule) {
1937 lowestRule = policy.warningBytes;
1938 }
1939 if (hasLimit && policy.limitBytes < lowestRule) {
1940 lowestRule = policy.limitBytes;
1941 }
1942 }
1943
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001944 // One final pass to catch any metered ifaces that don't have explicitly
1945 // defined policies; typically Wi-Fi networks.
1946 for (NetworkState state : states) {
1947 if (state.networkInfo != null && state.networkInfo.isConnected()
1948 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1949 matchingIfaces.clear();
1950 collectIfaces(matchingIfaces, state);
1951 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1952 final String iface = matchingIfaces.valueAt(j);
1953 if (!newMeteredIfaces.contains(iface)) {
1954 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1955 newMeteredIfaces.add(iface);
1956 }
1957 }
1958 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001959 }
1960
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001961 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001962 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1963 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001964 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001965 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001966 }
1967 }
1968 mMeteredIfaces = newMeteredIfaces;
1969
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001970 final ContentResolver cr = mContext.getContentResolver();
1971 final boolean quotaEnabled = Settings.Global.getInt(cr,
1972 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1973 final long quotaUnlimited = Settings.Global.getLong(cr,
1974 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1975 final float quotaLimited = Settings.Global.getFloat(cr,
1976 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1977
Jeff Sharkey9252b342018-01-19 07:58:35 +09001978 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001979 mSubscriptionOpportunisticQuota.clear();
1980 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001981 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001982 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001983 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001984 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001985 if (plan == null) continue;
1986
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001987 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001988 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001989 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1990 // Clamp to 0 when roaming
1991 quotaBytes = 0;
1992 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001993 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001994 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001995 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001996 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001997 } else {
1998 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001999 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
2000 final long start = cycle.getLower().toInstant().toEpochMilli();
2001 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002002 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06002003 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002004 .truncatedTo(ChronoUnit.DAYS)
2005 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09002006 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002007 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
2008 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09002009 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002010 // Number of remaining days including current day
2011 final long remainingDays =
2012 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002013
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002014 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002015 }
2016
2017 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2018 }
2019
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002020 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002021 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002022
2023 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002024
2025 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002026 }
2027
2028 /**
2029 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2030 * have at least a default mobile policy defined.
2031 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002032 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002033 private void ensureActiveMobilePolicyAL() {
2034 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002035 if (mSuppressDefaultPolicy) return;
2036
Jeff Sharkey146bb332018-04-18 15:42:57 -06002037 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2038 final int subId = mSubIdToSubscriberId.keyAt(i);
2039 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002040
Hugo Benichi446c9c92017-04-10 09:41:10 +09002041 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002042 }
2043 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002044
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002045 /**
2046 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2047 * have at least a default mobile policy defined.
2048 *
2049 * @param subId to build a default policy for
2050 * @param subscriberId that we check for an existing policy
2051 * @return true if a mobile network policy was added, or false one already existed.
2052 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002053 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002054 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002055 // Poke around to see if we already have a policy
2056 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002057 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002058 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2059 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2060 if (template.matches(probeIdent)) {
2061 if (LOGD) {
2062 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2063 + NetworkIdentity.scrubSubscriberId(subscriberId));
2064 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002065 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002066 }
2067 }
2068
Jeff Sharkey32566012014-12-02 18:30:14 -08002069 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2070 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002071 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002072 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002073 return true;
2074 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002075
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002076 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002077 final int dataWarningConfig = mContext.getResources().getInteger(
2078 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002079 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002080 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002081 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002082 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002083 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002084 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002085
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002086 private long getPlatformDefaultLimitBytes() {
2087 return LIMIT_DISABLED;
2088 }
2089
2090 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002091 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002092 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002093 final RecurrenceRule cycleRule = NetworkPolicy
2094 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002095 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002096 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2097 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2098 synchronized (mUidRulesFirstLock) {
2099 synchronized (mNetworkPoliciesSecondLock) {
2100 updateDefaultMobilePolicyAL(subId, policy);
2101 }
2102 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002103 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002104 }
2105
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002106 /**
2107 * Update the given {@link NetworkPolicy} based on any carrier-provided
2108 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2109 * Leaves policy untouched if the user has modified it.
2110 *
2111 * @return if the policy was modified
2112 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002113 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002114 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2115 if (!policy.inferred) {
2116 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2117 return false;
2118 }
2119
2120 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2121 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2122 policy.lastLimitSnooze, policy.metered, policy.inferred);
2123
2124 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2125 if (!ArrayUtils.isEmpty(plans)) {
2126 final SubscriptionPlan plan = plans[0];
2127 policy.cycleRule = plan.getCycleRule();
2128 final long planLimitBytes = plan.getDataLimitBytes();
2129 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2130 policy.warningBytes = getPlatformDefaultWarningBytes();
2131 policy.limitBytes = getPlatformDefaultLimitBytes();
2132 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2133 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2134 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2135 } else {
2136 policy.warningBytes = (planLimitBytes * 9) / 10;
2137 switch (plan.getDataLimitBehavior()) {
2138 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2139 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2140 policy.limitBytes = planLimitBytes;
2141 break;
2142 default:
2143 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2144 break;
2145 }
2146 }
2147 } else {
2148 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2149 final int currentCycleDay;
2150 if (policy.cycleRule.isMonthly()) {
2151 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2152 } else {
2153 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2154 }
2155 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2156 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2157 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2158 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2159 }
2160
2161 if (policy.equals(original)) {
2162 return false;
2163 } else {
2164 Slog.d(TAG, "Updated " + original + " to " + policy);
2165 return true;
2166 }
2167 }
2168
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002169 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002170 private void readPolicyAL() {
2171 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002172
2173 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002174 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002175 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002176 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002177 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002178
2179 FileInputStream fis = null;
2180 try {
2181 fis = mPolicyFile.openRead();
2182 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002183 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184
Felipe Leme46b451f2016-08-19 08:46:17 -07002185 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2186 // to skip UIDs that were explicitly blacklisted.
2187 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2188
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002189 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002190 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002191 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002192 while ((type = in.next()) != END_DOCUMENT) {
2193 final String tag = in.getName();
2194 if (type == START_TAG) {
2195 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002196 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002197 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002198 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2199 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002200 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2201 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2202 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002203 final String networkId;
2204 if (version >= VERSION_ADDED_NETWORK_ID) {
2205 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2206 } else {
2207 networkId = null;
2208 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002209 final RecurrenceRule cycleRule;
2210 if (version >= VERSION_ADDED_CYCLE) {
2211 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2212 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2213 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2214 cycleRule = new RecurrenceRule(
2215 RecurrenceRule.convertZonedDateTime(start),
2216 RecurrenceRule.convertZonedDateTime(end),
2217 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002218 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002219 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2220 final String cycleTimezone;
2221 if (version >= VERSION_ADDED_TIMEZONE) {
2222 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2223 } else {
2224 cycleTimezone = "UTC";
2225 }
2226 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002227 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002228 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2229 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002230 final long lastLimitSnooze;
2231 if (version >= VERSION_SPLIT_SNOOZE) {
2232 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2233 } else if (version >= VERSION_ADDED_SNOOZE) {
2234 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002235 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002236 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002237 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002238 final boolean metered;
2239 if (version >= VERSION_ADDED_METERED) {
2240 metered = readBooleanAttribute(in, ATTR_METERED);
2241 } else {
2242 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002243 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002244 metered = true;
2245 break;
2246 default:
2247 metered = false;
2248 }
2249 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002250 final long lastWarningSnooze;
2251 if (version >= VERSION_SPLIT_SNOOZE) {
2252 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2253 } else {
2254 lastWarningSnooze = SNOOZE_NEVER;
2255 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002256 final boolean inferred;
2257 if (version >= VERSION_ADDED_INFERRED) {
2258 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2259 } else {
2260 inferred = false;
2261 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002262
Jeff Sharkey32566012014-12-02 18:30:14 -08002263 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2264 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002265 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002266 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2267 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002268 lastLimitSnooze, metered, inferred));
2269 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002270
2271 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2272 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2273 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2274 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2275 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2276 RecurrenceRule.convertZonedDateTime(start),
2277 RecurrenceRule.convertZonedDateTime(end),
2278 RecurrenceRule.convertPeriod(period));
2279 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2280 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2281
2282 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2283 SubscriptionPlan.BYTES_UNKNOWN);
2284 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2285 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2286 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2287 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2288 builder.setDataLimit(limitBytes, limitBehavior);
2289 }
2290
2291 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2292 SubscriptionPlan.BYTES_UNKNOWN);
2293 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2294 SubscriptionPlan.TIME_UNKNOWN);
2295 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2296 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2297 builder.setDataUsage(usageBytes, usageTime);
2298 }
2299
2300 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2301 final SubscriptionPlan plan = builder.build();
2302 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2303 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2304
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002305 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2306 mSubscriptionPlansOwner.put(subId, ownerPackage);
2307
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002308 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002309 final int uid = readIntAttribute(in, ATTR_UID);
2310 final int policy = readIntAttribute(in, ATTR_POLICY);
2311
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002312 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002313 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002314 } else {
2315 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2316 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002318 final int appId = readIntAttribute(in, ATTR_APP_ID);
2319 final int policy = readIntAttribute(in, ATTR_POLICY);
2320
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002321 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002322 // app policy is deprecated so this is only used in pre system user split.
2323 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002324 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002325 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002326 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002327 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002328 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002329 } else if (TAG_WHITELIST.equals(tag)) {
2330 insideWhitelist = true;
2331 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2332 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002333 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002334 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2335 final int uid = readIntAttribute(in, ATTR_UID);
2336 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002337 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002338 } else if (type == END_TAG) {
2339 if (TAG_WHITELIST.equals(tag)) {
2340 insideWhitelist = false;
2341 }
2342
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002343 }
2344 }
2345
Felipe Leme46b451f2016-08-19 08:46:17 -07002346 final int size = whitelistedRestrictBackground.size();
2347 for (int i = 0; i < size; i++) {
2348 final int uid = whitelistedRestrictBackground.keyAt(i);
2349 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2350 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2351 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2352 + " because its policy is " + uidPoliciesToString(policy));
2353 continue;
2354 }
2355 if (UserHandle.isApp(uid)) {
2356 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2357 if (LOGV)
2358 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2359 setUidPolicyUncheckedUL(uid, newPolicy, false);
2360 } else {
2361 Slog.w(TAG, "unable to update policy on UID " + uid);
2362 }
2363 }
2364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 } catch (FileNotFoundException e) {
2366 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002367 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002368 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002369 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002370 } finally {
2371 IoUtils.closeQuietly(fis);
2372 }
2373 }
2374
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002375 /**
2376 * Upgrade legacy background data flags, notifying listeners of one last
2377 * change to always-true.
2378 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002379 private void upgradeDefaultBackgroundDataUL() {
2380 // This method is only called when we're unable to find the network policy flag, which
2381 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002382
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002383 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002384 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002385 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2386
2387 // NOTE: We used to read the legacy setting here :
2388 //
2389 // final int legacyFlagValue = Settings.Secure.getInt(
2390 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2391 //
2392 // This is no longer necessary because we will never upgrade directly from Gingerbread
2393 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2394 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002395 }
2396
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002397 /**
2398 * Perform upgrade step of moving any user-defined meterness overrides over
2399 * into {@link WifiConfiguration}.
2400 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002401 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002402 private void upgradeWifiMeteredOverrideAL() {
2403 boolean modified = false;
2404 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2405 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2406 for (int i = 0; i < mNetworkPolicy.size(); ) {
2407 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2408 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2409 && !policy.inferred) {
2410 mNetworkPolicy.removeAt(i);
2411 modified = true;
2412
2413 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2414 for (WifiConfiguration config : configs) {
2415 if (Objects.equals(resolveNetworkId(config), networkId)) {
2416 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2417 config.meteredOverride = policy.metered
2418 ? WifiConfiguration.METERED_OVERRIDE_METERED
2419 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2420 wm.updateNetwork(config);
2421 }
2422 }
2423 } else {
2424 i++;
2425 }
2426 }
2427 if (modified) {
2428 writePolicyAL();
2429 }
2430 }
2431
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002432 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002433 void writePolicyAL() {
2434 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002435
2436 FileOutputStream fos = null;
2437 try {
2438 fos = mPolicyFile.startWrite();
2439
2440 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002441 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002442 out.startDocument(null, true);
2443
2444 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002445 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002446 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002447
2448 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002449 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2450 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002451 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002452 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002453
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002454 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002455 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2456 final String subscriberId = template.getSubscriberId();
2457 if (subscriberId != null) {
2458 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002459 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002460 final String networkId = template.getNetworkId();
2461 if (networkId != null) {
2462 out.attribute(null, ATTR_NETWORK_ID, networkId);
2463 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002464 writeStringAttribute(out, ATTR_CYCLE_START,
2465 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2466 writeStringAttribute(out, ATTR_CYCLE_END,
2467 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2468 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2469 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002470 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2471 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002472 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2473 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002474 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002475 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002476 out.endTag(null, TAG_NETWORK_POLICY);
2477 }
2478
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002479 // write all known subscription plans
2480 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2481 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002482 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002483 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2484 if (ArrayUtils.isEmpty(plans)) continue;
2485
2486 for (SubscriptionPlan plan : plans) {
2487 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2488 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002489 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002490 final RecurrenceRule cycleRule = plan.getCycleRule();
2491 writeStringAttribute(out, ATTR_CYCLE_START,
2492 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2493 writeStringAttribute(out, ATTR_CYCLE_END,
2494 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2495 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2496 RecurrenceRule.convertPeriod(cycleRule.period));
2497 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2498 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2499 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2500 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2501 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2502 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2503 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2504 }
2505 }
2506
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002508 for (int i = 0; i < mUidPolicy.size(); i++) {
2509 final int uid = mUidPolicy.keyAt(i);
2510 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002511
Jeff Sharkey497e4432011-06-14 17:27:29 -07002512 // skip writing empty policies
2513 if (policy == POLICY_NONE) continue;
2514
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002515 out.startTag(null, TAG_UID_POLICY);
2516 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002517 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002518 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002519 }
2520
2521 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002522
2523 // write all whitelists
2524 out.startTag(null, TAG_WHITELIST);
2525
Felipe Lemea9505cc2016-02-26 10:28:41 -08002526 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002527 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002528 for (int i = 0; i < size; i++) {
2529 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2530 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2531 writeIntAttribute(out, ATTR_UID, uid);
2532 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2533 }
2534
Felipe Lemeb85a6372016-01-14 16:16:16 -08002535 out.endTag(null, TAG_WHITELIST);
2536
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002537 out.endDocument();
2538
2539 mPolicyFile.finishWrite(fos);
2540 } catch (IOException e) {
2541 if (fos != null) {
2542 mPolicyFile.failWrite(fos);
2543 }
2544 }
2545 }
2546
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002547 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002548 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002550
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002551 if (!UserHandle.isApp(uid)) {
2552 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002553 }
Felipe Lemef0823852016-06-08 13:43:08 -07002554 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002555 final long token = Binder.clearCallingIdentity();
2556 try {
2557 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2558 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002559 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002560 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002561 }
2562 } finally {
2563 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002564 }
2565 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002566 }
2567
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002568 @Override
2569 public void addUidPolicy(int uid, int policy) {
2570 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002571
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002572 if (!UserHandle.isApp(uid)) {
2573 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2574 }
2575
Felipe Lemef0823852016-06-08 13:43:08 -07002576 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002577 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2578 policy |= oldPolicy;
2579 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002580 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002581 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002582 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002583 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002584 }
2585
2586 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002587 public void removeUidPolicy(int uid, int policy) {
2588 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2589
2590 if (!UserHandle.isApp(uid)) {
2591 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2592 }
2593
Felipe Lemef0823852016-06-08 13:43:08 -07002594 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002595 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2596 policy = oldPolicy & ~policy;
2597 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002598 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002599 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002600 }
2601 }
2602 }
2603
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002604 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002605 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002606 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002607
Felipe Leme57e3d312016-08-23 14:42:52 -07002608 final boolean notifyApp;
2609 if (!isUidValidForWhitelistRules(uid)) {
2610 notifyApp = false;
2611 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002612 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2613 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2614 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2615 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002616 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2617 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002618 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2619 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2620 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2621 if (LOGD)
2622 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2623 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2624 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002625 notifyApp = wasBlocked != isBlocked;
2626 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002627 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2628 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002629 if (persist) {
2630 synchronized (mNetworkPoliciesSecondLock) {
2631 writePolicyAL();
2632 }
2633 }
Felipe Leme923845f2016-03-02 13:42:48 -08002634 }
2635
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002636 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002637 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002638 if (policy == POLICY_NONE) {
2639 mUidPolicy.delete(uid);
2640 } else {
2641 mUidPolicy.put(uid, policy);
2642 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002643
2644 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002645 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002646 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002647 synchronized (mNetworkPoliciesSecondLock) {
2648 writePolicyAL();
2649 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002650 }
2651 }
2652
2653 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002654 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002655 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2656
Felipe Lemef0823852016-06-08 13:43:08 -07002657 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002658 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002659 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002660 }
2661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002662 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002663 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002664 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2665
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002666 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002667 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002668 for (int i = 0; i < mUidPolicy.size(); i++) {
2669 final int uid = mUidPolicy.keyAt(i);
2670 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002671 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2672 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002673 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002674 }
2675 }
2676 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002677 return uids;
2678 }
2679
2680 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002681 * Removes any persistable state associated with given {@link UserHandle}, persisting
2682 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002683 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002684 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002685 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002686
Sudheer Shanka352dc572017-09-22 17:09:38 -07002687 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002688 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002689
Felipe Lemea110eec2016-04-29 09:58:06 -07002690 // Remove entries from revoked default restricted background UID whitelist
2691 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2692 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2693 if (UserHandle.getUserId(uid) == userId) {
2694 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002695 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002696 }
2697 }
2698
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002699 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002700 int[] uids = new int[0];
2701 for (int i = 0; i < mUidPolicy.size(); i++) {
2702 final int uid = mUidPolicy.keyAt(i);
2703 if (UserHandle.getUserId(uid) == userId) {
2704 uids = appendInt(uids, uid);
2705 }
2706 }
2707
2708 if (uids.length > 0) {
2709 for (int uid : uids) {
2710 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002711 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002712 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002713 }
Felipe Lemef0823852016-06-08 13:43:08 -07002714 synchronized (mNetworkPoliciesSecondLock) {
2715 updateRulesForGlobalChangeAL(true);
2716 if (writePolicy && changed) {
2717 writePolicyAL();
2718 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002719 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002720 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002721 }
2722
2723 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002724 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002725 // TODO: create permission for observing network policy
2726 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002727 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002728 }
2729
2730 @Override
2731 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002732 // TODO: create permission for observing network policy
2733 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002734 mListeners.unregister(listener);
2735 }
2736
Jeff Sharkey1b861272011-05-22 00:34:52 -07002737 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002738 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002739 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2740
Felipe Leme6a05eee2016-02-19 14:43:51 -08002741 final long token = Binder.clearCallingIdentity();
2742 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002743 synchronized (mUidRulesFirstLock) {
2744 synchronized (mNetworkPoliciesSecondLock) {
2745 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002746 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002747 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002748 }
2749 } finally {
2750 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002751 }
2752 }
2753
Hugo Benichi446c9c92017-04-10 09:41:10 +09002754 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002755 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002756 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2757 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002758 }
2759
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002760 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002761 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002762 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002763 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002764 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2765 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2766 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002767 } catch (SecurityException e) {
2768 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002769
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002770 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2771 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2772 return new NetworkPolicy[0];
2773 }
Svet Ganov16a16892015-04-16 10:32:04 -07002774 }
2775
Felipe Lemef0823852016-06-08 13:43:08 -07002776 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002777 final int size = mNetworkPolicy.size();
2778 final NetworkPolicy[] policies = new NetworkPolicy[size];
2779 for (int i = 0; i < size; i++) {
2780 policies[i] = mNetworkPolicy.valueAt(i);
2781 }
2782 return policies;
2783 }
2784 }
2785
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002786 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002787 private void normalizePoliciesNL() {
2788 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002789 }
2790
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002791 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002792 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002793 mNetworkPolicy.clear();
2794 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002795 if (policy == null) {
2796 continue;
2797 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002798 // When two normalized templates conflict, prefer the most
2799 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002800 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002801 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2802 if (existing == null || existing.compareTo(policy) > 0) {
2803 if (existing != null) {
2804 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2805 }
2806 mNetworkPolicy.put(policy.template, policy);
2807 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002808 }
2809 }
2810
2811 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002812 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002813 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002814
2815 final long token = Binder.clearCallingIdentity();
2816 try {
2817 performSnooze(template, TYPE_LIMIT);
2818 } finally {
2819 Binder.restoreCallingIdentity(token);
2820 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002821 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002822
Dianne Hackborn497175b2014-07-01 12:56:08 -07002823 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002824 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002825 synchronized (mUidRulesFirstLock) {
2826 synchronized (mNetworkPoliciesSecondLock) {
2827 // find and snooze local policy that matches
2828 final NetworkPolicy policy = mNetworkPolicy.get(template);
2829 if (policy == null) {
2830 throw new IllegalArgumentException("unable to find policy for " + template);
2831 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002832
Felipe Lemef0823852016-06-08 13:43:08 -07002833 switch (type) {
2834 case TYPE_WARNING:
2835 policy.lastWarningSnooze = currentTime;
2836 break;
2837 case TYPE_LIMIT:
2838 policy.lastLimitSnooze = currentTime;
2839 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002840 case TYPE_RAPID:
2841 policy.lastRapidSnooze = currentTime;
2842 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002843 default:
2844 throw new IllegalArgumentException("unexpected type");
2845 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002846
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002847 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002848 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002849 }
2850 }
2851
2852 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002853 public void onTetheringChanged(String iface, boolean tethering) {
2854 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002855 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002856 if (mRestrictBackground && tethering) {
2857 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2858 setRestrictBackground(false);
2859 }
2860 }
2861 }
2862
2863 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002864 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002865 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002866 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002867 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2868 final long token = Binder.clearCallingIdentity();
2869 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002870 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002871 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002872 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002873 } finally {
2874 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002875 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002876 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002877 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002878 }
2879 }
2880
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002881 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002882 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002883 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002884 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002885 if (restrictBackground == mRestrictBackground) {
2886 // Ideally, UI should never allow this scenario...
2887 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002888 return;
2889 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002890 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2891 final boolean oldRestrictBackground = mRestrictBackground;
2892 mRestrictBackground = restrictBackground;
2893 // Must whitelist foreground apps before turning data saver mode on.
2894 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2895 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2896 updateRulesForRestrictBackgroundUL();
2897 try {
2898 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2899 Slog.e(TAG,
2900 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2901 mRestrictBackground = oldRestrictBackground;
2902 // TODO: if it knew the foreground apps (see TODO above), it could call
2903 // updateRulesForRestrictBackgroundUL() again to restore state.
2904 return;
2905 }
2906 } catch (RemoteException e) {
2907 // ignored; service lives in system_server
2908 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002909
Sudheer Shanka543339f2017-07-28 15:18:07 -07002910 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002911 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002912
Kweku Adams25fa3a72019-07-12 17:00:17 -07002913 if (mRestrictBackgroundLowPowerMode) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002914 mRestrictBackgroundChangedInBsm = true;
2915 }
2916 synchronized (mNetworkPoliciesSecondLock) {
2917 updateNotificationsNL();
2918 writePolicyAL();
2919 }
2920 } finally {
2921 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002922 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002923 }
2924
2925 private void sendRestrictBackgroundChangedMsg() {
2926 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2927 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2928 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002929 }
2930
Felipe Lemeb85a6372016-01-14 16:16:16 -08002931 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002932 public int getRestrictBackgroundByCaller() {
2933 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2934 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002935
Felipe Lemef0823852016-06-08 13:43:08 -07002936 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002937 // Must clear identity because getUidPolicy() is restricted to system.
2938 final long token = Binder.clearCallingIdentity();
2939 final int policy;
2940 try {
2941 policy = getUidPolicy(uid);
2942 } finally {
2943 Binder.restoreCallingIdentity(token);
2944 }
2945 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2946 // App is blacklisted.
2947 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2948 }
Felipe Leme1b103232016-01-22 09:44:57 -08002949 if (!mRestrictBackground) {
2950 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2951 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002952 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002953 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2954 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2955 }
2956 }
2957
2958 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002959 public boolean getRestrictBackground() {
2960 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2961
Felipe Lemef0823852016-06-08 13:43:08 -07002962 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002963 return mRestrictBackground;
2964 }
2965 }
2966
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002967 @Override
2968 public void setDeviceIdleMode(boolean enabled) {
2969 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002970 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2971 try {
2972 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002973 if (mDeviceIdleMode == enabled) {
2974 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002975 }
Felipe Lemeea014392016-09-06 13:59:54 -07002976 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002977 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002978 if (mSystemReady) {
2979 // Device idle change means we need to rebuild rules for all
2980 // known apps, so do a global refresh.
2981 updateRulesForRestrictPowerUL();
2982 }
2983 }
2984 if (enabled) {
2985 EventLogTags.writeDeviceIdleOnPhase("net");
2986 } else {
2987 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002988 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002989 } finally {
2990 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002991 }
2992 }
2993
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002994 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002995 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2996 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002997 final long token = Binder.clearCallingIdentity();
2998 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002999 final WifiManager wm = mContext.getSystemService(WifiManager.class);
3000 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
3001 for (WifiConfiguration config : configs) {
3002 if (Objects.equals(resolveNetworkId(config), networkId)) {
3003 config.meteredOverride = meteredOverride;
3004 wm.updateNetwork(config);
3005 }
3006 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003007 } finally {
3008 Binder.restoreCallingIdentity(token);
3009 }
3010 }
3011
Jeff Sharkey46645002011-07-27 21:11:21 -07003012 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003013 @Deprecated
3014 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3015 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3016 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3017 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003018 }
3019
Jeff Sharkey53313d72017-07-13 16:47:32 -06003020 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3021 // Verify they're not lying about package name
3022 mAppOps.checkPackage(callingUid, callingPackage);
3023
Jeff Sharkey53313d72017-07-13 16:47:32 -06003024 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003025 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003026 final long token = Binder.clearCallingIdentity();
3027 try {
3028 si = mContext.getSystemService(SubscriptionManager.class)
3029 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003030 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003031 } finally {
3032 Binder.restoreCallingIdentity(token);
3033 }
3034
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003035 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003036 if (si != null) {
3037 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3038 return;
3039 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003040 }
3041
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003042 // Second check: has the CarrierService delegated access?
3043 if (config != null) {
3044 final String overridePackage = config
3045 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3046 if (!TextUtils.isEmpty(overridePackage)
3047 && Objects.equals(overridePackage, callingPackage)) {
3048 return;
3049 }
3050 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003051
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003052 // Third check: is caller the fallback/default CarrierService?
3053 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3054 if (!TextUtils.isEmpty(defaultPackage)
3055 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003056 return;
3057 }
3058
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003059 // Fourth check: is caller a testing app?
3060 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3061 if (!TextUtils.isEmpty(testPackage)
3062 && Objects.equals(testPackage, callingPackage)) {
3063 return;
3064 }
3065
3066 // Fifth check: is caller a legacy testing app?
3067 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3068 if (!TextUtils.isEmpty(legacyTestPackage)
3069 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003070 return;
3071 }
3072
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003073 // Final check: does the caller hold a permission?
3074 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003075 }
3076
Sarah Chin7af1fd02019-09-26 11:37:13 -07003077 private void enforceSubscriptionPlanValidity(SubscriptionPlan[] plans) {
3078 // nothing to check if no plans
3079 if (plans.length == 0) {
3080 return;
3081 }
3082
3083 long applicableNetworkTypes = 0;
3084 boolean allNetworks = false;
3085 for (SubscriptionPlan plan : plans) {
3086 if (plan.getNetworkTypes() == null) {
3087 allNetworks = true;
3088 } else {
3089 if ((applicableNetworkTypes & plan.getNetworkTypesBitMask()) != 0) {
3090 throw new IllegalArgumentException(
3091 "Multiple subscription plans defined for a single network type.");
3092 } else {
3093 applicableNetworkTypes |= plan.getNetworkTypesBitMask();
3094 }
3095 }
3096 }
3097
3098 // ensure at least one plan applies for every network type
3099 if (!allNetworks) {
3100 throw new IllegalArgumentException(
3101 "No generic subscription plan that applies to all network types.");
3102 }
3103 }
3104
Jeff Sharkey53313d72017-07-13 16:47:32 -06003105 @Override
3106 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3107 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3108
Jeff Sharkey53313d72017-07-13 16:47:32 -06003109 final String fake = SystemProperties.get("fw.fake_plan");
3110 if (!TextUtils.isEmpty(fake)) {
3111 final List<SubscriptionPlan> plans = new ArrayList<>();
3112 if ("month_hard".equals(fake)) {
3113 plans.add(SubscriptionPlan.Builder
3114 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3115 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003116 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3117 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3118 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3119 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3120 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003121 plans.add(SubscriptionPlan.Builder
3122 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3123 .setTitle("G-Mobile Happy")
3124 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3125 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3126 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3127 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3128 .build());
3129 plans.add(SubscriptionPlan.Builder
3130 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3131 .setTitle("G-Mobile, Charged after limit")
3132 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3133 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3134 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3135 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3136 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003137 } else if ("month_soft".equals(fake)) {
3138 plans.add(SubscriptionPlan.Builder
3139 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3140 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3141 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3142 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003143 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3144 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3145 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3146 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3147 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003148 plans.add(SubscriptionPlan.Builder
3149 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3150 .setTitle("G-Mobile, Throttled after limit")
3151 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3152 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3153 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3154 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3155 .build());
3156 plans.add(SubscriptionPlan.Builder
3157 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3158 .setTitle("G-Mobile, No data connection after limit")
3159 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3160 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3161 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3162 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3163 .build());
3164
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003165 } else if ("month_over".equals(fake)) {
3166 plans.add(SubscriptionPlan.Builder
3167 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3168 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3169 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3170 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3171 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3172 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3173 .build());
3174 plans.add(SubscriptionPlan.Builder
3175 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3176 .setTitle("G-Mobile, Throttled after limit")
3177 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3178 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3179 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3180 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3181 .build());
3182 plans.add(SubscriptionPlan.Builder
3183 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3184 .setTitle("G-Mobile, No data connection after limit")
3185 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3186 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3187 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3188 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3189 .build());
3190
Jeff Sharkey53313d72017-07-13 16:47:32 -06003191 } else if ("month_none".equals(fake)) {
3192 plans.add(SubscriptionPlan.Builder
3193 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3194 .setTitle("G-Mobile")
3195 .build());
3196 } else if ("prepaid".equals(fake)) {
3197 plans.add(SubscriptionPlan.Builder
3198 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3199 ZonedDateTime.now().plusDays(10))
3200 .setTitle("G-Mobile")
3201 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3202 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3203 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3204 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3205 .build());
3206 } else if ("prepaid_crazy".equals(fake)) {
3207 plans.add(SubscriptionPlan.Builder
3208 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3209 ZonedDateTime.now().plusDays(10))
3210 .setTitle("G-Mobile Anytime")
3211 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3212 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3213 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3214 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3215 .build());
3216 plans.add(SubscriptionPlan.Builder
3217 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3218 ZonedDateTime.now().plusDays(20))
3219 .setTitle("G-Mobile Nickel Nights")
3220 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003221 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3222 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003223 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3224 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3225 .build());
3226 plans.add(SubscriptionPlan.Builder
3227 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3228 ZonedDateTime.now().plusDays(20))
3229 .setTitle("G-Mobile Bonus 3G")
3230 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003231 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003232 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3233 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3234 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3235 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003236 } else if ("unlimited".equals(fake)) {
3237 plans.add(SubscriptionPlan.Builder
3238 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3239 ZonedDateTime.now().plusDays(10))
3240 .setTitle("G-Mobile Awesome")
3241 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3242 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3243 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3244 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3245 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003246 }
3247 return plans.toArray(new SubscriptionPlan[plans.size()]);
3248 }
3249
Jeff Sharkey4635f102017-09-01 11:27:13 -06003250 synchronized (mNetworkPoliciesSecondLock) {
3251 // Only give out plan details to the package that defined them,
3252 // so that we don't risk leaking plans between apps. We always
3253 // let in core system components (like the Settings app).
3254 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3255 if (Objects.equals(ownerPackage, callingPackage)
3256 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3257 return mSubscriptionPlans.get(subId);
3258 } else {
3259 Log.w(TAG, "Not returning plans because caller " + callingPackage
3260 + " doesn't match owner " + ownerPackage);
3261 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003262 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003263 }
3264 }
3265
3266 @Override
3267 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3268 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003269 enforceSubscriptionPlanValidity(plans);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003270
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003271 for (SubscriptionPlan plan : plans) {
3272 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003273 }
3274
3275 final long token = Binder.clearCallingIdentity();
3276 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003277 synchronized (mUidRulesFirstLock) {
3278 synchronized (mNetworkPoliciesSecondLock) {
3279 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003280 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003281
Jeff Sharkey146bb332018-04-18 15:42:57 -06003282 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3283 if (subscriberId != null) {
3284 ensureActiveMobilePolicyAL(subId, subscriberId);
3285 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3286 } else {
3287 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3288 }
3289
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003290 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003291 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003292 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003293
3294 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3296 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3297 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Sarah Chin7af1fd02019-09-26 11:37:13 -07003298 mHandler.sendMessage(
3299 mHandler.obtainMessage(MSG_SUBSCRIPTION_PLANS_CHANGED, subId, 0, plans));
Jeff Sharkey53313d72017-07-13 16:47:32 -06003300 } finally {
3301 Binder.restoreCallingIdentity(token);
3302 }
3303 }
3304
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003305 /**
3306 * Only visible for testing purposes. This doesn't give any access to
3307 * existing plans; it simply lets the debug package define new plans.
3308 */
3309 void setSubscriptionPlansOwner(int subId, String packageName) {
3310 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3311 }
3312
Jeff Sharkey53313d72017-07-13 16:47:32 -06003313 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003314 public String getSubscriptionPlansOwner(int subId) {
3315 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3316 throw new SecurityException();
3317 }
3318
3319 synchronized (mNetworkPoliciesSecondLock) {
3320 return mSubscriptionPlansOwner.get(subId);
3321 }
3322 }
3323
3324 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003325 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
Sarah Chin7af1fd02019-09-26 11:37:13 -07003326 long timeoutMillis, String callingPackage) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003327 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3328
3329 // We can only override when carrier told us about plans
3330 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003331 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3332 if (plan == null
3333 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003334 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003335 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003336 }
3337 }
3338
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003339 // Only allow overrides when feature is enabled. However, we always
3340 // allow disabling of overrides for safety reasons.
3341 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3342 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3343 if (overrideEnabled || overrideValue == 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003344 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3345 overrideMask, overrideValue, subId));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003346 if (timeoutMillis > 0) {
Sarah Chin7af1fd02019-09-26 11:37:13 -07003347 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3348 overrideMask, 0, subId), timeoutMillis);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003349 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003350 }
3351 }
3352
3353 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003354 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003355 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003356
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003357 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3358
Dianne Hackborn497175b2014-07-01 12:56:08 -07003359 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003360 for (String arg : args) {
3361 argSet.add(arg);
3362 }
3363
Felipe Lemef0823852016-06-08 13:43:08 -07003364 synchronized (mUidRulesFirstLock) {
3365 synchronized (mNetworkPoliciesSecondLock) {
3366 if (argSet.contains("--unsnooze")) {
3367 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3368 mNetworkPolicy.valueAt(i).clearSnooze();
3369 }
3370
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003371 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003372
3373 fout.println("Cleared snooze timestamps");
3374 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003375 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003376
Felipe Lemef0823852016-06-08 13:43:08 -07003377 fout.print("System ready: "); fout.println(mSystemReady);
3378 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3379 fout.print("Restrict power: "); fout.println(mRestrictPower);
3380 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003381 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3382
3383 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003384 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003385 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003386 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3387 fout.println(mNetworkPolicy.valueAt(i).toString());
3388 }
3389 fout.decreaseIndent();
3390
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003391 fout.println();
3392 fout.println("Subscription plans:");
3393 fout.increaseIndent();
3394 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3395 final int subId = mSubscriptionPlans.keyAt(i);
3396 fout.println("Subscriber ID " + subId + ":");
3397 fout.increaseIndent();
3398 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3399 if (!ArrayUtils.isEmpty(plans)) {
3400 for (SubscriptionPlan plan : plans) {
3401 fout.println(plan);
3402 }
3403 }
3404 fout.decreaseIndent();
3405 }
3406 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003407
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003408 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003409 fout.println("Active subscriptions:");
3410 fout.increaseIndent();
3411 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3412 final int subId = mSubIdToSubscriberId.keyAt(i);
3413 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3414
3415 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3416 }
3417 fout.decreaseIndent();
3418
3419 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003420 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3421 fout.println("Merged subscriptions: " + Arrays.toString(
3422 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3423 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003424
3425 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003426 fout.println("Policy for UIDs:");
3427 fout.increaseIndent();
3428 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003429 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003430 final int uid = mUidPolicy.keyAt(i);
3431 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003432 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003433 fout.print(uid);
3434 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003435 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003436 fout.println();
3437 }
3438 fout.decreaseIndent();
3439
3440 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3441 if (size > 0) {
3442 fout.println("Power save whitelist (except idle) app ids:");
3443 fout.increaseIndent();
3444 for (int i = 0; i < size; i++) {
3445 fout.print("UID=");
3446 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3447 fout.print(": ");
3448 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3449 fout.println();
3450 }
3451 fout.decreaseIndent();
3452 }
3453
3454 size = mPowerSaveWhitelistAppIds.size();
3455 if (size > 0) {
3456 fout.println("Power save whitelist app ids:");
3457 fout.increaseIndent();
3458 for (int i = 0; i < size; i++) {
3459 fout.print("UID=");
3460 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3461 fout.print(": ");
3462 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3463 fout.println();
3464 }
3465 fout.decreaseIndent();
3466 }
3467
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003468 size = mAppIdleTempWhitelistAppIds.size();
3469 if (size > 0) {
3470 fout.println("App idle whitelist app ids:");
3471 fout.increaseIndent();
3472 for (int i = 0; i < size; i++) {
3473 fout.print("UID=");
3474 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3475 fout.print(": ");
3476 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3477 fout.println();
3478 }
3479 fout.decreaseIndent();
3480 }
3481
Felipe Lemef0823852016-06-08 13:43:08 -07003482 size = mDefaultRestrictBackgroundWhitelistUids.size();
3483 if (size > 0) {
3484 fout.println("Default restrict background whitelist uids:");
3485 fout.increaseIndent();
3486 for (int i = 0; i < size; i++) {
3487 fout.print("UID=");
3488 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3489 fout.println();
3490 }
3491 fout.decreaseIndent();
3492 }
3493
3494 size = mRestrictBackgroundWhitelistRevokedUids.size();
3495 if (size > 0) {
3496 fout.println("Default restrict background whitelist uids revoked by users:");
3497 fout.increaseIndent();
3498 for (int i = 0; i < size; i++) {
3499 fout.print("UID=");
3500 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3501 fout.println();
3502 }
3503 fout.decreaseIndent();
3504 }
3505
3506 final SparseBooleanArray knownUids = new SparseBooleanArray();
3507 collectKeys(mUidState, knownUids);
3508 collectKeys(mUidRules, knownUids);
3509
3510 fout.println("Status for all known UIDs:");
3511 fout.increaseIndent();
3512 size = knownUids.size();
3513 for (int i = 0; i < size; i++) {
3514 final int uid = knownUids.keyAt(i);
3515 fout.print("UID=");
3516 fout.print(uid);
3517
3518 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3519 fout.print(" state=");
3520 fout.print(state);
3521 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3522 fout.print(" (fg)");
3523 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003524 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003525 ? " (fg svc)" : " (bg)");
3526 }
3527
3528 final int uidRules = mUidRules.get(uid, RULE_NONE);
3529 fout.print(" rules=");
3530 fout.print(uidRulesToString(uidRules));
3531 fout.println();
3532 }
3533 fout.decreaseIndent();
3534
3535 fout.println("Status for just UIDs with rules:");
3536 fout.increaseIndent();
3537 size = mUidRules.size();
3538 for (int i = 0; i < size; i++) {
3539 final int uid = mUidRules.keyAt(i);
3540 fout.print("UID=");
3541 fout.print(uid);
3542 final int uidRules = mUidRules.get(uid, RULE_NONE);
3543 fout.print(" rules=");
3544 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003545 fout.println();
3546 }
3547 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003548
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003549 fout.println("Admin restricted uids for metered data:");
3550 fout.increaseIndent();
3551 size = mMeteredRestrictedUids.size();
3552 for (int i = 0; i < size; ++i) {
3553 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3554 fout.println(mMeteredRestrictedUids.valueAt(i));
3555 }
3556 fout.decreaseIndent();
3557
Makoto Onuki49392d32018-04-11 13:51:02 -07003558 fout.println();
3559 mStatLogger.dump(fout);
3560
Sudheer Shanka352dc572017-09-22 17:09:38 -07003561 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003562 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003563 }
3564 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003565
3566 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003567 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003568 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003569 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003570 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003571 }
3572
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003573 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003574 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003575 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003576 return isUidStateForeground(
3577 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003578 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003579 }
3580
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003581 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003582 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003583 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003584 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003585 }
3586
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003587 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003588 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003589 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3590 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3591 }
3592
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003593 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003594 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003595 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003596 }
3597
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003598 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003599 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003600 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003601 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003602 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003603 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003604 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003605 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3606 try {
3607 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3608 if (oldUidState != uidState) {
3609 // state changed, push updated rules
3610 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003611 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3612 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3613 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003614 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003615 if (mDeviceIdleMode) {
3616 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003617 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003618 if (mRestrictPower) {
3619 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003620 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003621 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003622 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003623 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003624 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003625 } finally {
3626 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003627 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003628 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003629 }
3630
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003631 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003632 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003633 final int index = mUidState.indexOfKey(uid);
3634 if (index >= 0) {
3635 final int oldUidState = mUidState.valueAt(index);
3636 mUidState.removeAt(index);
3637 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003638 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003639 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003640 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003641 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003642 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003643 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003644 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003645 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003646 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003647 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003648 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003649 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003650 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003651 }
3652
Felipe Lemef28983d2016-03-25 12:18:23 -07003653 // adjust stats accounting based on foreground status
3654 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003655 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3656 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3657 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3658 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003659 try {
3660 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003661 } finally {
3662 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003663 }
3664 }
3665
Sudheer Shankac9d94072017-02-22 22:13:55 +00003666 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3667 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003668 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003669 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003670 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003671 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003672 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003673 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003674 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003675 }
3676
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003677 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003678 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003679 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3680 try {
3681 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3682 mUidFirewallPowerSaveRules);
3683 } finally {
3684 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3685 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003686 }
3687
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003688 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003689 void updateRuleForRestrictPowerUL(int uid) {
3690 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003691 }
3692
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003693 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003694 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003695 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3696 try {
3697 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3698 mUidFirewallDozableRules);
3699 } finally {
3700 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3701 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003702 }
3703
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003704 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003705 void updateRuleForDeviceIdleUL(int uid) {
3706 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003707 }
3708
Felipe Lemef28983d2016-03-25 12:18:23 -07003709 // NOTE: since both fw_dozable and fw_powersave uses the same map
3710 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003711 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003712 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003713 SparseIntArray rules) {
3714 if (enabled) {
3715 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003716 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003717 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003718 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003719 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003720 for (int ui = users.size() - 1; ui >= 0; ui--) {
3721 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003722 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3723 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3724 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3725 updateRulesForWhitelistedAppIds(uidRules,
3726 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003727 }
3728 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003729 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003730 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003731 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3732 }
3733 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003734 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003735 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003736 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003737 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003738 }
3739
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003740 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3741 final SparseBooleanArray whitelistedAppIds, int userId) {
3742 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3743 if (whitelistedAppIds.valueAt(i)) {
3744 final int appId = whitelistedAppIds.keyAt(i);
3745 final int uid = UserHandle.getUid(userId, appId);
3746 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3747 }
3748 }
3749 }
3750
3751 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003752 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3753 * mode, and app idle).
3754 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003755 * @param deviceIdleMode if true then we don't consider
3756 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3757 * whitelisted.
3758 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003759 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003760 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003761 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003762 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3763 || mPowerSaveWhitelistAppIds.get(appId);
3764 if (!deviceIdleMode) {
3765 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3766 }
3767 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003768 }
3769
Felipe Lemef28983d2016-03-25 12:18:23 -07003770 // NOTE: since both fw_dozable and fw_powersave uses the same map
3771 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003772 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003773 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003774 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003775 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003776 chain == FIREWALL_CHAIN_DOZABLE);
3777 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003778 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003779 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003780 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003781 }
3782 }
3783 }
3784
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003785 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003786 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003787 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3788 try {
3789 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3790 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003791
Felipe Leme873a83a2016-09-07 11:34:10 -07003792 // Fully update the app idle firewall chain.
3793 final List<UserInfo> users = mUserManager.getUsers();
3794 for (int ui = users.size() - 1; ui >= 0; ui--) {
3795 UserInfo user = users.get(ui);
3796 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3797 for (int uid : idleUids) {
3798 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3799 // quick check: if this uid doesn't have INTERNET permission, it
3800 // doesn't have network access anyway, so it is a waste to mess
3801 // with it here.
3802 if (hasInternetPermissions(uid)) {
3803 uidRules.put(uid, FIREWALL_RULE_DENY);
3804 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003805 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003806 }
3807 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003808
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003809 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003810 } finally {
3811 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3812 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003813 }
3814
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003815 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003816 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003817 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003818
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003819 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3820 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3821 }
3822 try {
3823 int appId = UserHandle.getAppId(uid);
3824 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3825 && !isUidForegroundOnRestrictPowerUL(uid)) {
3826 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003827 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003828 } else {
3829 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003830 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003831 }
3832 } finally {
3833 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003834 }
3835 }
3836
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003837 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003838 * Update rules that might be changed by {@link #mRestrictBackground},
3839 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003840 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003841 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003842 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003843 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3844 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3845 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3846 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003847 try {
Felipe Leme09700462016-09-08 09:33:48 -07003848 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003849 updateRulesForRestrictPowerUL();
3850 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003851
Felipe Leme873a83a2016-09-07 11:34:10 -07003852 // If the set of restricted networks may have changed, re-evaluate those.
3853 if (restrictedNetworksChanged) {
3854 normalizePoliciesNL();
3855 updateNetworkRulesNL();
3856 }
3857 } finally {
3858 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003859 }
3860 }
3861
Felipe Leme09700462016-09-08 09:33:48 -07003862 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003863 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003864 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003865 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3866 try {
3867 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003868 updateRulesForPowerSaveUL();
3869 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3870 } finally {
3871 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3872 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003873 }
3874
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003875 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003876 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003877 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3878 try {
3879 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3880 } finally {
3881 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3882 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003883 }
3884
3885 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3886 private static final int TYPE_RESTRICT_POWER = 2;
3887 @Retention(RetentionPolicy.SOURCE)
3888 @IntDef(flag = false, value = {
3889 TYPE_RESTRICT_BACKGROUND,
3890 TYPE_RESTRICT_POWER,
3891 })
3892 public @interface RestrictType {
3893 }
3894
3895 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003896 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003897 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003898 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3899 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3900 }
3901 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003902 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003903
3904 final PackageManager pm = mContext.getPackageManager();
3905 final List<UserInfo> users;
3906 final List<ApplicationInfo> apps;
3907
3908 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3909 try {
3910 users = mUserManager.getUsers();
3911 } finally {
3912 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3913 }
3914 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3915 try {
3916 apps = pm.getInstalledApplications(
3917 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3918 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3919 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3920 } finally {
3921 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3922 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003923
Felipe Leme873a83a2016-09-07 11:34:10 -07003924 final int usersSize = users.size();
3925 final int appsSize = apps.size();
3926 for (int i = 0; i < usersSize; i++) {
3927 final UserInfo user = users.get(i);
3928 for (int j = 0; j < appsSize; j++) {
3929 final ApplicationInfo app = apps.get(j);
3930 final int uid = UserHandle.getUid(user.id, app.uid);
3931 switch (type) {
3932 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003933 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003934 break;
3935 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003936 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003937 break;
3938 default:
3939 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3940 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003941 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003942 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003943 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003944 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003945 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003946 }
3947
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003948 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003949 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003950 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003951 final int numUsers = users.size();
3952 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003953 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003954 int uid = UserHandle.getUid(user.id, appId);
3955 // Update external firewall rules.
3956 updateRuleForAppIdleUL(uid);
3957 updateRuleForDeviceIdleUL(uid);
3958 updateRuleForRestrictPowerUL(uid);
3959 // Update internal rules.
3960 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003961 }
3962 }
3963
Felipe Leme70c57c22016-03-29 10:45:13 -07003964 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3965 // methods below could be merged into a isUidValidForRules() method.
3966 private boolean isUidValidForBlacklistRules(int uid) {
3967 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003968 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003969 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003970 return true;
3971 }
3972
3973 return false;
3974 }
3975
Felipe Leme70c57c22016-03-29 10:45:13 -07003976 private boolean isUidValidForWhitelistRules(int uid) {
3977 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3978 }
3979
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003980 /**
3981 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3982 * power saving restrictions may still apply.
3983 */
3984 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003985 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003986 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3987
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003988 synchronized (mUidRulesFirstLock) {
3989 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3990 // No change.
3991 return;
3992 }
3993
3994 final long token = Binder.clearCallingIdentity();
3995 try {
3996 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3997 if (shouldWhitelist) {
3998 mAppIdleTempWhitelistAppIds.put(uid, true);
3999 } else {
4000 mAppIdleTempWhitelistAppIds.delete(uid);
4001 }
4002 updateRuleForAppIdleUL(uid);
4003 updateRulesForPowerRestrictionsUL(uid);
4004 } finally {
4005 Binder.restoreCallingIdentity(token);
4006 }
4007 }
4008 }
4009
4010 /** Return the list of UIDs currently in the app idle whitelist. */
4011 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004012 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004013 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4014
4015 synchronized (mUidRulesFirstLock) {
4016 final int len = mAppIdleTempWhitelistAppIds.size();
4017 int[] uids = new int[len];
4018 for (int i = 0; i < len; ++i) {
4019 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4020 }
4021 return uids;
4022 }
4023 }
4024
4025 /** Returns if the UID is currently considered idle. */
4026 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004027 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004028 synchronized (mUidRulesFirstLock) {
4029 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4030 // UID is temporarily whitelisted.
4031 return false;
4032 }
4033 }
4034
Amith Yamasani15e472352015-04-24 19:06:07 -07004035 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4036 final int userId = UserHandle.getUserId(uid);
4037
songjinshi0655edd2016-05-18 19:55:32 +08004038 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004039 for (String packageName : packages) {
4040 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4041 return false;
4042 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004043 }
4044 }
4045 return true;
4046 }
4047
4048 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004049 * Checks if an uid has INTERNET permissions.
4050 * <p>
4051 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004052 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004053 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004054 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004055 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004056 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004057 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004058 }
4059 } catch (RemoteException e) {
4060 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004061 return true;
4062 }
4063
4064 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004065 * Clears all state - internal and external - associated with an UID.
4066 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004067 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004068 private void onUidDeletedUL(int uid) {
4069 // First cleanup in-memory state synchronously...
4070 mUidRules.delete(uid);
4071 mUidPolicy.delete(uid);
4072 mUidFirewallStandbyRules.delete(uid);
4073 mUidFirewallDozableRules.delete(uid);
4074 mUidFirewallPowerSaveRules.delete(uid);
4075 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4076 mPowerSaveWhitelistAppIds.delete(uid);
4077 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004078 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004079
4080 // ...then update iptables asynchronously.
4081 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4082 }
4083
4084 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004085 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004086 *
Felipe Leme781ba142016-05-09 16:24:48 -07004087 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004088 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004089 * <li>Doze mode
4090 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004091 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004092 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004093 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004094 *
4095 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004096 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004097 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004098 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004099 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004100 updateRuleForDeviceIdleUL(uid);
4101 updateRuleForAppIdleUL(uid);
4102 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004103
4104 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004105 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004106
4107 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004108 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004109 }
4110
Felipe Leme70c57c22016-03-29 10:45:13 -07004111 /**
4112 * Applies network rules to bandwidth controllers based on process state and user-defined
4113 * restrictions (blacklist / whitelist).
4114 *
4115 * <p>
4116 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4117 * networks:
4118 * <ul>
4119 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4120 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4121 * also blacklisted.
4122 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004123 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004124 * <ul>
4125 *
4126 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4127 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4128 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4129 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004130 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004131 * {@link INetworkManagementService}, but this method should also be called in events (like
4132 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4133 * following rules should also be applied:
4134 *
4135 * <ul>
4136 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4137 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4138 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4139 * {@code bw_penalty_box}.
4140 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4141 * </ul>
4142 *
4143 * <p>For optimization, the rules are only applied on user apps that have internet access
4144 * permission, since there is no need to change the {@code iptables} rule if the app does not
4145 * have permission to use the internet.
4146 *
4147 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004148 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004149 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004150 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004151 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4152 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4153 "updateRulesForDataUsageRestrictionsUL: " + uid);
4154 }
4155 try {
4156 updateRulesForDataUsageRestrictionsULInner(uid);
4157 } finally {
4158 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4159 }
4160 }
4161
4162 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004163 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004164 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004165 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004166 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004167
Dianne Hackborn497175b2014-07-01 12:56:08 -07004168 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004169 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004170 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004171 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004172
Felipe Leme781ba142016-05-09 16:24:48 -07004173 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004174 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004175 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4176 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004177
Felipe Leme70c57c22016-03-29 10:45:13 -07004178 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004179 if (isRestrictedByAdmin) {
4180 newRule = RULE_REJECT_METERED;
4181 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004182 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4183 newRule = RULE_TEMPORARY_ALLOW_METERED;
4184 } else if (isWhitelisted) {
4185 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004186 }
4187 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004188 if (isBlacklisted) {
4189 newRule = RULE_REJECT_METERED;
4190 } else if (mRestrictBackground && isWhitelisted) {
4191 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004192 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004193 }
Felipe Leme781ba142016-05-09 16:24:48 -07004194 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004195
Felipe Lemef28983d2016-03-25 12:18:23 -07004196 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004197 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004198 + ": isForeground=" +isForeground
4199 + ", isBlacklisted=" + isBlacklisted
4200 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004201 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004202 + ", oldRule=" + uidRulesToString(oldRule)
4203 + ", newRule=" + uidRulesToString(newRule)
4204 + ", newUidRules=" + uidRulesToString(newUidRules)
4205 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004206 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004207
Felipe Leme46c4fc32016-05-04 09:21:43 -07004208 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004209 mUidRules.delete(uid);
4210 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004211 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004212 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004213
Felipe Leme70c57c22016-03-29 10:45:13 -07004214 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004215 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004216 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004217 // Temporarily whitelist foreground app, removing from blacklist if necessary
4218 // (since bw_penalty_box prevails over bw_happy_box).
4219
4220 setMeteredNetworkWhitelist(uid, true);
4221 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4222 // but ideally it should be just:
4223 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004224 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004225 setMeteredNetworkBlacklist(uid, false);
4226 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004227 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004228 // Remove temporary whitelist from app that is not on foreground anymore.
4229
4230 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4231 // but ideally they should be just:
4232 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4233 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004234 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004235 setMeteredNetworkWhitelist(uid, false);
4236 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004237 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004238 setMeteredNetworkBlacklist(uid, true);
4239 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004240 } else if (hasRule(newRule, RULE_REJECT_METERED)
4241 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004242 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004243 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004244 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004245 // Since blacklist prevails over whitelist, we need to handle the special case
4246 // where app is whitelisted and blacklisted at the same time (although such
4247 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004248 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004249 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004250 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4251 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004252 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004253 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004254 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004255 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004256 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4257 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004258 + ", whitelisted=" + isWhitelisted
4259 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004260 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004261 + ", newRule=" + uidRulesToString(newUidRules)
4262 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004263 }
Felipe Leme781ba142016-05-09 16:24:48 -07004264
Sudheer Shankac9d94072017-02-22 22:13:55 +00004265 // Dispatch changed rule to existing listeners.
4266 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004267 }
4268 }
4269
4270 /**
4271 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4272 * listeners in case of change.
4273 * <p>
4274 * There are 3 power-related rules that affects whether an app has background access on
4275 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4276 * restriction, it's added to the equivalent firewall chain:
4277 * <ul>
4278 * <li>App is idle: {@code fw_standby} firewall chain.
4279 * <li>Device is idle: {@code fw_dozable} firewall chain.
4280 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4281 * </ul>
4282 * <p>
4283 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4284 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4285 * <p>
4286 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4287 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004288 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004289 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004290 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4291
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004292 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004293
Sudheer Shankac9d94072017-02-22 22:13:55 +00004294 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004295 mUidRules.delete(uid);
4296 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004297 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004298 }
4299 }
4300
4301 /**
4302 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4303 *
4304 * @param uid the uid of the app to update rules for
4305 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004306 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004307 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004308 */
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004309 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004310 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4311 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004312 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004313 }
4314 try {
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004315 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004316 } finally {
4317 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4318 }
4319 }
4320
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004321 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules) {
Felipe Leme781ba142016-05-09 16:24:48 -07004322 if (!isUidValidForBlacklistRules(uid)) {
4323 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004324 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004325 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004326
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004327 final boolean isIdle = isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004328 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004329 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004330
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004331 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004332 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4333 int newRule = RULE_NONE;
4334
4335 // First step: define the new rule based on user restrictions and foreground state.
4336
4337 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4338 // by considering the foreground and non-foreground states.
4339 if (isForeground) {
4340 if (restrictMode) {
4341 newRule = RULE_ALLOW_ALL;
4342 }
4343 } else if (restrictMode) {
4344 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4345 }
4346
4347 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4348
4349 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004350 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004351 + ", isIdle: " + isIdle
4352 + ", mRestrictPower: " + mRestrictPower
4353 + ", mDeviceIdleMode: " + mDeviceIdleMode
4354 + ", isForeground=" + isForeground
4355 + ", isWhitelisted=" + isWhitelisted
4356 + ", oldRule=" + uidRulesToString(oldRule)
4357 + ", newRule=" + uidRulesToString(newRule)
4358 + ", newUidRules=" + uidRulesToString(newUidRules)
4359 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4360 }
4361
Felipe Leme781ba142016-05-09 16:24:48 -07004362 // Second step: notify listeners if state changed.
4363 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004364 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004365 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004366 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004367 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4368 } else {
4369 // All scenarios should have been covered above
4370 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4371 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004372 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004373 + ", newRule=" + uidRulesToString(newUidRules)
4374 + ", oldRule=" + uidRulesToString(oldUidRules));
4375 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004376 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004377 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004378
Sudheer Shankac9d94072017-02-22 22:13:55 +00004379 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004380 }
4381
Christopher Tateb909c4d52019-10-21 12:50:37 -07004382 private class NetPolicyAppIdleStateChangeListener extends AppIdleStateChangeListener {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004383 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004384 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4385 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004386 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004387 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4388 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004389 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004390 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004391 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004392 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004393 }
4394 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004395 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004396 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004397 }
4398
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004399 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4400 if (listener != null) {
4401 try {
4402 listener.onUidRulesChanged(uid, uidRules);
4403 } catch (RemoteException ignored) {
4404 }
4405 }
4406 }
4407
4408 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4409 String[] meteredIfaces) {
4410 if (listener != null) {
4411 try {
4412 listener.onMeteredIfacesChanged(meteredIfaces);
4413 } catch (RemoteException ignored) {
4414 }
4415 }
4416 }
4417
4418 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4419 boolean restrictBackground) {
4420 if (listener != null) {
4421 try {
4422 listener.onRestrictBackgroundChanged(restrictBackground);
4423 } catch (RemoteException ignored) {
4424 }
4425 }
4426 }
4427
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004428 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4429 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004430 if (listener != null) {
4431 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004432 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004433 } catch (RemoteException ignored) {
4434 }
4435 }
4436 }
4437
Jeff Sharkey9252b342018-01-19 07:58:35 +09004438 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
Sarah Chin7af1fd02019-09-26 11:37:13 -07004439 int overrideMask, int overrideValue) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09004440 if (listener != null) {
4441 try {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004442 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4443 } catch (RemoteException ignored) {
4444 }
4445 }
4446 }
4447
4448 private void dispatchSubscriptionPlansChanged(INetworkPolicyListener listener, int subId,
4449 SubscriptionPlan[] plans) {
4450 if (listener != null) {
4451 try {
4452 listener.onSubscriptionPlansChanged(subId, plans);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004453 } catch (RemoteException ignored) {
4454 }
4455 }
4456 }
4457
Makoto Onuki8e777332017-03-28 11:25:47 -07004458 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004459 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004460 public boolean handleMessage(Message msg) {
4461 switch (msg.what) {
4462 case MSG_RULES_CHANGED: {
4463 final int uid = msg.arg1;
4464 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004465 final int length = mListeners.beginBroadcast();
4466 for (int i = 0; i < length; i++) {
4467 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4468 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004469 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004470 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004471 return true;
4472 }
4473 case MSG_METERED_IFACES_CHANGED: {
4474 final String[] meteredIfaces = (String[]) msg.obj;
4475 final int length = mListeners.beginBroadcast();
4476 for (int i = 0; i < length; i++) {
4477 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004478 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004479 }
4480 mListeners.finishBroadcast();
4481 return true;
4482 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004483 case MSG_LIMIT_REACHED: {
4484 final String iface = (String) msg.obj;
4485
Felipe Lemef0823852016-06-08 13:43:08 -07004486 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004487 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004488 // force stats update to make sure we have
4489 // numbers that caused alert to trigger.
4490 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004491
Felipe Lemef0823852016-06-08 13:43:08 -07004492 updateNetworkEnabledNL();
4493 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004494 }
4495 }
4496 return true;
4497 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004498 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4499 final boolean restrictBackground = msg.arg1 != 0;
4500 final int length = mListeners.beginBroadcast();
4501 for (int i = 0; i < length; i++) {
4502 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004503 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004504 }
4505 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004506 final Intent intent =
4507 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4508 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4509 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4510 return true;
4511 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004512 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004513 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004514 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004515 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004516 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004517 final int length = mListeners.beginBroadcast();
4518 for (int i = 0; i < length; i++) {
4519 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004520 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004521 }
4522 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004523 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4524 if (notifyApp.booleanValue()) {
4525 broadcastRestrictBackgroundChanged(uid, notifyApp);
4526 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004527 return true;
4528 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004529 case MSG_ADVISE_PERSIST_THRESHOLD: {
4530 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004531 // make sure stats are recorded frequently enough; we aim
4532 // for 2MB threshold for 2GB/month rules.
4533 final long persistThreshold = lowestRule / 1000;
4534 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004535 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004536 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004537 case MSG_UPDATE_INTERFACE_QUOTA: {
4538 removeInterfaceQuota((String) msg.obj);
4539 // int params need to be stitched back into a long
4540 setInterfaceQuota((String) msg.obj,
4541 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4542 return true;
4543 }
4544 case MSG_REMOVE_INTERFACE_QUOTA: {
4545 removeInterfaceQuota((String) msg.obj);
4546 return true;
4547 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004548 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4549 resetUidFirewallRules(msg.arg1);
4550 return true;
4551 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004552 case MSG_SUBSCRIPTION_OVERRIDE: {
Sarah Chin7af1fd02019-09-26 11:37:13 -07004553 final int overrideMask = msg.arg1;
4554 final int overrideValue = msg.arg2;
4555 final int subId = (int) msg.obj;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004556 final int length = mListeners.beginBroadcast();
4557 for (int i = 0; i < length; i++) {
4558 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Sarah Chin7af1fd02019-09-26 11:37:13 -07004559 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004560 }
4561 mListeners.finishBroadcast();
4562 return true;
4563 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004564 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4565 final int userId = msg.arg1;
4566 final Set<String> packageNames = (Set<String>) msg.obj;
4567 setMeteredRestrictedPackagesInternal(packageNames, userId);
4568 return true;
4569 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004570 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4571 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4572 final boolean enabled = msg.arg1 != 0;
4573 setNetworkTemplateEnabledInner(template, enabled);
4574 return true;
4575 }
Sarah Chin7af1fd02019-09-26 11:37:13 -07004576 case MSG_SUBSCRIPTION_PLANS_CHANGED: {
4577 final SubscriptionPlan[] plans = (SubscriptionPlan[]) msg.obj;
4578 final int subId = msg.arg1;
4579 final int length = mListeners.beginBroadcast();
4580 for (int i = 0; i < length; i++) {
4581 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4582 dispatchSubscriptionPlansChanged(listener, subId, plans);
4583 }
4584 mListeners.finishBroadcast();
4585 return true;
4586 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004587 default: {
4588 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004589 }
4590 }
4591 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004592 };
4593
4594 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4595 @Override
4596 public boolean handleMessage(Message msg) {
4597 switch (msg.what) {
4598 case UID_MSG_STATE_CHANGED: {
4599 final int uid = msg.arg1;
4600 final int procState = msg.arg2;
4601 final long procStateSeq = (Long) msg.obj;
4602
4603 handleUidChanged(uid, procState, procStateSeq);
4604 return true;
4605 }
4606 case UID_MSG_GONE: {
4607 final int uid = msg.arg1;
4608 handleUidGone(uid);
4609 return true;
4610 }
4611 default: {
4612 return false;
4613 }
4614 }
4615 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004616 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004617
Makoto Onuki8e777332017-03-28 11:25:47 -07004618 void handleUidChanged(int uid, int procState, long procStateSeq) {
4619 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4620 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004621 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004622 synchronized (mUidRulesFirstLock) {
4623 // We received a uid state change callback, add it to the history so that it
4624 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004625 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004626 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004627 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004628 // Updating the network rules is done, so notify AMS about this.
4629 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4630 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004631 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4632 // called from the handler, so there's no multi-threading issue.
4633 if (updated) {
4634 updateNetworkStats(uid, isUidStateForeground(procState));
4635 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004636 } finally {
4637 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4638 }
4639 }
4640
4641 void handleUidGone(int uid) {
4642 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4643 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004644 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004645 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004646 updated = removeUidStateUL(uid);
4647 }
4648 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4649 // called from the handler, so there's no multi-threading issue.
4650 if (updated) {
4651 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004652 }
4653 } finally {
4654 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4655 }
4656 }
4657
Felipe Leme57e3d312016-08-23 14:42:52 -07004658 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4659 final PackageManager pm = mContext.getPackageManager();
4660 final String[] packages = pm.getPackagesForUid(uid);
4661 if (packages != null) {
4662 final int userId = UserHandle.getUserId(uid);
4663 for (String packageName : packages) {
4664 final Intent intent =
4665 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4666 intent.setPackage(packageName);
4667 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4668 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4669 }
4670 }
4671 }
4672
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004673 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4674 // long quotaBytes split up into two ints to fit in message
4675 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4676 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4677 }
4678
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004679 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004680 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004681 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004682 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004683 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004684 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004685 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004686 }
4687 }
4688
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004689 private void removeInterfaceQuotaAsync(String iface) {
4690 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4691 }
4692
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004693 private void removeInterfaceQuota(String iface) {
4694 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004695 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004696 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004697 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004698 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004699 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004700 }
4701 }
4702
Felipe Leme70c57c22016-03-29 10:45:13 -07004703 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4704 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004705 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004706 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004707 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004708 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4709 } catch (RemoteException e) {
4710 // ignored; service lives in system_server
4711 }
4712 }
4713
4714 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4715 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4716 try {
4717 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4718 } catch (IllegalStateException e) {
4719 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004720 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004721 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004722 }
4723 }
4724
Felipe Lemebc853dd2016-09-08 13:26:55 -07004725 private static final int CHAIN_TOGGLE_NONE = 0;
4726 private static final int CHAIN_TOGGLE_ENABLE = 1;
4727 private static final int CHAIN_TOGGLE_DISABLE = 2;
4728 @Retention(RetentionPolicy.SOURCE)
4729 @IntDef(flag = false, value = {
4730 CHAIN_TOGGLE_NONE,
4731 CHAIN_TOGGLE_ENABLE,
4732 CHAIN_TOGGLE_DISABLE
4733 })
4734 public @interface ChainToggleType {
4735 }
4736
4737 /**
Kweku Adamsdf33ae12019-10-08 11:51:41 -07004738 * Calls {@link #setUidFirewallRulesUL(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004739 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004740 *
4741 * @param chain firewall chain.
4742 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4743 * @param toggle whether the chain should be enabled, disabled, or not changed.
4744 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004745 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004746 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004747 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004748 if (uidRules != null) {
4749 setUidFirewallRulesUL(chain, uidRules);
4750 }
4751 if (toggle != CHAIN_TOGGLE_NONE) {
4752 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4753 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004754 }
4755
Amith Yamasani15e472352015-04-24 19:06:07 -07004756 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004757 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4758 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4759 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004760 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004761 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004762 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004763 int size = uidRules.size();
4764 int[] uids = new int[size];
4765 int[] rules = new int[size];
4766 for(int index = size - 1; index >= 0; --index) {
4767 uids[index] = uidRules.keyAt(index);
4768 rules[index] = uidRules.valueAt(index);
4769 }
4770 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004771 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004772 } catch (IllegalStateException e) {
4773 Log.wtf(TAG, "problem setting firewall uid rules", e);
4774 } catch (RemoteException e) {
4775 // ignored; service lives in system_server
4776 }
4777 }
4778
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004779 /**
4780 * Add or remove a uid to the firewall blacklist for all network ifaces.
4781 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004782 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004783 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4784 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4785 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004786 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004787 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004788 if (chain == FIREWALL_CHAIN_DOZABLE) {
4789 mUidFirewallDozableRules.put(uid, rule);
4790 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4791 mUidFirewallStandbyRules.put(uid, rule);
4792 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4793 mUidFirewallPowerSaveRules.put(uid, rule);
4794 }
4795
4796 try {
4797 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004798 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004799 } catch (IllegalStateException e) {
4800 Log.wtf(TAG, "problem setting firewall uid rules", e);
4801 } catch (RemoteException e) {
4802 // ignored; service lives in system_server
4803 }
4804 } finally {
4805 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004806 }
4807 }
4808
4809 /**
4810 * Add or remove a uid to the firewall blacklist for all network ifaces.
4811 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004812 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004813 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004814 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4815 mFirewallChainStates.get(chain) == enable) {
4816 // All is the same, nothing to do.
4817 return;
4818 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004819 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004820 try {
4821 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004822 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004823 } catch (IllegalStateException e) {
4824 Log.wtf(TAG, "problem enable firewall chain", e);
4825 } catch (RemoteException e) {
4826 // ignored; service lives in system_server
4827 }
4828 }
4829
Felipe Leme03e95e22016-09-09 09:25:31 -07004830 /**
4831 * Resets all firewall rules associated with an UID.
4832 */
4833 private void resetUidFirewallRules(int uid) {
4834 try {
4835 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4836 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4837 mNetworkManager
4838 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4839 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4840 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4841 } catch (IllegalStateException e) {
4842 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4843 } catch (RemoteException e) {
4844 // ignored; service lives in system_server
4845 }
4846 }
4847
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004848 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004849 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004850 return getNetworkTotalBytes(template, start, end);
4851 }
4852
4853 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004854 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004855 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004856 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004857 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004858 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004859 }
4860 }
4861
4862 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4863 try {
4864 return mNetworkStats.getNetworkUidBytes(template, start, end);
4865 } catch (RuntimeException e) {
4866 Slog.w(TAG, "Failed to read network stats: " + e);
4867 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004868 }
4869 }
4870
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004871 private boolean isBandwidthControlEnabled() {
4872 final long token = Binder.clearCallingIdentity();
4873 try {
4874 return mNetworkManager.isBandwidthControlEnabled();
4875 } catch (RemoteException e) {
4876 // ignored; service lives in system_server
4877 return false;
4878 } finally {
4879 Binder.restoreCallingIdentity(token);
4880 }
4881 }
4882
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004883 private static Intent buildAllowBackgroundDataIntent() {
4884 return new Intent(ACTION_ALLOW_BACKGROUND);
4885 }
4886
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004887 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4888 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004889 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4890 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4891 return intent;
4892 }
4893
4894 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4895 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4896 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004897 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4898 return intent;
4899 }
4900
Wei Liu546cb772016-07-21 16:19:01 -07004901 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004902 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004903 intent.setComponent(ComponentName.unflattenFromString(
4904 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004905 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4906 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4907 return intent;
4908 }
4909
Wei Liu546cb772016-07-21 16:19:01 -07004910 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004911 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004912 intent.setComponent(ComponentName.unflattenFromString(
4913 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004914 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4915 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4916 return intent;
4917 }
4918
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004919 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004920 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004921 mHandler.getLooper().getQueue().addIdleHandler(handler);
4922 }
4923
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004924 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004925 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004926 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
Kweku Adams25fa3a72019-07-12 17:00:17 -07004927 if (mRestrictBackgroundLowPowerMode == result.batterySaverEnabled) {
4928 // Nothing changed. Nothing to do.
4929 return;
4930 }
4931 mRestrictBackgroundLowPowerMode = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004932
Kweku Adams25fa3a72019-07-12 17:00:17 -07004933 boolean restrictBackground = mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004934 boolean shouldInvokeRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -07004935 // store the temporary mRestrictBackgroundChangedInBsm and update it at the end.
jackqdyulei29c82ab2017-03-10 14:09:16 -08004936 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4937
Kweku Adams25fa3a72019-07-12 17:00:17 -07004938 if (mRestrictBackgroundLowPowerMode) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004939 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4940 // turn it on.
Kweku Adams25fa3a72019-07-12 17:00:17 -07004941 shouldInvokeRestrictBackground = !mRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004942 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4943 localRestrictBgChangedInBsm = false;
4944 } else {
4945 // Try to restore the restrictBackground if it doesn't change in bsm
4946 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4947 restrictBackground = mRestrictBackgroundBeforeBsm;
4948 }
4949
4950 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004951 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004952 }
4953
4954 // Change it at last so setRestrictBackground() won't affect this variable
4955 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4956 }
4957
Jeff Sharkey1b861272011-05-22 00:34:52 -07004958 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4959 final int size = source.size();
4960 for (int i = 0; i < size; i++) {
4961 target.put(source.keyAt(i), true);
4962 }
4963 }
4964
Stuart Scottf1fb3972015-04-02 18:00:02 -07004965 @Override
4966 public void factoryReset(String subscriber) {
4967 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4968
Stuart Scotte3e314d2015-04-20 14:07:45 -07004969 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4970 return;
4971 }
4972
Stuart Scottf1fb3972015-04-02 18:00:02 -07004973 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004974 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004975 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4976 for (NetworkPolicy policy : policies) {
4977 if (policy.template.equals(template)) {
4978 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4979 policy.inferred = false;
4980 policy.clearSnooze();
4981 }
4982 }
4983 setNetworkPolicies(policies);
4984
4985 // Turn restrict background data off
4986 setRestrictBackground(false);
4987
Stuart Scotte3e314d2015-04-20 14:07:45 -07004988 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4989 // Remove app's "restrict background data" flag
4990 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4991 setUidPolicy(uid, POLICY_NONE);
4992 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004993 }
4994 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004995
Sudheer Shankab8f23162017-08-04 13:30:10 -07004996 @Override
4997 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004998 final long startTime = mStatLogger.getTime();
4999
Sudheer Shankab8f23162017-08-04 13:30:10 -07005000 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07005001 final int uidRules;
5002 final boolean isBackgroundRestricted;
5003 synchronized (mUidRulesFirstLock) {
5004 uidRules = mUidRules.get(uid, RULE_NONE);
5005 isBackgroundRestricted = mRestrictBackground;
5006 }
junyulai05986c62018-08-07 19:50:45 +08005007 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5008 isBackgroundRestricted, mLogger);
5009
5010 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5011
5012 return ret;
5013 }
5014
5015 private static boolean isSystem(int uid) {
5016 return uid < Process.FIRST_APPLICATION_UID;
5017 }
5018
5019 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
5020 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5021 final int reason;
5022 // Networks are never blocked for system components
5023 if (isSystem(uid)) {
5024 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005025 }
junyulai05986c62018-08-07 19:50:45 +08005026 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5027 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005028 }
junyulai05986c62018-08-07 19:50:45 +08005029 else if (!isNetworkMetered) {
5030 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005031 }
junyulai05986c62018-08-07 19:50:45 +08005032 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5033 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005034 }
junyulai05986c62018-08-07 19:50:45 +08005035 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5036 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005037 }
junyulai05986c62018-08-07 19:50:45 +08005038 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5039 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005040 }
junyulai05986c62018-08-07 19:50:45 +08005041 else if (isBackgroundRestricted) {
5042 reason = NTWK_BLOCKED_BG_RESTRICT;
5043 }
5044 else {
5045 reason = NTWK_ALLOWED_DEFAULT;
5046 }
5047
5048 final boolean blocked;
5049 switch(reason) {
5050 case NTWK_ALLOWED_DEFAULT:
5051 case NTWK_ALLOWED_NON_METERED:
5052 case NTWK_ALLOWED_TMP_WHITELIST:
5053 case NTWK_ALLOWED_WHITELIST:
5054 case NTWK_ALLOWED_SYSTEM:
5055 blocked = false;
5056 break;
5057 case NTWK_BLOCKED_POWER:
5058 case NTWK_BLOCKED_BLACKLIST:
5059 case NTWK_BLOCKED_BG_RESTRICT:
5060 blocked = true;
5061 break;
5062 default:
5063 throw new IllegalArgumentException();
5064 }
5065 if (logger != null) {
5066 logger.networkBlocked(uid, reason);
5067 }
5068
5069 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005070 }
5071
Felipe Lemed17fda42016-04-29 11:12:45 -07005072 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5073
5074 @Override
5075 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005076 synchronized (mUidRulesFirstLock) {
5077 boolean changed = removeUserStateUL(userId, false);
5078 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005079 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005080 synchronized (mNetworkPoliciesSecondLock) {
5081 writePolicyAL();
5082 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005083 }
5084 }
5085 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005086
5087 /**
5088 * @return true if the given uid is restricted from doing networking on metered networks.
5089 */
5090 @Override
5091 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5092 final int uidRules;
5093 final boolean isBackgroundRestricted;
5094 synchronized (mUidRulesFirstLock) {
5095 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5096 isBackgroundRestricted = mRestrictBackground;
5097 }
5098 return isBackgroundRestricted
5099 && !hasRule(uidRules, RULE_ALLOW_METERED)
5100 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5101 }
5102
5103 /**
5104 * @return true if networking is blocked on the given interface for the given uid according
5105 * to current networking policies.
5106 */
5107 @Override
5108 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005109 final long startTime = mStatLogger.getTime();
5110
junyulai05986c62018-08-07 19:50:45 +08005111 final int uidRules;
5112 final boolean isBackgroundRestricted;
5113 synchronized (mUidRulesFirstLock) {
5114 uidRules = mUidRules.get(uid, RULE_NONE);
5115 isBackgroundRestricted = mRestrictBackground;
5116 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005117 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005118 synchronized (mNetworkPoliciesSecondLock) {
5119 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005120 }
junyulai05986c62018-08-07 19:50:45 +08005121 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5122 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005123
5124 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5125
5126 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005127 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005128
5129 @Override
5130 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5131 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005132 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005133 if (added) {
5134 mPowerSaveTempWhitelistAppIds.put(appId, true);
5135 } else {
5136 mPowerSaveTempWhitelistAppIds.delete(appId);
5137 }
5138 updateRulesForTempWhitelistChangeUL(appId);
5139 }
5140 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005141
5142 @Override
5143 public SubscriptionPlan getSubscriptionPlan(Network network) {
5144 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005145 final int subId = getSubIdLocked(network);
5146 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005147 }
5148 }
5149
5150 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005151 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5152 synchronized (mNetworkPoliciesSecondLock) {
5153 final int subId = findRelevantSubIdNL(template);
5154 return getPrimarySubscriptionPlanLocked(subId);
5155 }
5156 }
5157
5158 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005159 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005160 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005161 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005162 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005163 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005164 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005165 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5166 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5167 }
5168
5169 if (quotaType == QUOTA_TYPE_JOBS) {
5170 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5171 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5172 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5173 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5174 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5175 } else {
5176 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5177 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005178 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005179
5180 @Override
5181 public void onAdminDataAvailable() {
5182 mAdminDataAvailableLatch.countDown();
5183 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005184
5185 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005186 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5187 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5188 }
5189
5190 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005191 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5192 setMeteredRestrictedPackagesInternal(packageNames, userId);
5193 }
5194
5195 @Override
5196 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5197 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5198 userId, 0, packageNames).sendToTarget();
5199 }
5200 }
5201
5202 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5203 synchronized (mUidRulesFirstLock) {
5204 final Set<Integer> newRestrictedUids = new ArraySet<>();
5205 for (String packageName : packageNames) {
5206 final int uid = getUidForPackage(packageName, userId);
5207 if (uid >= 0) {
5208 newRestrictedUids.add(uid);
5209 }
5210 }
5211 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5212 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5213 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5214 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5215 }
5216 }
5217
5218 private int getUidForPackage(String packageName, int userId) {
5219 try {
5220 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5221 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5222 } catch (NameNotFoundException e) {
5223 return -1;
5224 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005225 }
5226
5227 private int parseSubId(NetworkState state) {
5228 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5229 int subId = INVALID_SUBSCRIPTION_ID;
5230 if (state != null && state.networkCapabilities != null
5231 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5232 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5233 if (spec instanceof StringNetworkSpecifier) {
5234 try {
5235 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5236 } catch (NumberFormatException e) {
5237 }
5238 }
5239 }
5240 return subId;
5241 }
5242
Andreas Gampea36dc622018-02-05 17:19:22 -08005243 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005244 private int getSubIdLocked(Network network) {
5245 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005246 }
5247
Andreas Gampea36dc622018-02-05 17:19:22 -08005248 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005249 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5250 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005251 if (!ArrayUtils.isEmpty(plans)) {
5252 for (SubscriptionPlan plan : plans) {
5253 if (plan.getCycleRule().isRecurring()) {
5254 // Recurring plans will always have an active cycle
5255 return plan;
5256 } else {
5257 // Non-recurring plans need manual test for active cycle
5258 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5259 if (cycle.contains(ZonedDateTime.now(mClock))) {
5260 return plan;
5261 }
5262 }
5263 }
5264 }
5265 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005266 }
5267
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005268 /**
5269 * This will only ever be called once - during device boot.
5270 */
5271 private void waitForAdminData() {
5272 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5273 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5274 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5275 }
5276 }
5277
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005278 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5279 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005280 if (!mNetworkManagerReady) {
5281 return;
5282 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005283 if (oldRestrictedUids == null) {
5284 for (int uid : newRestrictedUids) {
5285 updateRulesForDataUsageRestrictionsUL(uid);
5286 }
5287 return;
5288 }
5289 for (int uid : oldRestrictedUids) {
5290 if (!newRestrictedUids.contains(uid)) {
5291 updateRulesForDataUsageRestrictionsUL(uid);
5292 }
5293 }
5294 for (int uid : newRestrictedUids) {
5295 if (!oldRestrictedUids.contains(uid)) {
5296 updateRulesForDataUsageRestrictionsUL(uid);
5297 }
5298 }
5299 }
5300
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005301 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005302 private boolean isRestrictedByAdminUL(int uid) {
5303 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5304 UserHandle.getUserId(uid));
5305 return restrictedUids != null && restrictedUids.contains(uid);
5306 }
5307
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005308 private static boolean hasRule(int uidRules, int rule) {
5309 return (uidRules & rule) != 0;
5310 }
5311
Jeff Sharkey2e471452018-01-19 18:02:47 +09005312 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5313 return (val != null) ? val : new NetworkState[0];
5314 }
5315
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005316 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5317 String key, boolean defaultValue) {
5318 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5319 }
5320
Chris Wren193ae6b2017-03-31 15:17:11 -04005321 private class NotificationId {
5322 private final String mTag;
5323 private final int mId;
5324
5325 NotificationId(NetworkPolicy policy, int type) {
5326 mTag = buildNotificationTag(policy, type);
5327 mId = type;
5328 }
5329
5330 @Override
5331 public boolean equals(Object o) {
5332 if (this == o) return true;
5333 if (!(o instanceof NotificationId)) return false;
5334 NotificationId that = (NotificationId) o;
5335 return Objects.equals(mTag, that.mTag);
5336 }
5337
5338 @Override
5339 public int hashCode() {
5340 return Objects.hash(mTag);
5341 }
5342
5343 /**
5344 * Build unique tag that identifies an active {@link NetworkPolicy}
5345 * notification of a specific type, like {@link #TYPE_LIMIT}.
5346 */
5347 private String buildNotificationTag(NetworkPolicy policy, int type) {
5348 return TAG + ":" + policy.template.hashCode() + ":" + type;
5349 }
5350
5351 public String getTag() {
5352 return mTag;
5353 }
5354
5355 public int getId() {
5356 return mId;
5357 }
5358 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005359}