blob: d3346cddf3d09b9d779da69d19903ae22ce61786 [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;
Heemin Seogb9820d42019-05-21 16:17:43 -0700220import com.android.internal.os.RoSystemProperties;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700221import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800222import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800223import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600224import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700225import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700226import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600227import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700228import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700229import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700230import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700231import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800232import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600233
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600234import libcore.io.IoUtils;
235
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700240import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241import java.io.FileInputStream;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700245import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700246import java.lang.annotation.Retention;
247import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100248import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700249import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900250import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600251import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700252import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600253import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900254import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600256import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700257import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600258import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400259import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800260import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800261import java.util.concurrent.CountDownLatch;
262import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700264/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700265 * Service that maintains low-level network policy rules, using
266 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700267 * <p>
268 * Derives active rules by combining a given policy with other system status,
269 * and delivers to listeners, such as {@link ConnectivityManager}, for
270 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700271 *
272 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700273 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700274 * <ul>
275 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
276 * rules).
277 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
278 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700279 * </ul>
280 *
281 * <p>
282 * As such, methods that require synchronization have the following prefixes:
283 * <ul>
284 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
285 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000286 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
287 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700288 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700290public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700291 static final String TAG = NetworkPolicyLogger.TAG;
292 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
293 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700294
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900295 /**
296 * No opportunistic quota could be calculated from user data plan or data settings.
297 */
298 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
299
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final int VERSION_INIT = 1;
301 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700302 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800304 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800305 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700306 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700307 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700308 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700309 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600310 private static final int VERSION_ADDED_CYCLE = 11;
311 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800313 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400314 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800315 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400316 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400318 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900319 @VisibleForTesting
320 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700321
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String TAG_POLICY_LIST = "policy-list";
323 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600324 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700326 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800327 private static final String TAG_WHITELIST = "whitelist";
328 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800329 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
331 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700332 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700333 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
334 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700335 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600336 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
337 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
338 private static final String ATTR_CYCLE_START = "cycleStart";
339 private static final String ATTR_CYCLE_END = "cycleEnd";
340 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341 private static final String ATTR_WARNING_BYTES = "warningBytes";
342 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
345 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800346 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700347 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700349 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600351 private static final String ATTR_SUB_ID = "subId";
352 private static final String ATTR_TITLE = "title";
353 private static final String ATTR_SUMMARY = "summary";
354 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
355 private static final String ATTR_USAGE_BYTES = "usageBytes";
356 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600357 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800359 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800360 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800361 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800362 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700363 private static final String ACTION_SNOOZE_RAPID =
364 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700365
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800366 /**
367 * Indicates the maximum wait time for admin data to be available;
368 */
369 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
370
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600371 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
372 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
373 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
374 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
375
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700376 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700377 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800378 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800379 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700380 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700381 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
382 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700383 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700384 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900385 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800386 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700387 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700388
Makoto Onuki8e777332017-03-28 11:25:47 -0700389 private static final int UID_MSG_STATE_CHANGED = 100;
390 private static final int UID_MSG_GONE = 101;
391
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600392 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
393
Jeff Sharkey75279902011-05-24 18:39:45 -0700394 private final Context mContext;
395 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700396 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700397 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700398 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700399 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700400 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700401 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
403 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700404 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800406 @GuardedBy("mUidRulesFirstLock")
407 private PowerSaveState mRestrictBackgroundPowerState;
408
409 // Store the status of restrict background before turning on battery saver.
410 // Used to restore mRestrictBackground when battery saver is turned off.
411 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700412
Sudheer Shanka543339f2017-07-28 15:18:07 -0700413 // Denotes the status of restrict background read from disk.
414 private boolean mLoadedRestrictBackground;
415
Felipe Lemef0823852016-06-08 13:43:08 -0700416 // See main javadoc for instructions on how to use these locks.
417 final Object mUidRulesFirstLock = new Object();
418 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700419
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700420 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
421 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700422
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
424 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
425 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800426 // Store whether user flipped restrict background in battery saver mode
427 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700428
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700429 private final boolean mSuppressDefaultPolicy;
430
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800431 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
432
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700433 private volatile boolean mNetworkManagerReady;
434
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700435 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600436 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800437 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700438
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600439 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600440 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600441 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600442 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600443 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600445
Jeff Sharkey9252b342018-01-19 07:58:35 +0900446 /** Map from subId to daily opportunistic quota. */
447 @GuardedBy("mNetworkPoliciesSecondLock")
448 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
449
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700450 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700451 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700452 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700454
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700456 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700458 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800460 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700461
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700462 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700464 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
465
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800466 // "Power save mode" is the concept used in the DeviceIdleController that includes various
467 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
468 // and "battery saver" are not equivalent.
469
Jeff Sharkey32566012014-12-02 18:30:14 -0800470 /**
471 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700472 * in power save mode, except device idle (doze) still applies.
473 * TODO: An int array might be sufficient
474 */
Felipe Lemef0823852016-06-08 13:43:08 -0700475 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700476 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
477
478 /**
479 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800480 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700481 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800482 */
Felipe Lemef0823852016-06-08 13:43:08 -0700483 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700484 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700485
Felipe Lemef0823852016-06-08 13:43:08 -0700486 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700487 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
488
Felipe Lemeb85a6372016-01-14 16:16:16 -0800489 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800490 * UIDs that have been white-listed temporarily to be able to have network access despite being
491 * idle. Other power saving restrictions still apply.
492 */
493 @GuardedBy("mUidRulesFirstLock")
494 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
495
496 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800497 * UIDs that have been initially white-listed by system to avoid restricted background.
498 */
Felipe Lemef0823852016-06-08 13:43:08 -0700499 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800500 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
501 new SparseBooleanArray();
502
503 /**
504 * UIDs that have been initially white-listed by system to avoid restricted background,
505 * but later revoked by user.
506 */
Felipe Lemef0823852016-06-08 13:43:08 -0700507 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800508 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
509 new SparseBooleanArray();
510
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700511 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800513 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700514 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700515 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800516 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700517
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700518 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700519 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400520 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700521
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700522 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700523 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800524 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700525
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600526 /** Map from network ID to last observed meteredness state */
527 @GuardedBy("mNetworkPoliciesSecondLock")
528 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900529 /** Map from network ID to last observed roaming state */
530 @GuardedBy("mNetworkPoliciesSecondLock")
531 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
532
Jeff Sharkey9252b342018-01-19 07:58:35 +0900533 /** Map from netId to subId as of last update */
534 @GuardedBy("mNetworkPoliciesSecondLock")
535 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
536
Jeff Sharkey146bb332018-04-18 15:42:57 -0600537 /** Map from subId to subscriberId as of last update */
538 @GuardedBy("mNetworkPoliciesSecondLock")
539 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
540 /** Set of all merged subscriberId as of last update */
541 @GuardedBy("mNetworkPoliciesSecondLock")
Malcolm Chen07fcb5b2019-07-02 22:29:35 -0700542 private List<String[]> mMergedSubscriberIds = new ArrayList<>();
Jeff Sharkey146bb332018-04-18 15:42:57 -0600543
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800544 /**
545 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
546 * userId to restricted uids which belong to that user.
547 */
548 @GuardedBy("mUidRulesFirstLock")
549 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
550
Jeff Sharkey32566012014-12-02 18:30:14 -0800551 private final RemoteCallbackList<INetworkPolicyListener>
552 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700553
Dianne Hackborn497175b2014-07-01 12:56:08 -0700554 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700555 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800556 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700557
558 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700559
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700560 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700562
Svet Ganov16a16892015-04-16 10:32:04 -0700563 private final AppOpsManager mAppOps;
564
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800565 private final IPackageManager mIPm;
566
Sudheer Shankae7361852017-03-07 11:51:46 -0800567 private ActivityManagerInternal mActivityManagerInternal;
568
Sudheer Shanka352dc572017-09-22 17:09:38 -0700569 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800570
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700571 // TODO: keep whitelist of system-critical services that should never have
572 // rules enforced, such as system, phone, and radio UIDs.
573
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700574 // TODO: migrate notifications to SystemUI
575
Makoto Onuki49392d32018-04-11 13:51:02 -0700576
577 interface Stats {
578 int UPDATE_NETWORK_ENABLED = 0;
579 int IS_UID_NETWORKING_BLOCKED = 1;
580
581 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
582 }
583
584 public final StatLogger mStatLogger = new StatLogger(new String[] {
585 "updateNetworkEnabledNL()",
586 "isUidNetworkingBlocked()",
587 });
588
Jeff Sharkey75279902011-05-24 18:39:45 -0700589 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700590 INetworkManagementService networkManagement) {
591 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
592 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700593 }
594
Jeff Sharkey9911a282018-02-14 22:29:11 -0700595 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700596 return new File(Environment.getDataDirectory(), "system");
597 }
598
Jeff Sharkey9911a282018-02-14 22:29:11 -0700599 private static @NonNull Clock getDefaultClock() {
600 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
601 Clock.systemUTC());
602 }
603
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700604 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700605 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
606 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700607 mContext = checkNotNull(context, "missing context");
608 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700609 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700610 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700611 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700612 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700613 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700614 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700615 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700616
Amith Yamasani450a16b2013-09-18 16:28:50 -0700617 HandlerThread thread = new HandlerThread(TAG);
618 thread.start();
619 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700620
Makoto Onuki8e777332017-03-28 11:25:47 -0700621 // We create another thread for the UID events, which are more time-critical.
622 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
623 /*allowIo=*/ false);
624 mUidEventThread.start();
625 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
626
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700627 mSuppressDefaultPolicy = suppressDefaultPolicy;
628
Dianne Hackborne17b4452018-01-10 13:15:40 -0800629 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700630
631 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800632
Felipe Lemed17fda42016-04-29 11:12:45 -0700633 // Expose private service for system components to use.
634 LocalServices.addService(NetworkPolicyManagerInternal.class,
635 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700636 }
637
638 public void bindConnectivityManager(IConnectivityManager connManager) {
639 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700640 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700641
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700642 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700643 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700644 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700645 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
646 mPowerSaveWhitelistExceptIdleAppIds.clear();
647 if (whitelist != null) {
648 for (int uid : whitelist) {
649 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
650 }
651 }
652 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700653 mPowerSaveWhitelistAppIds.clear();
654 if (whitelist != null) {
655 for (int uid : whitelist) {
656 mPowerSaveWhitelistAppIds.put(uid, true);
657 }
658 }
659 } catch (RemoteException e) {
660 }
661 }
662
Felipe Lemea9505cc2016-02-26 10:28:41 -0800663 /**
664 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
665 * revoke the whitelist.
666 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700667 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800668 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700669 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700670 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800671 final List<UserInfo> users = mUserManager.getUsers();
672 final int numberUsers = users.size();
673
Felipe Lemea110eec2016-04-29 09:58:06 -0700674 boolean changed = false;
675 for (int i = 0; i < numberUsers; i++) {
676 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700677 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700678 }
679 return changed;
680 }
681
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700682 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700683 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700684 final SystemConfig sysConfig = SystemConfig.getInstance();
685 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800686 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
687 boolean changed = false;
688 for (int i = 0; i < allowDataUsage.size(); i++) {
689 final String pkg = allowDataUsage.valueAt(i);
690 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700691 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
692 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800693 final ApplicationInfo app;
694 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700695 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800696 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700697 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
698 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800699 continue;
700 }
701 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700702 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
703 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 continue;
705 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700706 final int uid = UserHandle.getUid(userId, app.uid);
707 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
708 if (LOGD)
709 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
710 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800711 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700712 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700713 if (LOGD)
714 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
715 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700716 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700717 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800718 }
719 }
720 return changed;
721 }
722
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800723 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700724 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800725 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800727 // Boost thread's priority during system server init
728 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700729 if (!isBandwidthControlEnabled()) {
730 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
731 return;
732 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700733
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700735 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700736
Felipe Leme873a83a2016-09-07 11:34:10 -0700737 synchronized (mUidRulesFirstLock) {
738 synchronized (mNetworkPoliciesSecondLock) {
739 updatePowerSaveWhitelistUL();
740 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
741 mPowerManagerInternal.registerLowPowerModeObserver(
742 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800743 @Override
744 public int getServiceType() {
745 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700746 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800747
748 @Override
749 public void onLowPowerModeChanged(PowerSaveState result) {
750 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800751 if (LOGD) {
752 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
753 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800754 synchronized (mUidRulesFirstLock) {
755 if (mRestrictPower != enabled) {
756 mRestrictPower = enabled;
757 updateRulesForRestrictPowerUL();
758 }
759 }
760 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800761 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800762 mRestrictPower = mPowerManagerInternal.getLowPowerState(
763 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700764
765 mSystemReady = true;
766
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800767 waitForAdminData();
768
Felipe Leme873a83a2016-09-07 11:34:10 -0700769 // read policy from disk
770 readPolicyAL();
771
jackqdyulei29c82ab2017-03-10 14:09:16 -0800772 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700773 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800774 mRestrictBackgroundPowerState = mPowerManagerInternal
775 .getLowPowerState(ServiceType.DATA_SAVER);
776 final boolean localRestrictBackground =
777 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700778 if (localRestrictBackground && !mLoadedRestrictBackground) {
779 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800780 }
781 mPowerManagerInternal.registerLowPowerModeObserver(
782 new PowerManagerInternal.LowPowerModeListener() {
783 @Override
784 public int getServiceType() {
785 return ServiceType.DATA_SAVER;
786 }
787
788 @Override
789 public void onLowPowerModeChanged(PowerSaveState result) {
790 synchronized (mUidRulesFirstLock) {
791 updateRestrictBackgroundByLowPowerModeUL(result);
792 }
793 }
794 });
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
797 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700798 }
Felipe Lemef0823852016-06-08 13:43:08 -0700799
Sudheer Shanka543339f2017-07-28 15:18:07 -0700800 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700801 updateRulesForGlobalChangeAL(false);
802 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700803 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800804 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700805
Sudheer Shankae7361852017-03-07 11:51:46 -0800806 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700807 try {
808 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000809 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700810 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700811 mNetworkManager.registerObserver(mAlertObserver);
812 } catch (RemoteException e) {
813 // ignored; both services live in system_server
814 }
815
816 // listen for changes to power save whitelist
817 final IntentFilter whitelistFilter = new IntentFilter(
818 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
819 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
820
Felipe Leme873a83a2016-09-07 11:34:10 -0700821 // watch for network interfaces to be claimed
822 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
823 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
824
825 // listen for package changes to update policy
826 final IntentFilter packageFilter = new IntentFilter();
827 packageFilter.addAction(ACTION_PACKAGE_ADDED);
828 packageFilter.addDataScheme("package");
829 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
830
831 // listen for UID changes to update policy
832 mContext.registerReceiver(
833 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
834
835 // listen for user changes to update policy
836 final IntentFilter userFilter = new IntentFilter();
837 userFilter.addAction(ACTION_USER_ADDED);
838 userFilter.addAction(ACTION_USER_REMOVED);
839 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
840
841 // listen for stats update events
842 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
843 mContext.registerReceiver(
844 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
845
846 // listen for restrict background changes from notifications
847 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
848 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
849
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700850 // Listen for snooze from notifications
851 mContext.registerReceiver(mSnoozeReceiver,
852 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
853 mContext.registerReceiver(mSnoozeReceiver,
854 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700855
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600856 // listen for configured wifi networks to be loaded
857 final IntentFilter wifiFilter =
858 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
859 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700860
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700861 // listen for carrier config changes to update data cycle information
862 final IntentFilter carrierConfigFilter = new IntentFilter(
863 ACTION_CARRIER_CONFIG_CHANGED);
864 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
865
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600866 // listen for meteredness changes
867 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
868 new NetworkRequest.Builder().build(), mNetworkCallback);
869
Felipe Leme873a83a2016-09-07 11:34:10 -0700870 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600871
872 // Listen for subscriber changes
873 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
874 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
875 @Override
876 public void onSubscriptionsChanged() {
877 updateNetworksInternal();
878 }
879 });
880
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800881 // tell systemReady() that the service has been initialized
882 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700883 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800884 // Restore the default priority after init is done
885 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700886 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700888 }
889
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800890 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700891 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800892 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
893 mHandler.post(() -> initService(initCompleteSignal));
894 return initCompleteSignal;
895 }
896
897 public void systemReady(CountDownLatch initCompleteSignal) {
898 // wait for initService to complete
899 try {
900 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
901 throw new IllegalStateException("Service " + TAG +" init timeout");
902 }
903 } catch (InterruptedException e) {
904 Thread.currentThread().interrupt();
905 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
906 }
907 }
908
Sudheer Shankac9d94072017-02-22 22:13:55 +0000909 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700910 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700911 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
912 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700913 }
914
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700915 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700916 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700917 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700918
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700919 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700920 }
921
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700922 @Override public void onUidIdle(int uid, boolean disabled) {
923 }
924
925 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700926 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700927 };
928
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700929 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700930 @Override
931 public void onReceive(Context context, Intent intent) {
932 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700933 synchronized (mUidRulesFirstLock) {
934 updatePowerSaveWhitelistUL();
935 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700936 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700937 }
938 }
939 };
940
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700942 @Override
943 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700944 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700945
946 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700947 final int uid = intent.getIntExtra(EXTRA_UID, -1);
948 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700949
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700950 if (ACTION_PACKAGE_ADDED.equals(action)) {
951 // update rules for UID, since it might be subject to
952 // global background data policy
953 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700954 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700955 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700956 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700957 }
958 }
959 };
960
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700961 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700962 @Override
963 public void onReceive(Context context, Intent intent) {
964 // on background handler thread, and UID_REMOVED is protected
965
966 final int uid = intent.getIntExtra(EXTRA_UID, -1);
967 if (uid == -1) return;
968
969 // remove any policy and update rules to clean up
970 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700971 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700972 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700973 synchronized (mNetworkPoliciesSecondLock) {
974 writePolicyAL();
975 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700976 }
977 }
978 };
979
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700980 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700981 @Override
982 public void onReceive(Context context, Intent intent) {
983 // on background handler thread, and USER_ADDED and USER_REMOVED
984 // broadcasts are protected
985
986 final String action = intent.getAction();
987 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
988 if (userId == -1) return;
989
Amith Yamasani15e472352015-04-24 19:06:07 -0700990 switch (action) {
991 case ACTION_USER_REMOVED:
992 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700993 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800994 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700995 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700996 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800997 // Removing outside removeUserStateUL since that can also be called when
998 // user resets app preferences.
999 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001000 if (action == ACTION_USER_ADDED) {
1001 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001002 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001003 }
1004 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001005 synchronized (mNetworkPoliciesSecondLock) {
1006 updateRulesForGlobalChangeAL(true);
1007 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001008 }
1009 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001010 }
1011 }
1012 };
1013
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001014 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015 * Receiver that watches for {@link INetworkStatsService} updates, which we
1016 * use to check against {@link NetworkPolicy#warningBytes}.
1017 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001018 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 @Override
1020 public void onReceive(Context context, Intent intent) {
1021 // on background handler thread, and verified
1022 // READ_NETWORK_USAGE_HISTORY permission above.
1023
Felipe Lemef0823852016-06-08 13:43:08 -07001024 synchronized (mNetworkPoliciesSecondLock) {
1025 updateNetworkEnabledNL();
1026 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 }
1028 }
1029 };
1030
1031 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001032 * Receiver that watches for {@link Notification} control of
1033 * {@link #mRestrictBackground}.
1034 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001035 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001036 @Override
1037 public void onReceive(Context context, Intent intent) {
1038 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1039 // permission above.
1040
1041 setRestrictBackground(false);
1042 }
1043 };
1044
1045 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001046 * Receiver that watches for {@link Notification} control of
1047 * {@link NetworkPolicy#lastWarningSnooze}.
1048 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001049 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001050 @Override
1051 public void onReceive(Context context, Intent intent) {
1052 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1053 // permission above.
1054
1055 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001056 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1057 performSnooze(template, TYPE_WARNING);
1058 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1059 performSnooze(template, TYPE_RAPID);
1060 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 }
1062 };
1063
1064 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001065 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001066 * we can perform upgrade logic. After initial upgrade logic, it updates
1067 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001068 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001069 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001070 @Override
1071 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001072 synchronized (mUidRulesFirstLock) {
1073 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001074 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001075 }
1076 }
1077 // Only need to perform upgrade logic once
1078 mContext.unregisterReceiver(this);
1079 }
1080 };
1081
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001082 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1083 Network network) {
1084 final boolean lastValue = lastValues.get(network.netId, false);
1085 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1086 if (changed) {
1087 lastValues.put(network.netId, newValue);
1088 }
1089 return changed;
1090 }
1091
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001092 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1093 @Override
1094 public void onCapabilitiesChanged(Network network,
1095 NetworkCapabilities networkCapabilities) {
1096 if (network == null || networkCapabilities == null) return;
1097
1098 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001099 final boolean newMetered = !networkCapabilities
1100 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001101 final boolean meteredChanged = updateCapabilityChange(
1102 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001103
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001104 final boolean newRoaming = !networkCapabilities
1105 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1106 final boolean roamingChanged = updateCapabilityChange(
1107 mNetworkRoaming, newRoaming, network);
1108
1109 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001110 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001111 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001112 }
1113 }
1114 }
1115 };
1116
1117 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 * Observer that watches for {@link INetworkManagementService} alerts.
1119 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001120 final private INetworkManagementEventObserver mAlertObserver
1121 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001122 @Override
1123 public void limitReached(String limitName, String iface) {
1124 // only someone like NMS should be calling us
1125 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1126
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001127 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1128 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 }
1130 }
1131 };
1132
1133 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1135 * to show visible notifications as needed.
1136 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001137 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001138 void updateNotificationsNL() {
1139 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001140 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001143 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145
1146 // TODO: when switching to kernel notifications, compute next future
1147 // cycle boundary to recompute notifications.
1148
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001149 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001150 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1152 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001153 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001154
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001156 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001157 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001158
Jeff Sharkey53313d72017-07-13 16:47:32 -06001159 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1160 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001161 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1162 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1163 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001165 // Carrier might want to manage notifications themselves
1166 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001167 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1168 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1169 // Don't show notifications until we confirm that the loaded config is from an
1170 // identified carrier, which may want to manage their own notifications. This method
1171 // should be called every time the carrier config changes anyways, and there's no
1172 // reason to alert if there isn't a carrier.
1173 return;
1174 }
1175
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001176 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1177 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1178 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1179 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1180 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1181 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1182
1183 // Notify when data usage is over warning
1184 if (notifyWarning) {
1185 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1186 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1187 if (!snoozedThisCycle) {
1188 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1189 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001191 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001193 // Notify when data usage is over limit
1194 if (notifyLimit) {
1195 if (policy.isOverLimit(totalBytes)) {
1196 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1197 if (snoozedThisCycle) {
1198 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1199 } else {
1200 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1201 notifyOverLimitNL(policy.template);
1202 }
1203 } else {
1204 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001205 }
1206 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001207
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 // Warn if average usage over last 4 days is on track to blow pretty
1209 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001210 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001211 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001212 final long recentStart = now - recentDuration;
1213 final long recentEnd = now;
1214 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001215
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001216 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001217 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001218 final long alertBytes = (policy.limitBytes * 3) / 2;
1219
1220 if (LOGD) {
1221 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1222 + projectedBytes + " alert " + alertBytes);
1223 }
1224
1225 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1226 - DateUtils.DAY_IN_MILLIS;
1227 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001228 enqueueNotification(policy, TYPE_RAPID, 0,
1229 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001230 }
1231 }
1232 }
1233
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001235 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001236 final NotificationId notificationId = beforeNotifs.valueAt(i);
1237 if (!mActiveNotifs.contains(notificationId)) {
1238 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 }
1240 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001241
1242 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001243 }
1244
1245 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 * Attempt to find a specific app to blame for rapid data usage during the
1247 * given time period.
1248 */
1249 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1250 long start, long end) {
1251 long totalBytes = 0;
1252 long maxBytes = 0;
1253 int maxUid = 0;
1254
1255 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1256 NetworkStats.Entry entry = null;
1257 for (int i = 0; i < stats.size(); i++) {
1258 entry = stats.getValues(i, entry);
1259 final long bytes = entry.rxBytes + entry.txBytes;
1260 totalBytes += bytes;
1261 if (bytes > maxBytes) {
1262 maxBytes = bytes;
1263 maxUid = entry.uid;
1264 }
1265 }
1266
1267 // Only point blame if the majority of usage was done by a single app.
1268 // TODO: support shared UIDs
1269 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1270 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001271 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001272 try {
1273 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1274 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1275 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1276 } catch (NameNotFoundException ignored) {
1277 }
1278 }
1279 }
1280
1281 return null;
1282 }
1283
1284 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001285 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001286 * current device state, such as when
1287 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1288 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001289 *
1290 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1291 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001292 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001293 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001294 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001295 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001296 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1297 final int subId = mSubIdToSubscriberId.keyAt(i);
1298 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001299 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1300 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1301 true);
1302 if (template.matches(probeIdent)) {
1303 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001304 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001305 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001306 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001307 }
1308
1309 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001310 * Notify that given {@link NetworkTemplate} is over
1311 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1312 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001313 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001314 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001316 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001317 mOverLimitNotified.add(template);
1318 }
1319 }
1320
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001321 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001322 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001323 mOverLimitNotified.remove(template);
1324 }
1325
1326 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 * Show notification for combined {@link NetworkPolicy} and specific type,
1328 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1329 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001330 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1331 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001332 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001333 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001334 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001335 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001336 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001337 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001338 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001339
1340 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001341 final CharSequence title;
1342 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001343 switch (type) {
1344 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001345 title = res.getText(R.string.data_usage_warning_title);
1346 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001347 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001349 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001350
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001351 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1352 builder.setDeleteIntent(PendingIntent.getBroadcast(
1353 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1354
Wei Liu546cb772016-07-21 16:19:01 -07001355 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001356 // TODO: Resolve to single code path.
1357 if (isHeadlessSystemUserBuild()) {
1358 builder.setContentIntent(PendingIntent.getActivityAsUser(
1359 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1360 /* options= */ null, UserHandle.CURRENT));
1361 } else {
1362 builder.setContentIntent(PendingIntent.getActivity(
1363 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1364 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001365 break;
1366 }
1367 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001368 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001369 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001370 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001371 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001372 case MATCH_WIFI:
1373 title = res.getText(R.string.data_usage_wifi_limit_title);
1374 break;
1375 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001376 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001377 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001378 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001379
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001380 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001381 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001382
Wei Liu546cb772016-07-21 16:19:01 -07001383 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001384 // TODO: Resolve to single code path.
1385 if (isHeadlessSystemUserBuild()) {
1386 builder.setContentIntent(PendingIntent.getActivityAsUser(
1387 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1388 /* options= */ null, UserHandle.CURRENT));
1389 } else {
1390 builder.setContentIntent(PendingIntent.getActivity(
1391 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1392 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001393 break;
1394 }
1395 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001396 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001397 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001398 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1399 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001400 case MATCH_WIFI:
1401 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1402 break;
1403 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001404 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001405 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001406 final long overBytes = totalBytes - policy.limitBytes;
1407 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001408 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001409
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001410 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001411 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001412 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001413
Wei Liu546cb772016-07-21 16:19:01 -07001414 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001415 // TODO: Resolve to single code path.
1416 if (isHeadlessSystemUserBuild()) {
1417 builder.setContentIntent(PendingIntent.getActivityAsUser(
1418 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1419 /* options= */ null, UserHandle.CURRENT));
1420 } else {
1421 builder.setContentIntent(PendingIntent.getActivity(
1422 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1423 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001424 break;
1425 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001426 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001427 title = res.getText(R.string.data_usage_rapid_title);
1428 if (rapidBlame != null) {
1429 body = res.getString(R.string.data_usage_rapid_app_body,
1430 rapidBlame.loadLabel(mContext.getPackageManager()));
1431 } else {
1432 body = res.getString(R.string.data_usage_rapid_body);
1433 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001434
Jeff Sharkey2e471452018-01-19 18:02:47 +09001435 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001436
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001437 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1438 builder.setDeleteIntent(PendingIntent.getBroadcast(
1439 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1440
1441 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001442 // TODO: Resolve to single code path.
1443 if (isHeadlessSystemUserBuild()) {
1444 builder.setContentIntent(PendingIntent.getActivityAsUser(
1445 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1446 /* options= */ null, UserHandle.CURRENT));
1447 } else {
1448 builder.setContentIntent(PendingIntent.getActivity(
1449 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1450 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001451 break;
1452 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001453 default: {
1454 return;
1455 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001456 }
1457
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001458 builder.setTicker(title);
1459 builder.setContentTitle(title);
1460 builder.setContentText(body);
1461 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001462
1463 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1464 notificationId.getId(), builder.build(), UserHandle.ALL);
1465 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001466 }
1467
Chris Wren193ae6b2017-03-31 15:17:11 -04001468 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001469 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1470 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001471 }
1472
1473 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001474 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001475 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001477 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478 @Override
1479 public void onReceive(Context context, Intent intent) {
1480 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1481 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001482 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483 }
1484 };
1485
Jeff Sharkey146bb332018-04-18 15:42:57 -06001486 private void updateNetworksInternal() {
1487 // Get all of our cross-process communication with telephony out of
1488 // the way before we acquire internal locks.
1489 updateSubscriptions();
1490
1491 synchronized (mUidRulesFirstLock) {
1492 synchronized (mNetworkPoliciesSecondLock) {
1493 ensureActiveMobilePolicyAL();
1494 normalizePoliciesNL();
1495 updateNetworkEnabledNL();
1496 updateNetworkRulesNL();
1497 updateNotificationsNL();
1498 }
1499 }
1500 }
1501
Jeff Sharkey2e471452018-01-19 18:02:47 +09001502 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001503 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001504 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001505 final CountDownLatch latch = new CountDownLatch(1);
1506 mHandler.post(() -> {
1507 latch.countDown();
1508 });
1509 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001510 }
1511
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001513 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1514 * if necessary.
1515 *
1516 * @param subId that has its associated NetworkPolicy updated if necessary
1517 * @return if any policies were updated
1518 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001519 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001520 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001521 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001522
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001523 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001524 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001525 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001526 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001527 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1528 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1529 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001530 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1531 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001532 }
1533 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001534 return policyUpdated;
1535 }
1536
1537 /**
1538 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1539 *
1540 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1541 * to do so, it returns the fallback value.
1542 *
1543 * @param config The CarrierConfig to read the value from.
1544 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1545 * @return cycleDay to use in the mobile NetworkPolicy.
1546 */
1547 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001548 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001549 int fallbackCycleDay) {
1550 if (config == null) {
1551 return fallbackCycleDay;
1552 }
1553 int cycleDay =
1554 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1555 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1556 return fallbackCycleDay;
1557 }
1558 // validate cycleDay value
1559 final Calendar cal = Calendar.getInstance();
1560 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1561 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1562 Slog.e(TAG, "Invalid date in "
1563 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1564 return fallbackCycleDay;
1565 }
1566 return cycleDay;
1567 }
1568
1569 /**
1570 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1571 *
1572 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1573 * to do so, it returns the fallback value.
1574 *
1575 * @param config The CarrierConfig to read the value from.
1576 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1577 * @return warningBytes to use in the mobile NetworkPolicy.
1578 */
1579 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001580 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001581 long fallbackWarningBytes) {
1582 if (config == null) {
1583 return fallbackWarningBytes;
1584 }
1585 long warningBytes =
1586 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1587
1588 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1589 return WARNING_DISABLED;
1590 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1591 return getPlatformDefaultWarningBytes();
1592 } else if (warningBytes < 0) {
1593 Slog.e(TAG, "Invalid value in "
1594 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1595 + "non-negative value but got: " + warningBytes);
1596 return fallbackWarningBytes;
1597 }
1598
1599 return warningBytes;
1600 }
1601
1602 /**
1603 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1604 *
1605 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1606 * to do so, it returns the fallback value.
1607 *
1608 * @param config The CarrierConfig to read the value from.
1609 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1610 * @return limitBytes to use in the mobile NetworkPolicy.
1611 */
1612 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001613 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001614 long fallbackLimitBytes) {
1615 if (config == null) {
1616 return fallbackLimitBytes;
1617 }
1618 long limitBytes =
1619 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1620
1621 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1622 return LIMIT_DISABLED;
1623 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1624 return getPlatformDefaultLimitBytes();
1625 } else if (limitBytes < 0) {
1626 Slog.e(TAG, "Invalid value in "
1627 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1628 + "non-negative value but got: " + limitBytes);
1629 return fallbackLimitBytes;
1630 }
1631 return limitBytes;
1632 }
1633
1634 /**
1635 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1636 */
1637 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1638 @Override
1639 public void onReceive(Context context, Intent intent) {
1640 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1641 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1642
1643 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1644 return;
1645 }
1646 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001647
1648 // Get all of our cross-process communication with telephony out of
1649 // the way before we acquire internal locks.
1650 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001651
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001652 synchronized (mUidRulesFirstLock) {
1653 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001654 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1655 if (subscriberId != null) {
1656 ensureActiveMobilePolicyAL(subId, subscriberId);
1657 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1658 } else {
1659 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1660 }
1661
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001662 // update network and notification rules, as the data cycle changed and it's
1663 // possible that we should be triggering warnings/limits now
1664 handleNetworkPoliciesUpdateAL(true);
1665 }
1666 }
1667 }
1668 };
1669
1670 /**
1671 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1672 * one has been updated.
1673 *
1674 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1675 * update.
1676 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001677 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001678 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1679 if (shouldNormalizePolicies) {
1680 normalizePoliciesNL();
1681 }
1682 updateNetworkEnabledNL();
1683 updateNetworkRulesNL();
1684 updateNotificationsNL();
1685 writePolicyAL();
1686 }
1687
1688 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001689 * Proactively control network data connections when they exceed
1690 * {@link NetworkPolicy#limitBytes}.
1691 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001692 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001693 void updateNetworkEnabledNL() {
1694 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001695 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001696
1697 // TODO: reset any policy-disabled networks when any policy is removed
1698 // completely, which is currently rare case.
1699
Makoto Onuki49392d32018-04-11 13:51:02 -07001700 final long startTime = mStatLogger.getTime();
1701
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001702 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1703 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001704 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001705 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001706 setNetworkTemplateEnabled(policy.template, true);
1707 continue;
1708 }
1709
Jeff Sharkey53313d72017-07-13 16:47:32 -06001710 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1711 .cycleIterator(policy).next();
1712 final long start = cycle.first.toInstant().toEpochMilli();
1713 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001714 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001715
1716 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001717 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1718 && policy.lastLimitSnooze < start;
1719 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001720
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001721 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001722 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001723
1724 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001725 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001726 }
1727
1728 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001729 * Proactively disable networks that match the given
1730 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001731 */
1732 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001733 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1734 // held. Call it via the handler.
1735 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1736 .sendToTarget();
1737 }
1738
1739 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001740 // TODO: reach into ConnectivityManager to proactively disable bringing
1741 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001742
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001743 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001744 // If mobile data usage hits the limit or if the user resumes the data, we need to
1745 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001746
Jeff Sharkey146bb332018-04-18 15:42:57 -06001747 final IntArray matchingSubIds = new IntArray();
1748 synchronized (mNetworkPoliciesSecondLock) {
1749 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1750 final int subId = mSubIdToSubscriberId.keyAt(i);
1751 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1752
1753 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1754 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1755 true);
1756 // Template is matched when subscriber id matches.
1757 if (template.matches(probeIdent)) {
1758 matchingSubIds.add(subId);
1759 }
Jack Yu8781b682016-07-08 14:28:51 -07001760 }
1761 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001762
1763 // Only talk with telephony outside of locks
1764 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1765 for (int i = 0; i < matchingSubIds.size(); i++) {
1766 final int subId = matchingSubIds.get(i);
1767 tm.setPolicyDataEnabled(enabled, subId);
1768 }
Jack Yu8781b682016-07-08 14:28:51 -07001769 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001770 }
1771
1772 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001773 * Collect all ifaces from a {@link NetworkState} into the given set.
1774 */
1775 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1776 final String baseIface = state.linkProperties.getInterfaceName();
1777 if (baseIface != null) {
1778 ifaces.add(baseIface);
1779 }
1780 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1781 final String stackedIface = stackedLink.getInterfaceName();
1782 if (stackedIface != null) {
1783 ifaces.add(stackedIface);
1784 }
1785 }
1786 }
1787
1788 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001789 * Examine all currently active subscriptions from
1790 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1791 * internal data structures.
1792 * <p>
1793 * Callers <em>must not</em> hold any locks when this method called.
1794 */
1795 void updateSubscriptions() {
1796 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1797 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1798
1799 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1800 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1801
1802 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001803 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001804
1805 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1806 for (int subId : subIds) {
1807 final String subscriberId = tm.getSubscriberId(subId);
1808 if (!TextUtils.isEmpty(subscriberId)) {
1809 subIdToSubscriberId.put(subId, subscriberId);
1810 } else {
1811 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1812 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001813
1814 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1815 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1816 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001817 }
1818
1819 synchronized (mNetworkPoliciesSecondLock) {
1820 mSubIdToSubscriberId.clear();
1821 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1822 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1823 subIdToSubscriberId.valueAt(i));
1824 }
1825
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001826 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001827 }
1828
1829 Trace.traceEnd(TRACE_TAG_NETWORK);
1830 }
1831
1832 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001833 * Examine all connected {@link NetworkState}, looking for
1834 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1835 * remaining quota based on usage cycle and historical stats.
1836 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001837 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001838 void updateNetworkRulesNL() {
1839 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001840 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001841
1842 final NetworkState[] states;
1843 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001844 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001845 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001846 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001847 return;
1848 }
1849
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001850 // First, generate identities of all connected networks so we can
1851 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001852 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001853 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001854 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001855 if (state.network != null) {
1856 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1857 }
Wei Liub8eaf452016-01-25 10:32:27 -08001858 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001859 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1860 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001861 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001862 }
1863 }
1864
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001865 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001866 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001867
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001868 // For every well-defined policy, compute remaining data based on
1869 // current cycle and historical stats, and push to kernel.
1870 final ArraySet<String> matchingIfaces = new ArraySet<>();
1871 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1872 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1873
1874 // Collect all ifaces that match this policy
1875 matchingIfaces.clear();
1876 for (int j = identified.size() - 1; j >= 0; j--) {
1877 if (policy.template.matches(identified.valueAt(j))) {
1878 collectIfaces(matchingIfaces, identified.keyAt(j));
1879 }
1880 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001881
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001882 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001883 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001884 }
1885
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001886 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001887 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001888 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001889 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001890 if (hasLimit && policy.hasCycle()) {
1891 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1892 .cycleIterator(policy).next();
1893 final long start = cycle.first.toInstant().toEpochMilli();
1894 final long end = cycle.second.toInstant().toEpochMilli();
1895 final long totalBytes = getTotalBytes(policy.template, start, end);
1896
1897 if (policy.lastLimitSnooze >= start) {
1898 // snoozing past quota, but we still need to restrict apps,
1899 // so push really high quota.
1900 quotaBytes = Long.MAX_VALUE;
1901 } else {
1902 // remaining "quota" bytes are based on total usage in
1903 // current cycle. kernel doesn't like 0-byte rules, so we
1904 // set 1-byte quota and disable the radio later.
1905 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1906 }
1907 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001908 // metered network, but no policy limit; we still need to
1909 // restrict apps, so push really high quota.
1910 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001911 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001912
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001913 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001914 // TODO: switch to shared quota once NMS supports
1915 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001916 }
1917
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001918 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1919 final String iface = matchingIfaces.valueAt(j);
1920 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001921 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001922 }
1923 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001924
1925 // keep track of lowest warning or limit of active policies
1926 if (hasWarning && policy.warningBytes < lowestRule) {
1927 lowestRule = policy.warningBytes;
1928 }
1929 if (hasLimit && policy.limitBytes < lowestRule) {
1930 lowestRule = policy.limitBytes;
1931 }
1932 }
1933
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001934 // One final pass to catch any metered ifaces that don't have explicitly
1935 // defined policies; typically Wi-Fi networks.
1936 for (NetworkState state : states) {
1937 if (state.networkInfo != null && state.networkInfo.isConnected()
1938 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1939 matchingIfaces.clear();
1940 collectIfaces(matchingIfaces, state);
1941 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1942 final String iface = matchingIfaces.valueAt(j);
1943 if (!newMeteredIfaces.contains(iface)) {
1944 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1945 newMeteredIfaces.add(iface);
1946 }
1947 }
1948 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001949 }
1950
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001951 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001952 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1953 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001954 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001955 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001956 }
1957 }
1958 mMeteredIfaces = newMeteredIfaces;
1959
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001960 final ContentResolver cr = mContext.getContentResolver();
1961 final boolean quotaEnabled = Settings.Global.getInt(cr,
1962 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1963 final long quotaUnlimited = Settings.Global.getLong(cr,
1964 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1965 final float quotaLimited = Settings.Global.getFloat(cr,
1966 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1967
Jeff Sharkey9252b342018-01-19 07:58:35 +09001968 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001969 mSubscriptionOpportunisticQuota.clear();
1970 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001971 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001972 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001973 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001974 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001975 if (plan == null) continue;
1976
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001977 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001978 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001979 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1980 // Clamp to 0 when roaming
1981 quotaBytes = 0;
1982 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001983 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001984 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001985 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001986 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001987 } else {
1988 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001989 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1990 final long start = cycle.getLower().toInstant().toEpochMilli();
1991 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001992 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001993 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001994 .truncatedTo(ChronoUnit.DAYS)
1995 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001996 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001997 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1998 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001999 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002000 // Number of remaining days including current day
2001 final long remainingDays =
2002 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002003
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002004 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002005 }
2006
2007 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2008 }
2009
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002010 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002011 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002012
2013 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002014
2015 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002016 }
2017
2018 /**
2019 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2020 * have at least a default mobile policy defined.
2021 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002022 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002023 private void ensureActiveMobilePolicyAL() {
2024 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002025 if (mSuppressDefaultPolicy) return;
2026
Jeff Sharkey146bb332018-04-18 15:42:57 -06002027 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2028 final int subId = mSubIdToSubscriberId.keyAt(i);
2029 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002030
Hugo Benichi446c9c92017-04-10 09:41:10 +09002031 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002032 }
2033 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002034
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002035 /**
2036 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2037 * have at least a default mobile policy defined.
2038 *
2039 * @param subId to build a default policy for
2040 * @param subscriberId that we check for an existing policy
2041 * @return true if a mobile network policy was added, or false one already existed.
2042 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002043 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002044 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002045 // Poke around to see if we already have a policy
2046 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002047 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002048 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2049 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2050 if (template.matches(probeIdent)) {
2051 if (LOGD) {
2052 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2053 + NetworkIdentity.scrubSubscriberId(subscriberId));
2054 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002055 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002056 }
2057 }
2058
Jeff Sharkey32566012014-12-02 18:30:14 -08002059 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2060 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002061 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002062 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002063 return true;
2064 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002065
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002066 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002067 final int dataWarningConfig = mContext.getResources().getInteger(
2068 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002069 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002070 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002071 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002072 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002073 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002074 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002075
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002076 private long getPlatformDefaultLimitBytes() {
2077 return LIMIT_DISABLED;
2078 }
2079
2080 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002081 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002082 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002083 final RecurrenceRule cycleRule = NetworkPolicy
2084 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002085 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002086 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2087 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2088 synchronized (mUidRulesFirstLock) {
2089 synchronized (mNetworkPoliciesSecondLock) {
2090 updateDefaultMobilePolicyAL(subId, policy);
2091 }
2092 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002093 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002094 }
2095
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002096 /**
2097 * Update the given {@link NetworkPolicy} based on any carrier-provided
2098 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2099 * Leaves policy untouched if the user has modified it.
2100 *
2101 * @return if the policy was modified
2102 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002103 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002104 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2105 if (!policy.inferred) {
2106 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2107 return false;
2108 }
2109
2110 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2111 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2112 policy.lastLimitSnooze, policy.metered, policy.inferred);
2113
2114 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2115 if (!ArrayUtils.isEmpty(plans)) {
2116 final SubscriptionPlan plan = plans[0];
2117 policy.cycleRule = plan.getCycleRule();
2118 final long planLimitBytes = plan.getDataLimitBytes();
2119 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2120 policy.warningBytes = getPlatformDefaultWarningBytes();
2121 policy.limitBytes = getPlatformDefaultLimitBytes();
2122 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2123 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2124 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2125 } else {
2126 policy.warningBytes = (planLimitBytes * 9) / 10;
2127 switch (plan.getDataLimitBehavior()) {
2128 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2129 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2130 policy.limitBytes = planLimitBytes;
2131 break;
2132 default:
2133 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2134 break;
2135 }
2136 }
2137 } else {
2138 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2139 final int currentCycleDay;
2140 if (policy.cycleRule.isMonthly()) {
2141 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2142 } else {
2143 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2144 }
2145 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2146 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2147 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2148 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2149 }
2150
2151 if (policy.equals(original)) {
2152 return false;
2153 } else {
2154 Slog.d(TAG, "Updated " + original + " to " + policy);
2155 return true;
2156 }
2157 }
2158
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002159 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002160 private void readPolicyAL() {
2161 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002162
2163 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002164 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002165 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002166 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002167 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002168
2169 FileInputStream fis = null;
2170 try {
2171 fis = mPolicyFile.openRead();
2172 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002173 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002174
Felipe Leme46b451f2016-08-19 08:46:17 -07002175 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2176 // to skip UIDs that were explicitly blacklisted.
2177 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2178
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002180 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002181 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002182 while ((type = in.next()) != END_DOCUMENT) {
2183 final String tag = in.getName();
2184 if (type == START_TAG) {
2185 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002186 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002188 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2189 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002190 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2191 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2192 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002193 final String networkId;
2194 if (version >= VERSION_ADDED_NETWORK_ID) {
2195 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2196 } else {
2197 networkId = null;
2198 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002199 final RecurrenceRule cycleRule;
2200 if (version >= VERSION_ADDED_CYCLE) {
2201 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2202 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2203 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2204 cycleRule = new RecurrenceRule(
2205 RecurrenceRule.convertZonedDateTime(start),
2206 RecurrenceRule.convertZonedDateTime(end),
2207 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002208 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002209 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2210 final String cycleTimezone;
2211 if (version >= VERSION_ADDED_TIMEZONE) {
2212 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2213 } else {
2214 cycleTimezone = "UTC";
2215 }
2216 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002217 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002218 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2219 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002220 final long lastLimitSnooze;
2221 if (version >= VERSION_SPLIT_SNOOZE) {
2222 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2223 } else if (version >= VERSION_ADDED_SNOOZE) {
2224 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002225 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002226 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002227 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002228 final boolean metered;
2229 if (version >= VERSION_ADDED_METERED) {
2230 metered = readBooleanAttribute(in, ATTR_METERED);
2231 } else {
2232 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002233 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002234 metered = true;
2235 break;
2236 default:
2237 metered = false;
2238 }
2239 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002240 final long lastWarningSnooze;
2241 if (version >= VERSION_SPLIT_SNOOZE) {
2242 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2243 } else {
2244 lastWarningSnooze = SNOOZE_NEVER;
2245 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002246 final boolean inferred;
2247 if (version >= VERSION_ADDED_INFERRED) {
2248 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2249 } else {
2250 inferred = false;
2251 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002252
Jeff Sharkey32566012014-12-02 18:30:14 -08002253 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2254 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002255 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002256 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2257 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002258 lastLimitSnooze, metered, inferred));
2259 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002260
2261 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2262 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2263 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2264 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2265 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2266 RecurrenceRule.convertZonedDateTime(start),
2267 RecurrenceRule.convertZonedDateTime(end),
2268 RecurrenceRule.convertPeriod(period));
2269 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2270 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2271
2272 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2273 SubscriptionPlan.BYTES_UNKNOWN);
2274 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2275 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2276 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2277 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2278 builder.setDataLimit(limitBytes, limitBehavior);
2279 }
2280
2281 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2282 SubscriptionPlan.BYTES_UNKNOWN);
2283 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2284 SubscriptionPlan.TIME_UNKNOWN);
2285 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2286 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2287 builder.setDataUsage(usageBytes, usageTime);
2288 }
2289
2290 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2291 final SubscriptionPlan plan = builder.build();
2292 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2293 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2294
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002295 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2296 mSubscriptionPlansOwner.put(subId, ownerPackage);
2297
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002298 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002299 final int uid = readIntAttribute(in, ATTR_UID);
2300 final int policy = readIntAttribute(in, ATTR_POLICY);
2301
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002302 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002303 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002304 } else {
2305 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2306 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002307 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002308 final int appId = readIntAttribute(in, ATTR_APP_ID);
2309 final int policy = readIntAttribute(in, ATTR_POLICY);
2310
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002312 // app policy is deprecated so this is only used in pre system user split.
2313 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002314 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002315 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002316 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002318 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002319 } else if (TAG_WHITELIST.equals(tag)) {
2320 insideWhitelist = true;
2321 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2322 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002323 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002324 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2325 final int uid = readIntAttribute(in, ATTR_UID);
2326 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002327 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002328 } else if (type == END_TAG) {
2329 if (TAG_WHITELIST.equals(tag)) {
2330 insideWhitelist = false;
2331 }
2332
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002333 }
2334 }
2335
Felipe Leme46b451f2016-08-19 08:46:17 -07002336 final int size = whitelistedRestrictBackground.size();
2337 for (int i = 0; i < size; i++) {
2338 final int uid = whitelistedRestrictBackground.keyAt(i);
2339 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2340 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2341 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2342 + " because its policy is " + uidPoliciesToString(policy));
2343 continue;
2344 }
2345 if (UserHandle.isApp(uid)) {
2346 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2347 if (LOGV)
2348 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2349 setUidPolicyUncheckedUL(uid, newPolicy, false);
2350 } else {
2351 Slog.w(TAG, "unable to update policy on UID " + uid);
2352 }
2353 }
2354
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002355 } catch (FileNotFoundException e) {
2356 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002357 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002358 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002359 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002360 } finally {
2361 IoUtils.closeQuietly(fis);
2362 }
2363 }
2364
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002365 /**
2366 * Upgrade legacy background data flags, notifying listeners of one last
2367 * change to always-true.
2368 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002369 private void upgradeDefaultBackgroundDataUL() {
2370 // This method is only called when we're unable to find the network policy flag, which
2371 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002372
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002373 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002374 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002375 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2376
2377 // NOTE: We used to read the legacy setting here :
2378 //
2379 // final int legacyFlagValue = Settings.Secure.getInt(
2380 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2381 //
2382 // This is no longer necessary because we will never upgrade directly from Gingerbread
2383 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2384 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002385 }
2386
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002387 /**
2388 * Perform upgrade step of moving any user-defined meterness overrides over
2389 * into {@link WifiConfiguration}.
2390 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002391 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002392 private void upgradeWifiMeteredOverrideAL() {
2393 boolean modified = false;
2394 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2395 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2396 for (int i = 0; i < mNetworkPolicy.size(); ) {
2397 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2398 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2399 && !policy.inferred) {
2400 mNetworkPolicy.removeAt(i);
2401 modified = true;
2402
2403 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2404 for (WifiConfiguration config : configs) {
2405 if (Objects.equals(resolveNetworkId(config), networkId)) {
2406 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2407 config.meteredOverride = policy.metered
2408 ? WifiConfiguration.METERED_OVERRIDE_METERED
2409 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2410 wm.updateNetwork(config);
2411 }
2412 }
2413 } else {
2414 i++;
2415 }
2416 }
2417 if (modified) {
2418 writePolicyAL();
2419 }
2420 }
2421
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002422 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002423 void writePolicyAL() {
2424 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002425
2426 FileOutputStream fos = null;
2427 try {
2428 fos = mPolicyFile.startWrite();
2429
2430 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002431 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002432 out.startDocument(null, true);
2433
2434 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002435 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002436 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002437
2438 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002439 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2440 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002441 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002442 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002443
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002444 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002445 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2446 final String subscriberId = template.getSubscriberId();
2447 if (subscriberId != null) {
2448 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002449 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002450 final String networkId = template.getNetworkId();
2451 if (networkId != null) {
2452 out.attribute(null, ATTR_NETWORK_ID, networkId);
2453 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002454 writeStringAttribute(out, ATTR_CYCLE_START,
2455 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2456 writeStringAttribute(out, ATTR_CYCLE_END,
2457 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2458 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2459 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002460 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2461 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002462 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2463 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002464 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002465 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002466 out.endTag(null, TAG_NETWORK_POLICY);
2467 }
2468
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002469 // write all known subscription plans
2470 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2471 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002472 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002473 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2474 if (ArrayUtils.isEmpty(plans)) continue;
2475
2476 for (SubscriptionPlan plan : plans) {
2477 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2478 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002479 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002480 final RecurrenceRule cycleRule = plan.getCycleRule();
2481 writeStringAttribute(out, ATTR_CYCLE_START,
2482 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2483 writeStringAttribute(out, ATTR_CYCLE_END,
2484 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2485 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2486 RecurrenceRule.convertPeriod(cycleRule.period));
2487 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2488 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2489 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2490 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2491 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2492 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2493 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2494 }
2495 }
2496
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002497 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002498 for (int i = 0; i < mUidPolicy.size(); i++) {
2499 final int uid = mUidPolicy.keyAt(i);
2500 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002501
Jeff Sharkey497e4432011-06-14 17:27:29 -07002502 // skip writing empty policies
2503 if (policy == POLICY_NONE) continue;
2504
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002505 out.startTag(null, TAG_UID_POLICY);
2506 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002508 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002509 }
2510
2511 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002512
2513 // write all whitelists
2514 out.startTag(null, TAG_WHITELIST);
2515
Felipe Lemea9505cc2016-02-26 10:28:41 -08002516 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002517 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002518 for (int i = 0; i < size; i++) {
2519 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2520 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2521 writeIntAttribute(out, ATTR_UID, uid);
2522 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2523 }
2524
Felipe Lemeb85a6372016-01-14 16:16:16 -08002525 out.endTag(null, TAG_WHITELIST);
2526
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002527 out.endDocument();
2528
2529 mPolicyFile.finishWrite(fos);
2530 } catch (IOException e) {
2531 if (fos != null) {
2532 mPolicyFile.failWrite(fos);
2533 }
2534 }
2535 }
2536
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002537 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002538 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002539 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002540
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002541 if (!UserHandle.isApp(uid)) {
2542 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002543 }
Felipe Lemef0823852016-06-08 13:43:08 -07002544 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002545 final long token = Binder.clearCallingIdentity();
2546 try {
2547 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2548 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002549 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002550 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002554 }
2555 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002556 }
2557
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002558 @Override
2559 public void addUidPolicy(int uid, int policy) {
2560 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002561
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002562 if (!UserHandle.isApp(uid)) {
2563 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2564 }
2565
Felipe Lemef0823852016-06-08 13:43:08 -07002566 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002567 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2568 policy |= oldPolicy;
2569 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002570 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002571 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002572 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002573 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002574 }
2575
2576 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002577 public void removeUidPolicy(int uid, int policy) {
2578 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2579
2580 if (!UserHandle.isApp(uid)) {
2581 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2582 }
2583
Felipe Lemef0823852016-06-08 13:43:08 -07002584 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002585 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2586 policy = oldPolicy & ~policy;
2587 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002588 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002589 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002590 }
2591 }
2592 }
2593
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002594 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002595 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002596 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002597
Felipe Leme57e3d312016-08-23 14:42:52 -07002598 final boolean notifyApp;
2599 if (!isUidValidForWhitelistRules(uid)) {
2600 notifyApp = false;
2601 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002602 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2603 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2604 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2605 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002606 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2607 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002608 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2609 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2610 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2611 if (LOGD)
2612 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2613 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2614 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002615 notifyApp = wasBlocked != isBlocked;
2616 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002617 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2618 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002619 if (persist) {
2620 synchronized (mNetworkPoliciesSecondLock) {
2621 writePolicyAL();
2622 }
2623 }
Felipe Leme923845f2016-03-02 13:42:48 -08002624 }
2625
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002626 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002627 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002628 if (policy == POLICY_NONE) {
2629 mUidPolicy.delete(uid);
2630 } else {
2631 mUidPolicy.put(uid, policy);
2632 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002633
2634 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002635 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002636 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002637 synchronized (mNetworkPoliciesSecondLock) {
2638 writePolicyAL();
2639 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002640 }
2641 }
2642
2643 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002644 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002645 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2646
Felipe Lemef0823852016-06-08 13:43:08 -07002647 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002648 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002649 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002650 }
2651
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002652 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002653 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002654 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2655
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002656 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002657 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002658 for (int i = 0; i < mUidPolicy.size(); i++) {
2659 final int uid = mUidPolicy.keyAt(i);
2660 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002661 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2662 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002663 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002664 }
2665 }
2666 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002667 return uids;
2668 }
2669
2670 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002671 * Removes any persistable state associated with given {@link UserHandle}, persisting
2672 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002673 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002674 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002675 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002676
Sudheer Shanka352dc572017-09-22 17:09:38 -07002677 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002678 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002679
Felipe Lemea110eec2016-04-29 09:58:06 -07002680 // Remove entries from revoked default restricted background UID whitelist
2681 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2682 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2683 if (UserHandle.getUserId(uid) == userId) {
2684 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002685 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002686 }
2687 }
2688
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002689 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002690 int[] uids = new int[0];
2691 for (int i = 0; i < mUidPolicy.size(); i++) {
2692 final int uid = mUidPolicy.keyAt(i);
2693 if (UserHandle.getUserId(uid) == userId) {
2694 uids = appendInt(uids, uid);
2695 }
2696 }
2697
2698 if (uids.length > 0) {
2699 for (int uid : uids) {
2700 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002701 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002702 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002703 }
Felipe Lemef0823852016-06-08 13:43:08 -07002704 synchronized (mNetworkPoliciesSecondLock) {
2705 updateRulesForGlobalChangeAL(true);
2706 if (writePolicy && changed) {
2707 writePolicyAL();
2708 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002709 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002710 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002711 }
2712
2713 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002714 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002715 // TODO: create permission for observing network policy
2716 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002717 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002718 }
2719
2720 @Override
2721 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002722 // TODO: create permission for observing network policy
2723 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002724 mListeners.unregister(listener);
2725 }
2726
Jeff Sharkey1b861272011-05-22 00:34:52 -07002727 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002728 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002729 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2730
Felipe Leme6a05eee2016-02-19 14:43:51 -08002731 final long token = Binder.clearCallingIdentity();
2732 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002733 synchronized (mUidRulesFirstLock) {
2734 synchronized (mNetworkPoliciesSecondLock) {
2735 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002736 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002737 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002738 }
2739 } finally {
2740 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002741 }
2742 }
2743
Hugo Benichi446c9c92017-04-10 09:41:10 +09002744 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002745 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002746 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2747 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002748 }
2749
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002750 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002751 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002752 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002753 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002754 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2755 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2756 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002757 } catch (SecurityException e) {
2758 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002759
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002760 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2761 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2762 return new NetworkPolicy[0];
2763 }
Svet Ganov16a16892015-04-16 10:32:04 -07002764 }
2765
Felipe Lemef0823852016-06-08 13:43:08 -07002766 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002767 final int size = mNetworkPolicy.size();
2768 final NetworkPolicy[] policies = new NetworkPolicy[size];
2769 for (int i = 0; i < size; i++) {
2770 policies[i] = mNetworkPolicy.valueAt(i);
2771 }
2772 return policies;
2773 }
2774 }
2775
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002776 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002777 private void normalizePoliciesNL() {
2778 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002779 }
2780
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002781 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002782 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002783 mNetworkPolicy.clear();
2784 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002785 if (policy == null) {
2786 continue;
2787 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002788 // When two normalized templates conflict, prefer the most
2789 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002790 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002791 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2792 if (existing == null || existing.compareTo(policy) > 0) {
2793 if (existing != null) {
2794 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2795 }
2796 mNetworkPolicy.put(policy.template, policy);
2797 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002798 }
2799 }
2800
2801 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002802 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002803 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002804
2805 final long token = Binder.clearCallingIdentity();
2806 try {
2807 performSnooze(template, TYPE_LIMIT);
2808 } finally {
2809 Binder.restoreCallingIdentity(token);
2810 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002811 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002812
Dianne Hackborn497175b2014-07-01 12:56:08 -07002813 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002814 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002815 synchronized (mUidRulesFirstLock) {
2816 synchronized (mNetworkPoliciesSecondLock) {
2817 // find and snooze local policy that matches
2818 final NetworkPolicy policy = mNetworkPolicy.get(template);
2819 if (policy == null) {
2820 throw new IllegalArgumentException("unable to find policy for " + template);
2821 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002822
Felipe Lemef0823852016-06-08 13:43:08 -07002823 switch (type) {
2824 case TYPE_WARNING:
2825 policy.lastWarningSnooze = currentTime;
2826 break;
2827 case TYPE_LIMIT:
2828 policy.lastLimitSnooze = currentTime;
2829 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002830 case TYPE_RAPID:
2831 policy.lastRapidSnooze = currentTime;
2832 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002833 default:
2834 throw new IllegalArgumentException("unexpected type");
2835 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002836
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002837 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002838 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002839 }
2840 }
2841
2842 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002843 public void onTetheringChanged(String iface, boolean tethering) {
2844 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002845 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002846 if (mRestrictBackground && tethering) {
2847 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2848 setRestrictBackground(false);
2849 }
2850 }
2851 }
2852
2853 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002854 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002855 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002856 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002857 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2858 final long token = Binder.clearCallingIdentity();
2859 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002860 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002861 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002862 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002863 } finally {
2864 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002865 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002866 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002867 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002868 }
2869 }
2870
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002871 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002872 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002873 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002874 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002875 if (restrictBackground == mRestrictBackground) {
2876 // Ideally, UI should never allow this scenario...
2877 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002878 return;
2879 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002880 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2881 final boolean oldRestrictBackground = mRestrictBackground;
2882 mRestrictBackground = restrictBackground;
2883 // Must whitelist foreground apps before turning data saver mode on.
2884 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2885 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2886 updateRulesForRestrictBackgroundUL();
2887 try {
2888 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2889 Slog.e(TAG,
2890 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2891 mRestrictBackground = oldRestrictBackground;
2892 // TODO: if it knew the foreground apps (see TODO above), it could call
2893 // updateRulesForRestrictBackgroundUL() again to restore state.
2894 return;
2895 }
2896 } catch (RemoteException e) {
2897 // ignored; service lives in system_server
2898 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002899
Sudheer Shanka543339f2017-07-28 15:18:07 -07002900 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002901 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002902
2903 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2904 mRestrictBackgroundChangedInBsm = true;
2905 }
2906 synchronized (mNetworkPoliciesSecondLock) {
2907 updateNotificationsNL();
2908 writePolicyAL();
2909 }
2910 } finally {
2911 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002912 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002913 }
2914
2915 private void sendRestrictBackgroundChangedMsg() {
2916 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2917 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2918 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002919 }
2920
Felipe Lemeb85a6372016-01-14 16:16:16 -08002921 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002922 public int getRestrictBackgroundByCaller() {
2923 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2924 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002925
Felipe Lemef0823852016-06-08 13:43:08 -07002926 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002927 // Must clear identity because getUidPolicy() is restricted to system.
2928 final long token = Binder.clearCallingIdentity();
2929 final int policy;
2930 try {
2931 policy = getUidPolicy(uid);
2932 } finally {
2933 Binder.restoreCallingIdentity(token);
2934 }
2935 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2936 // App is blacklisted.
2937 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2938 }
Felipe Leme1b103232016-01-22 09:44:57 -08002939 if (!mRestrictBackground) {
2940 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2941 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002942 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002943 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2944 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2945 }
2946 }
2947
2948 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002949 public boolean getRestrictBackground() {
2950 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2951
Felipe Lemef0823852016-06-08 13:43:08 -07002952 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002953 return mRestrictBackground;
2954 }
2955 }
2956
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002957 @Override
2958 public void setDeviceIdleMode(boolean enabled) {
2959 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002960 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2961 try {
2962 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002963 if (mDeviceIdleMode == enabled) {
2964 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002965 }
Felipe Lemeea014392016-09-06 13:59:54 -07002966 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002967 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002968 if (mSystemReady) {
2969 // Device idle change means we need to rebuild rules for all
2970 // known apps, so do a global refresh.
2971 updateRulesForRestrictPowerUL();
2972 }
2973 }
2974 if (enabled) {
2975 EventLogTags.writeDeviceIdleOnPhase("net");
2976 } else {
2977 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002978 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002979 } finally {
2980 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002981 }
2982 }
2983
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002984 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002985 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2986 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002987 final long token = Binder.clearCallingIdentity();
2988 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002989 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2990 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2991 for (WifiConfiguration config : configs) {
2992 if (Objects.equals(resolveNetworkId(config), networkId)) {
2993 config.meteredOverride = meteredOverride;
2994 wm.updateNetwork(config);
2995 }
2996 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002997 } finally {
2998 Binder.restoreCallingIdentity(token);
2999 }
3000 }
3001
Jeff Sharkey46645002011-07-27 21:11:21 -07003002 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003003 @Deprecated
3004 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3005 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3006 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3007 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003008 }
3009
Jeff Sharkey53313d72017-07-13 16:47:32 -06003010 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3011 // Verify they're not lying about package name
3012 mAppOps.checkPackage(callingUid, callingPackage);
3013
Jeff Sharkey53313d72017-07-13 16:47:32 -06003014 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003015 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003016 final long token = Binder.clearCallingIdentity();
3017 try {
3018 si = mContext.getSystemService(SubscriptionManager.class)
3019 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003020 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003021 } finally {
3022 Binder.restoreCallingIdentity(token);
3023 }
3024
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003025 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003026 if (si != null) {
3027 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3028 return;
3029 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003030 }
3031
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003032 // Second check: has the CarrierService delegated access?
3033 if (config != null) {
3034 final String overridePackage = config
3035 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3036 if (!TextUtils.isEmpty(overridePackage)
3037 && Objects.equals(overridePackage, callingPackage)) {
3038 return;
3039 }
3040 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003041
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003042 // Third check: is caller the fallback/default CarrierService?
3043 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3044 if (!TextUtils.isEmpty(defaultPackage)
3045 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003046 return;
3047 }
3048
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003049 // Fourth check: is caller a testing app?
3050 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3051 if (!TextUtils.isEmpty(testPackage)
3052 && Objects.equals(testPackage, callingPackage)) {
3053 return;
3054 }
3055
3056 // Fifth check: is caller a legacy testing app?
3057 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3058 if (!TextUtils.isEmpty(legacyTestPackage)
3059 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003060 return;
3061 }
3062
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003063 // Final check: does the caller hold a permission?
3064 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003065 }
3066
3067 @Override
3068 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3069 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3070
Jeff Sharkey53313d72017-07-13 16:47:32 -06003071 final String fake = SystemProperties.get("fw.fake_plan");
3072 if (!TextUtils.isEmpty(fake)) {
3073 final List<SubscriptionPlan> plans = new ArrayList<>();
3074 if ("month_hard".equals(fake)) {
3075 plans.add(SubscriptionPlan.Builder
3076 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3077 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003078 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3079 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3080 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3081 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3082 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003083 plans.add(SubscriptionPlan.Builder
3084 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3085 .setTitle("G-Mobile Happy")
3086 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3087 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3088 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3089 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3090 .build());
3091 plans.add(SubscriptionPlan.Builder
3092 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3093 .setTitle("G-Mobile, Charged after limit")
3094 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3095 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3096 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3097 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3098 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003099 } else if ("month_soft".equals(fake)) {
3100 plans.add(SubscriptionPlan.Builder
3101 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3102 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3103 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3104 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003105 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3106 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3107 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3108 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3109 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003110 plans.add(SubscriptionPlan.Builder
3111 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3112 .setTitle("G-Mobile, Throttled after limit")
3113 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3114 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3115 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3116 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3117 .build());
3118 plans.add(SubscriptionPlan.Builder
3119 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3120 .setTitle("G-Mobile, No data connection after limit")
3121 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3122 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3123 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3124 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3125 .build());
3126
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003127 } else if ("month_over".equals(fake)) {
3128 plans.add(SubscriptionPlan.Builder
3129 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3130 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3131 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3132 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3133 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3134 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3135 .build());
3136 plans.add(SubscriptionPlan.Builder
3137 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3138 .setTitle("G-Mobile, Throttled after limit")
3139 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3140 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3141 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3142 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3143 .build());
3144 plans.add(SubscriptionPlan.Builder
3145 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3146 .setTitle("G-Mobile, No data connection after limit")
3147 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3148 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3149 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3150 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3151 .build());
3152
Jeff Sharkey53313d72017-07-13 16:47:32 -06003153 } else if ("month_none".equals(fake)) {
3154 plans.add(SubscriptionPlan.Builder
3155 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3156 .setTitle("G-Mobile")
3157 .build());
3158 } else if ("prepaid".equals(fake)) {
3159 plans.add(SubscriptionPlan.Builder
3160 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3161 ZonedDateTime.now().plusDays(10))
3162 .setTitle("G-Mobile")
3163 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3164 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3165 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3166 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3167 .build());
3168 } else if ("prepaid_crazy".equals(fake)) {
3169 plans.add(SubscriptionPlan.Builder
3170 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3171 ZonedDateTime.now().plusDays(10))
3172 .setTitle("G-Mobile Anytime")
3173 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3174 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3175 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3176 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3177 .build());
3178 plans.add(SubscriptionPlan.Builder
3179 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3180 ZonedDateTime.now().plusDays(20))
3181 .setTitle("G-Mobile Nickel Nights")
3182 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003183 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3184 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003185 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3186 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3187 .build());
3188 plans.add(SubscriptionPlan.Builder
3189 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3190 ZonedDateTime.now().plusDays(20))
3191 .setTitle("G-Mobile Bonus 3G")
3192 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003193 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003194 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3195 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3196 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3197 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003198 } else if ("unlimited".equals(fake)) {
3199 plans.add(SubscriptionPlan.Builder
3200 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3201 ZonedDateTime.now().plusDays(10))
3202 .setTitle("G-Mobile Awesome")
3203 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3204 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3205 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3206 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3207 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003208 }
3209 return plans.toArray(new SubscriptionPlan[plans.size()]);
3210 }
3211
Jeff Sharkey4635f102017-09-01 11:27:13 -06003212 synchronized (mNetworkPoliciesSecondLock) {
3213 // Only give out plan details to the package that defined them,
3214 // so that we don't risk leaking plans between apps. We always
3215 // let in core system components (like the Settings app).
3216 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3217 if (Objects.equals(ownerPackage, callingPackage)
3218 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3219 return mSubscriptionPlans.get(subId);
3220 } else {
3221 Log.w(TAG, "Not returning plans because caller " + callingPackage
3222 + " doesn't match owner " + ownerPackage);
3223 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003224 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003225 }
3226 }
3227
3228 @Override
3229 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3230 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3231
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003232 for (SubscriptionPlan plan : plans) {
3233 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003234 }
3235
3236 final long token = Binder.clearCallingIdentity();
3237 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003238 synchronized (mUidRulesFirstLock) {
3239 synchronized (mNetworkPoliciesSecondLock) {
3240 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003241 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003242
Jeff Sharkey146bb332018-04-18 15:42:57 -06003243 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3244 if (subscriberId != null) {
3245 ensureActiveMobilePolicyAL(subId, subscriberId);
3246 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3247 } else {
3248 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3249 }
3250
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003251 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003252 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003253 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003254
3255 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3256 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3257 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3258 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003259 } finally {
3260 Binder.restoreCallingIdentity(token);
3261 }
3262 }
3263
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003264 /**
3265 * Only visible for testing purposes. This doesn't give any access to
3266 * existing plans; it simply lets the debug package define new plans.
3267 */
3268 void setSubscriptionPlansOwner(int subId, String packageName) {
3269 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3270 }
3271
Jeff Sharkey53313d72017-07-13 16:47:32 -06003272 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003273 public String getSubscriptionPlansOwner(int subId) {
3274 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3275 throw new SecurityException();
3276 }
3277
3278 synchronized (mNetworkPoliciesSecondLock) {
3279 return mSubscriptionPlansOwner.get(subId);
3280 }
3281 }
3282
3283 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003284 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3285 long timeoutMillis, String callingPackage) {
3286 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3287
3288 // We can only override when carrier told us about plans
3289 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003290 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3291 if (plan == null
3292 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003293 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003294 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003295 }
3296 }
3297
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003298 // Only allow overrides when feature is enabled. However, we always
3299 // allow disabling of overrides for safety reasons.
3300 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3301 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3302 if (overrideEnabled || overrideValue == 0) {
3303 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3304 overrideMask, overrideValue, subId));
3305 if (timeoutMillis > 0) {
3306 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3307 overrideMask, 0, subId), timeoutMillis);
3308 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003309 }
3310 }
3311
3312 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003313 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003314 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003315
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003316 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3317
Dianne Hackborn497175b2014-07-01 12:56:08 -07003318 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003319 for (String arg : args) {
3320 argSet.add(arg);
3321 }
3322
Felipe Lemef0823852016-06-08 13:43:08 -07003323 synchronized (mUidRulesFirstLock) {
3324 synchronized (mNetworkPoliciesSecondLock) {
3325 if (argSet.contains("--unsnooze")) {
3326 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3327 mNetworkPolicy.valueAt(i).clearSnooze();
3328 }
3329
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003330 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003331
3332 fout.println("Cleared snooze timestamps");
3333 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003334 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003335
Felipe Lemef0823852016-06-08 13:43:08 -07003336 fout.print("System ready: "); fout.println(mSystemReady);
3337 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3338 fout.print("Restrict power: "); fout.println(mRestrictPower);
3339 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003340 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3341
3342 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003343 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003344 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003345 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3346 fout.println(mNetworkPolicy.valueAt(i).toString());
3347 }
3348 fout.decreaseIndent();
3349
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003350 fout.println();
3351 fout.println("Subscription plans:");
3352 fout.increaseIndent();
3353 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3354 final int subId = mSubscriptionPlans.keyAt(i);
3355 fout.println("Subscriber ID " + subId + ":");
3356 fout.increaseIndent();
3357 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3358 if (!ArrayUtils.isEmpty(plans)) {
3359 for (SubscriptionPlan plan : plans) {
3360 fout.println(plan);
3361 }
3362 }
3363 fout.decreaseIndent();
3364 }
3365 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003366
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003367 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003368 fout.println("Active subscriptions:");
3369 fout.increaseIndent();
3370 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3371 final int subId = mSubIdToSubscriberId.keyAt(i);
3372 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3373
3374 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3375 }
3376 fout.decreaseIndent();
3377
3378 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003379 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3380 fout.println("Merged subscriptions: " + Arrays.toString(
3381 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3382 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003383
3384 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003385 fout.println("Policy for UIDs:");
3386 fout.increaseIndent();
3387 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003388 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003389 final int uid = mUidPolicy.keyAt(i);
3390 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003391 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003392 fout.print(uid);
3393 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003394 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003395 fout.println();
3396 }
3397 fout.decreaseIndent();
3398
3399 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3400 if (size > 0) {
3401 fout.println("Power save whitelist (except idle) app ids:");
3402 fout.increaseIndent();
3403 for (int i = 0; i < size; i++) {
3404 fout.print("UID=");
3405 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3406 fout.print(": ");
3407 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3408 fout.println();
3409 }
3410 fout.decreaseIndent();
3411 }
3412
3413 size = mPowerSaveWhitelistAppIds.size();
3414 if (size > 0) {
3415 fout.println("Power save whitelist app ids:");
3416 fout.increaseIndent();
3417 for (int i = 0; i < size; i++) {
3418 fout.print("UID=");
3419 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3420 fout.print(": ");
3421 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3422 fout.println();
3423 }
3424 fout.decreaseIndent();
3425 }
3426
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003427 size = mAppIdleTempWhitelistAppIds.size();
3428 if (size > 0) {
3429 fout.println("App idle whitelist app ids:");
3430 fout.increaseIndent();
3431 for (int i = 0; i < size; i++) {
3432 fout.print("UID=");
3433 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3434 fout.print(": ");
3435 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3436 fout.println();
3437 }
3438 fout.decreaseIndent();
3439 }
3440
Felipe Lemef0823852016-06-08 13:43:08 -07003441 size = mDefaultRestrictBackgroundWhitelistUids.size();
3442 if (size > 0) {
3443 fout.println("Default restrict background whitelist uids:");
3444 fout.increaseIndent();
3445 for (int i = 0; i < size; i++) {
3446 fout.print("UID=");
3447 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3448 fout.println();
3449 }
3450 fout.decreaseIndent();
3451 }
3452
3453 size = mRestrictBackgroundWhitelistRevokedUids.size();
3454 if (size > 0) {
3455 fout.println("Default restrict background whitelist uids revoked by users:");
3456 fout.increaseIndent();
3457 for (int i = 0; i < size; i++) {
3458 fout.print("UID=");
3459 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3460 fout.println();
3461 }
3462 fout.decreaseIndent();
3463 }
3464
3465 final SparseBooleanArray knownUids = new SparseBooleanArray();
3466 collectKeys(mUidState, knownUids);
3467 collectKeys(mUidRules, knownUids);
3468
3469 fout.println("Status for all known UIDs:");
3470 fout.increaseIndent();
3471 size = knownUids.size();
3472 for (int i = 0; i < size; i++) {
3473 final int uid = knownUids.keyAt(i);
3474 fout.print("UID=");
3475 fout.print(uid);
3476
3477 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3478 fout.print(" state=");
3479 fout.print(state);
3480 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3481 fout.print(" (fg)");
3482 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003483 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003484 ? " (fg svc)" : " (bg)");
3485 }
3486
3487 final int uidRules = mUidRules.get(uid, RULE_NONE);
3488 fout.print(" rules=");
3489 fout.print(uidRulesToString(uidRules));
3490 fout.println();
3491 }
3492 fout.decreaseIndent();
3493
3494 fout.println("Status for just UIDs with rules:");
3495 fout.increaseIndent();
3496 size = mUidRules.size();
3497 for (int i = 0; i < size; i++) {
3498 final int uid = mUidRules.keyAt(i);
3499 fout.print("UID=");
3500 fout.print(uid);
3501 final int uidRules = mUidRules.get(uid, RULE_NONE);
3502 fout.print(" rules=");
3503 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003504 fout.println();
3505 }
3506 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003507
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003508 fout.println("Admin restricted uids for metered data:");
3509 fout.increaseIndent();
3510 size = mMeteredRestrictedUids.size();
3511 for (int i = 0; i < size; ++i) {
3512 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3513 fout.println(mMeteredRestrictedUids.valueAt(i));
3514 }
3515 fout.decreaseIndent();
3516
Makoto Onuki49392d32018-04-11 13:51:02 -07003517 fout.println();
3518 mStatLogger.dump(fout);
3519
Sudheer Shanka352dc572017-09-22 17:09:38 -07003520 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003521 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003522 }
3523 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003524
3525 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003526 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003527 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003528 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003529 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003530 }
3531
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003532 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003533 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003534 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003535 return isUidStateForeground(
3536 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003537 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003538 }
3539
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003540 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003541 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003542 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003543 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003544 }
3545
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003546 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003547 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003548 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3549 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3550 }
3551
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003552 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003553 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003554 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003555 }
3556
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003557 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003558 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003559 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003560 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003561 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003562 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003563 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003564 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3565 try {
3566 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3567 if (oldUidState != uidState) {
3568 // state changed, push updated rules
3569 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003570 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3571 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3572 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003573 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003574 if (mDeviceIdleMode) {
3575 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003576 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003577 if (mRestrictPower) {
3578 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003579 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003580 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003581 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003582 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003583 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003584 } finally {
3585 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003586 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003587 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003588 }
3589
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003590 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003591 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003592 final int index = mUidState.indexOfKey(uid);
3593 if (index >= 0) {
3594 final int oldUidState = mUidState.valueAt(index);
3595 mUidState.removeAt(index);
3596 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003597 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003598 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003599 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003600 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003601 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003602 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003603 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003604 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003605 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003606 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003607 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003608 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003609 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003610 }
3611
Felipe Lemef28983d2016-03-25 12:18:23 -07003612 // adjust stats accounting based on foreground status
3613 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003614 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3615 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3616 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3617 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003618 try {
3619 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003620 } finally {
3621 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003622 }
3623 }
3624
Sudheer Shankac9d94072017-02-22 22:13:55 +00003625 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3626 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003627 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003628 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003629 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003630 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003631 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003632 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003633 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003634 }
3635
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003636 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003637 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003638 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3639 try {
3640 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3641 mUidFirewallPowerSaveRules);
3642 } finally {
3643 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3644 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003645 }
3646
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003647 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003648 void updateRuleForRestrictPowerUL(int uid) {
3649 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003650 }
3651
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003652 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003653 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003654 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3655 try {
3656 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3657 mUidFirewallDozableRules);
3658 } finally {
3659 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3660 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003661 }
3662
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003663 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003664 void updateRuleForDeviceIdleUL(int uid) {
3665 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003666 }
3667
Felipe Lemef28983d2016-03-25 12:18:23 -07003668 // NOTE: since both fw_dozable and fw_powersave uses the same map
3669 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003670 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003671 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003672 SparseIntArray rules) {
3673 if (enabled) {
3674 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003675 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003676 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003677 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003678 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003679 for (int ui = users.size() - 1; ui >= 0; ui--) {
3680 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003681 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3682 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3683 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3684 updateRulesForWhitelistedAppIds(uidRules,
3685 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003686 }
3687 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003688 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003689 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003690 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3691 }
3692 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003693 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003694 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003695 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003696 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003697 }
3698
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003699 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3700 final SparseBooleanArray whitelistedAppIds, int userId) {
3701 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3702 if (whitelistedAppIds.valueAt(i)) {
3703 final int appId = whitelistedAppIds.keyAt(i);
3704 final int uid = UserHandle.getUid(userId, appId);
3705 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3706 }
3707 }
3708 }
3709
3710 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003711 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3712 * mode, and app idle).
3713 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003714 * @param deviceIdleMode if true then we don't consider
3715 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3716 * whitelisted.
3717 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003718 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003719 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003720 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003721 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3722 || mPowerSaveWhitelistAppIds.get(appId);
3723 if (!deviceIdleMode) {
3724 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3725 }
3726 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003727 }
3728
Felipe Lemef28983d2016-03-25 12:18:23 -07003729 // NOTE: since both fw_dozable and fw_powersave uses the same map
3730 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003731 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003732 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003733 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003734 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003735 chain == FIREWALL_CHAIN_DOZABLE);
3736 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003737 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003738 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003739 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003740 }
3741 }
3742 }
3743
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003744 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003745 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003746 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3747 try {
3748 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3749 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003750
Felipe Leme873a83a2016-09-07 11:34:10 -07003751 // Fully update the app idle firewall chain.
3752 final List<UserInfo> users = mUserManager.getUsers();
3753 for (int ui = users.size() - 1; ui >= 0; ui--) {
3754 UserInfo user = users.get(ui);
3755 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3756 for (int uid : idleUids) {
3757 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3758 // quick check: if this uid doesn't have INTERNET permission, it
3759 // doesn't have network access anyway, so it is a waste to mess
3760 // with it here.
3761 if (hasInternetPermissions(uid)) {
3762 uidRules.put(uid, FIREWALL_RULE_DENY);
3763 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003764 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003765 }
3766 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003767
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003768 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003769 } finally {
3770 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3771 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003772 }
3773
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003774 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003775 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003776 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003777
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003778 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3779 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3780 }
3781 try {
3782 int appId = UserHandle.getAppId(uid);
3783 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3784 && !isUidForegroundOnRestrictPowerUL(uid)) {
3785 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003786 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003787 } else {
3788 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003789 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003790 }
3791 } finally {
3792 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003793 }
3794 }
3795
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003796 /**
3797 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3798 * changed.
3799 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003800 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003801 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003802 boolean paroled = mUsageStats.isAppIdleParoleOn();
3803 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003804 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003805
3806 int ruleCount = mUidFirewallStandbyRules.size();
3807 for (int i = 0; i < ruleCount; i++) {
3808 int uid = mUidFirewallStandbyRules.keyAt(i);
3809 int oldRules = mUidRules.get(uid);
3810 if (enableChain) {
3811 // Chain wasn't enabled before and the other power-related
3812 // chains are whitelists, so we can clear the
3813 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3814 // the effective rules result in blocking network access.
3815 oldRules &= MASK_METERED_NETWORKS;
3816 } else {
3817 // Skip if it had no restrictions to begin with
3818 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3819 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003820 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3821 if (newUidRules == RULE_NONE) {
3822 mUidRules.delete(uid);
3823 } else {
3824 mUidRules.put(uid, newUidRules);
3825 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003826 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003827 }
3828
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003829 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003830 * Update rules that might be changed by {@link #mRestrictBackground},
3831 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003832 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003833 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003834 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003835 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3836 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3837 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3838 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003839 try {
Felipe Leme09700462016-09-08 09:33:48 -07003840 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003841 updateRulesForRestrictPowerUL();
3842 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003843
Felipe Leme873a83a2016-09-07 11:34:10 -07003844 // If the set of restricted networks may have changed, re-evaluate those.
3845 if (restrictedNetworksChanged) {
3846 normalizePoliciesNL();
3847 updateNetworkRulesNL();
3848 }
3849 } finally {
3850 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003851 }
3852 }
3853
Felipe Leme09700462016-09-08 09:33:48 -07003854 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003855 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003856 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003857 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3858 try {
3859 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003860 updateRulesForPowerSaveUL();
3861 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3862 } finally {
3863 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3864 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003865 }
3866
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003867 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003868 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003869 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3870 try {
3871 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3872 } finally {
3873 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3874 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003875 }
3876
3877 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3878 private static final int TYPE_RESTRICT_POWER = 2;
3879 @Retention(RetentionPolicy.SOURCE)
3880 @IntDef(flag = false, value = {
3881 TYPE_RESTRICT_BACKGROUND,
3882 TYPE_RESTRICT_POWER,
3883 })
3884 public @interface RestrictType {
3885 }
3886
3887 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003888 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003889 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003890 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3891 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3892 }
3893 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003894 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003895
3896 final PackageManager pm = mContext.getPackageManager();
3897 final List<UserInfo> users;
3898 final List<ApplicationInfo> apps;
3899
3900 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3901 try {
3902 users = mUserManager.getUsers();
3903 } finally {
3904 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3905 }
3906 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3907 try {
3908 apps = pm.getInstalledApplications(
3909 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3910 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3911 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3912 } finally {
3913 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3914 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003915
Felipe Leme873a83a2016-09-07 11:34:10 -07003916 final int usersSize = users.size();
3917 final int appsSize = apps.size();
3918 for (int i = 0; i < usersSize; i++) {
3919 final UserInfo user = users.get(i);
3920 for (int j = 0; j < appsSize; j++) {
3921 final ApplicationInfo app = apps.get(j);
3922 final int uid = UserHandle.getUid(user.id, app.uid);
3923 switch (type) {
3924 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003925 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003926 break;
3927 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003928 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003929 break;
3930 default:
3931 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3932 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003933 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003934 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003935 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003936 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003937 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003938 }
3939
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003940 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003941 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003942 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003943 final int numUsers = users.size();
3944 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003945 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003946 int uid = UserHandle.getUid(user.id, appId);
3947 // Update external firewall rules.
3948 updateRuleForAppIdleUL(uid);
3949 updateRuleForDeviceIdleUL(uid);
3950 updateRuleForRestrictPowerUL(uid);
3951 // Update internal rules.
3952 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003953 }
3954 }
3955
Felipe Leme70c57c22016-03-29 10:45:13 -07003956 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3957 // methods below could be merged into a isUidValidForRules() method.
3958 private boolean isUidValidForBlacklistRules(int uid) {
3959 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003960 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003961 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003962 return true;
3963 }
3964
3965 return false;
3966 }
3967
Felipe Leme70c57c22016-03-29 10:45:13 -07003968 private boolean isUidValidForWhitelistRules(int uid) {
3969 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3970 }
3971
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003972 /**
3973 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3974 * power saving restrictions may still apply.
3975 */
3976 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003977 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003978 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3979
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003980 synchronized (mUidRulesFirstLock) {
3981 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3982 // No change.
3983 return;
3984 }
3985
3986 final long token = Binder.clearCallingIdentity();
3987 try {
3988 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3989 if (shouldWhitelist) {
3990 mAppIdleTempWhitelistAppIds.put(uid, true);
3991 } else {
3992 mAppIdleTempWhitelistAppIds.delete(uid);
3993 }
3994 updateRuleForAppIdleUL(uid);
3995 updateRulesForPowerRestrictionsUL(uid);
3996 } finally {
3997 Binder.restoreCallingIdentity(token);
3998 }
3999 }
4000 }
4001
4002 /** Return the list of UIDs currently in the app idle whitelist. */
4003 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004004 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004005 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4006
4007 synchronized (mUidRulesFirstLock) {
4008 final int len = mAppIdleTempWhitelistAppIds.size();
4009 int[] uids = new int[len];
4010 for (int i = 0; i < len; ++i) {
4011 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4012 }
4013 return uids;
4014 }
4015 }
4016
4017 /** Returns if the UID is currently considered idle. */
4018 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004019 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004020 synchronized (mUidRulesFirstLock) {
4021 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4022 // UID is temporarily whitelisted.
4023 return false;
4024 }
4025 }
4026
Amith Yamasani15e472352015-04-24 19:06:07 -07004027 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4028 final int userId = UserHandle.getUserId(uid);
4029
songjinshi0655edd2016-05-18 19:55:32 +08004030 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004031 for (String packageName : packages) {
4032 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4033 return false;
4034 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004035 }
4036 }
4037 return true;
4038 }
4039
4040 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004041 * Checks if an uid has INTERNET permissions.
4042 * <p>
4043 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004044 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004045 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004046 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004047 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004048 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004049 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004050 }
4051 } catch (RemoteException e) {
4052 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004053 return true;
4054 }
4055
4056 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004057 * Clears all state - internal and external - associated with an UID.
4058 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004059 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004060 private void onUidDeletedUL(int uid) {
4061 // First cleanup in-memory state synchronously...
4062 mUidRules.delete(uid);
4063 mUidPolicy.delete(uid);
4064 mUidFirewallStandbyRules.delete(uid);
4065 mUidFirewallDozableRules.delete(uid);
4066 mUidFirewallPowerSaveRules.delete(uid);
4067 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4068 mPowerSaveWhitelistAppIds.delete(uid);
4069 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004070 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004071
4072 // ...then update iptables asynchronously.
4073 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4074 }
4075
4076 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004077 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004078 *
Felipe Leme781ba142016-05-09 16:24:48 -07004079 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004080 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004081 * <li>Doze mode
4082 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004083 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004084 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004085 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004086 *
4087 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004088 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004089 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004090 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004091 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004092 updateRuleForDeviceIdleUL(uid);
4093 updateRuleForAppIdleUL(uid);
4094 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004095
4096 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004097 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004098
4099 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004100 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004101 }
4102
Felipe Leme70c57c22016-03-29 10:45:13 -07004103 /**
4104 * Applies network rules to bandwidth controllers based on process state and user-defined
4105 * restrictions (blacklist / whitelist).
4106 *
4107 * <p>
4108 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4109 * networks:
4110 * <ul>
4111 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4112 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4113 * also blacklisted.
4114 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004115 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004116 * <ul>
4117 *
4118 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4119 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4120 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4121 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004122 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004123 * {@link INetworkManagementService}, but this method should also be called in events (like
4124 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4125 * following rules should also be applied:
4126 *
4127 * <ul>
4128 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4129 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4130 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4131 * {@code bw_penalty_box}.
4132 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4133 * </ul>
4134 *
4135 * <p>For optimization, the rules are only applied on user apps that have internet access
4136 * permission, since there is no need to change the {@code iptables} rule if the app does not
4137 * have permission to use the internet.
4138 *
4139 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004140 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004141 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004142 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004143 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4144 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4145 "updateRulesForDataUsageRestrictionsUL: " + uid);
4146 }
4147 try {
4148 updateRulesForDataUsageRestrictionsULInner(uid);
4149 } finally {
4150 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4151 }
4152 }
4153
4154 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004155 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004156 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004157 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004158 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004159
Dianne Hackborn497175b2014-07-01 12:56:08 -07004160 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004161 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004162 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004163 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004164
Felipe Leme781ba142016-05-09 16:24:48 -07004165 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004166 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004167 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4168 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004169
Felipe Leme70c57c22016-03-29 10:45:13 -07004170 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004171 if (isRestrictedByAdmin) {
4172 newRule = RULE_REJECT_METERED;
4173 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004174 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4175 newRule = RULE_TEMPORARY_ALLOW_METERED;
4176 } else if (isWhitelisted) {
4177 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004178 }
4179 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004180 if (isBlacklisted) {
4181 newRule = RULE_REJECT_METERED;
4182 } else if (mRestrictBackground && isWhitelisted) {
4183 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004184 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004185 }
Felipe Leme781ba142016-05-09 16:24:48 -07004186 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004187
Felipe Lemef28983d2016-03-25 12:18:23 -07004188 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004189 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004190 + ": isForeground=" +isForeground
4191 + ", isBlacklisted=" + isBlacklisted
4192 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004193 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004194 + ", oldRule=" + uidRulesToString(oldRule)
4195 + ", newRule=" + uidRulesToString(newRule)
4196 + ", newUidRules=" + uidRulesToString(newUidRules)
4197 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004198 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004199
Felipe Leme46c4fc32016-05-04 09:21:43 -07004200 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004201 mUidRules.delete(uid);
4202 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004203 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004204 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004205
Felipe Leme70c57c22016-03-29 10:45:13 -07004206 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004207 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004208 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004209 // Temporarily whitelist foreground app, removing from blacklist if necessary
4210 // (since bw_penalty_box prevails over bw_happy_box).
4211
4212 setMeteredNetworkWhitelist(uid, true);
4213 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4214 // but ideally it should be just:
4215 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004216 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004217 setMeteredNetworkBlacklist(uid, false);
4218 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004219 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004220 // Remove temporary whitelist from app that is not on foreground anymore.
4221
4222 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4223 // but ideally they should be just:
4224 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4225 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004226 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004227 setMeteredNetworkWhitelist(uid, false);
4228 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004229 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004230 setMeteredNetworkBlacklist(uid, true);
4231 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004232 } else if (hasRule(newRule, RULE_REJECT_METERED)
4233 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004234 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004235 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004236 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004237 // Since blacklist prevails over whitelist, we need to handle the special case
4238 // where app is whitelisted and blacklisted at the same time (although such
4239 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004240 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004241 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004242 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4243 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004244 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004245 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004246 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004247 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004248 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4249 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004250 + ", whitelisted=" + isWhitelisted
4251 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004252 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004253 + ", newRule=" + uidRulesToString(newUidRules)
4254 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004255 }
Felipe Leme781ba142016-05-09 16:24:48 -07004256
Sudheer Shankac9d94072017-02-22 22:13:55 +00004257 // Dispatch changed rule to existing listeners.
4258 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004259 }
4260 }
4261
4262 /**
4263 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4264 * listeners in case of change.
4265 * <p>
4266 * There are 3 power-related rules that affects whether an app has background access on
4267 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4268 * restriction, it's added to the equivalent firewall chain:
4269 * <ul>
4270 * <li>App is idle: {@code fw_standby} firewall chain.
4271 * <li>Device is idle: {@code fw_dozable} firewall chain.
4272 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4273 * </ul>
4274 * <p>
4275 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4276 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4277 * <p>
4278 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4279 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004280 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004281 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004282 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4283
Sudheer Shankac9d94072017-02-22 22:13:55 +00004284 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004285
Sudheer Shankac9d94072017-02-22 22:13:55 +00004286 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004287 mUidRules.delete(uid);
4288 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004289 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004290 }
4291 }
4292
4293 /**
4294 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4295 *
4296 * @param uid the uid of the app to update rules for
4297 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4298 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4299 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004300 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004301 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004302 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004303 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4304 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4305 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4306 + (paroled ? "P" : "-"));
4307 }
4308 try {
4309 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4310 } finally {
4311 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4312 }
4313 }
4314
4315 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004316 if (!isUidValidForBlacklistRules(uid)) {
4317 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004318 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004319 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004320
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004321 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004322 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004323 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004324
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004325 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004326 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4327 int newRule = RULE_NONE;
4328
4329 // First step: define the new rule based on user restrictions and foreground state.
4330
4331 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4332 // by considering the foreground and non-foreground states.
4333 if (isForeground) {
4334 if (restrictMode) {
4335 newRule = RULE_ALLOW_ALL;
4336 }
4337 } else if (restrictMode) {
4338 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4339 }
4340
4341 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4342
4343 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004344 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004345 + ", isIdle: " + isIdle
4346 + ", mRestrictPower: " + mRestrictPower
4347 + ", mDeviceIdleMode: " + mDeviceIdleMode
4348 + ", isForeground=" + isForeground
4349 + ", isWhitelisted=" + isWhitelisted
4350 + ", oldRule=" + uidRulesToString(oldRule)
4351 + ", newRule=" + uidRulesToString(newRule)
4352 + ", newUidRules=" + uidRulesToString(newUidRules)
4353 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4354 }
4355
Felipe Leme781ba142016-05-09 16:24:48 -07004356 // Second step: notify listeners if state changed.
4357 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004358 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004359 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004360 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004361 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4362 } else {
4363 // All scenarios should have been covered above
4364 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4365 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004366 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004367 + ", newRule=" + uidRulesToString(newUidRules)
4368 + ", oldRule=" + uidRulesToString(oldUidRules));
4369 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004370 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004371 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004372
Sudheer Shankac9d94072017-02-22 22:13:55 +00004373 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004374 }
4375
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004376 private class AppIdleStateChangeListener
4377 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4378
4379 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004380 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4381 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004382 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004383 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4384 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004385 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004386 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004387 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004388 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004389 }
4390 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004391 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004392 }
4393
4394 @Override
4395 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004396 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004397 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004398 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004399 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004400 }
4401 }
4402
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004403 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4404 if (listener != null) {
4405 try {
4406 listener.onUidRulesChanged(uid, uidRules);
4407 } catch (RemoteException ignored) {
4408 }
4409 }
4410 }
4411
4412 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4413 String[] meteredIfaces) {
4414 if (listener != null) {
4415 try {
4416 listener.onMeteredIfacesChanged(meteredIfaces);
4417 } catch (RemoteException ignored) {
4418 }
4419 }
4420 }
4421
4422 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4423 boolean restrictBackground) {
4424 if (listener != null) {
4425 try {
4426 listener.onRestrictBackgroundChanged(restrictBackground);
4427 } catch (RemoteException ignored) {
4428 }
4429 }
4430 }
4431
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004432 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4433 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004434 if (listener != null) {
4435 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004436 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004437 } catch (RemoteException ignored) {
4438 }
4439 }
4440 }
4441
Jeff Sharkey9252b342018-01-19 07:58:35 +09004442 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4443 int overrideMask, int overrideValue) {
4444 if (listener != null) {
4445 try {
4446 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4447 } catch (RemoteException ignored) {
4448 }
4449 }
4450 }
4451
Makoto Onuki8e777332017-03-28 11:25:47 -07004452 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004453 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004454 public boolean handleMessage(Message msg) {
4455 switch (msg.what) {
4456 case MSG_RULES_CHANGED: {
4457 final int uid = msg.arg1;
4458 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004459 final int length = mListeners.beginBroadcast();
4460 for (int i = 0; i < length; i++) {
4461 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4462 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004463 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004464 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004465 return true;
4466 }
4467 case MSG_METERED_IFACES_CHANGED: {
4468 final String[] meteredIfaces = (String[]) msg.obj;
4469 final int length = mListeners.beginBroadcast();
4470 for (int i = 0; i < length; i++) {
4471 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004472 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004473 }
4474 mListeners.finishBroadcast();
4475 return true;
4476 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004477 case MSG_LIMIT_REACHED: {
4478 final String iface = (String) msg.obj;
4479
Felipe Lemef0823852016-06-08 13:43:08 -07004480 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004481 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004482 // force stats update to make sure we have
4483 // numbers that caused alert to trigger.
4484 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004485
Felipe Lemef0823852016-06-08 13:43:08 -07004486 updateNetworkEnabledNL();
4487 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004488 }
4489 }
4490 return true;
4491 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004492 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4493 final boolean restrictBackground = msg.arg1 != 0;
4494 final int length = mListeners.beginBroadcast();
4495 for (int i = 0; i < length; i++) {
4496 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004497 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004498 }
4499 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004500 final Intent intent =
4501 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4502 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4503 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4504 return true;
4505 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004506 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004507 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004508 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004509 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004510 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004511 final int length = mListeners.beginBroadcast();
4512 for (int i = 0; i < length; i++) {
4513 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004514 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004515 }
4516 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004517 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4518 if (notifyApp.booleanValue()) {
4519 broadcastRestrictBackgroundChanged(uid, notifyApp);
4520 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004521 return true;
4522 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004523 case MSG_ADVISE_PERSIST_THRESHOLD: {
4524 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004525 // make sure stats are recorded frequently enough; we aim
4526 // for 2MB threshold for 2GB/month rules.
4527 final long persistThreshold = lowestRule / 1000;
4528 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004529 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004530 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004531 case MSG_UPDATE_INTERFACE_QUOTA: {
4532 removeInterfaceQuota((String) msg.obj);
4533 // int params need to be stitched back into a long
4534 setInterfaceQuota((String) msg.obj,
4535 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4536 return true;
4537 }
4538 case MSG_REMOVE_INTERFACE_QUOTA: {
4539 removeInterfaceQuota((String) msg.obj);
4540 return true;
4541 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004542 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4543 resetUidFirewallRules(msg.arg1);
4544 return true;
4545 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004546 case MSG_SUBSCRIPTION_OVERRIDE: {
4547 final int overrideMask = msg.arg1;
4548 final int overrideValue = msg.arg2;
4549 final int subId = (int) msg.obj;
4550 final int length = mListeners.beginBroadcast();
4551 for (int i = 0; i < length; i++) {
4552 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4553 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4554 }
4555 mListeners.finishBroadcast();
4556 return true;
4557 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004558 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4559 final int userId = msg.arg1;
4560 final Set<String> packageNames = (Set<String>) msg.obj;
4561 setMeteredRestrictedPackagesInternal(packageNames, userId);
4562 return true;
4563 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004564 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4565 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4566 final boolean enabled = msg.arg1 != 0;
4567 setNetworkTemplateEnabledInner(template, enabled);
4568 return true;
4569 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004570 default: {
4571 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004572 }
4573 }
4574 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004575 };
4576
4577 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4578 @Override
4579 public boolean handleMessage(Message msg) {
4580 switch (msg.what) {
4581 case UID_MSG_STATE_CHANGED: {
4582 final int uid = msg.arg1;
4583 final int procState = msg.arg2;
4584 final long procStateSeq = (Long) msg.obj;
4585
4586 handleUidChanged(uid, procState, procStateSeq);
4587 return true;
4588 }
4589 case UID_MSG_GONE: {
4590 final int uid = msg.arg1;
4591 handleUidGone(uid);
4592 return true;
4593 }
4594 default: {
4595 return false;
4596 }
4597 }
4598 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004599 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004600
Makoto Onuki8e777332017-03-28 11:25:47 -07004601 void handleUidChanged(int uid, int procState, long procStateSeq) {
4602 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4603 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004604 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004605 synchronized (mUidRulesFirstLock) {
4606 // We received a uid state change callback, add it to the history so that it
4607 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004608 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004609 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004610 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004611 // Updating the network rules is done, so notify AMS about this.
4612 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4613 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004614 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4615 // called from the handler, so there's no multi-threading issue.
4616 if (updated) {
4617 updateNetworkStats(uid, isUidStateForeground(procState));
4618 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004619 } finally {
4620 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4621 }
4622 }
4623
4624 void handleUidGone(int uid) {
4625 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4626 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004627 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004628 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004629 updated = removeUidStateUL(uid);
4630 }
4631 // 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, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004635 }
4636 } finally {
4637 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4638 }
4639 }
4640
Felipe Leme57e3d312016-08-23 14:42:52 -07004641 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4642 final PackageManager pm = mContext.getPackageManager();
4643 final String[] packages = pm.getPackagesForUid(uid);
4644 if (packages != null) {
4645 final int userId = UserHandle.getUserId(uid);
4646 for (String packageName : packages) {
4647 final Intent intent =
4648 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4649 intent.setPackage(packageName);
4650 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4651 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4652 }
4653 }
4654 }
4655
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004656 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4657 // long quotaBytes split up into two ints to fit in message
4658 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4659 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4660 }
4661
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004662 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004663 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004664 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004665 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004666 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004667 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004668 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004669 }
4670 }
4671
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004672 private void removeInterfaceQuotaAsync(String iface) {
4673 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4674 }
4675
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004676 private void removeInterfaceQuota(String iface) {
4677 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004678 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004679 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004680 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004681 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004682 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004683 }
4684 }
4685
Felipe Leme70c57c22016-03-29 10:45:13 -07004686 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4687 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004688 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004689 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004690 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004691 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4692 } catch (RemoteException e) {
4693 // ignored; service lives in system_server
4694 }
4695 }
4696
4697 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4698 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4699 try {
4700 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4701 } catch (IllegalStateException e) {
4702 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004703 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004704 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004705 }
4706 }
4707
Felipe Lemebc853dd2016-09-08 13:26:55 -07004708 private static final int CHAIN_TOGGLE_NONE = 0;
4709 private static final int CHAIN_TOGGLE_ENABLE = 1;
4710 private static final int CHAIN_TOGGLE_DISABLE = 2;
4711 @Retention(RetentionPolicy.SOURCE)
4712 @IntDef(flag = false, value = {
4713 CHAIN_TOGGLE_NONE,
4714 CHAIN_TOGGLE_ENABLE,
4715 CHAIN_TOGGLE_DISABLE
4716 })
4717 public @interface ChainToggleType {
4718 }
4719
4720 /**
4721 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004722 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004723 *
4724 * @param chain firewall chain.
4725 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4726 * @param toggle whether the chain should be enabled, disabled, or not changed.
4727 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004728 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004729 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004730 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004731 if (uidRules != null) {
4732 setUidFirewallRulesUL(chain, uidRules);
4733 }
4734 if (toggle != CHAIN_TOGGLE_NONE) {
4735 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4736 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004737 }
4738
Amith Yamasani15e472352015-04-24 19:06:07 -07004739 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004740 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4741 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4742 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004743 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004744 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004745 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004746 int size = uidRules.size();
4747 int[] uids = new int[size];
4748 int[] rules = new int[size];
4749 for(int index = size - 1; index >= 0; --index) {
4750 uids[index] = uidRules.keyAt(index);
4751 rules[index] = uidRules.valueAt(index);
4752 }
4753 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004754 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004755 } catch (IllegalStateException e) {
4756 Log.wtf(TAG, "problem setting firewall uid rules", e);
4757 } catch (RemoteException e) {
4758 // ignored; service lives in system_server
4759 }
4760 }
4761
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004762 /**
4763 * Add or remove a uid to the firewall blacklist for all network ifaces.
4764 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004765 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004766 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4767 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4768 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004769 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004770 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004771 if (chain == FIREWALL_CHAIN_DOZABLE) {
4772 mUidFirewallDozableRules.put(uid, rule);
4773 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4774 mUidFirewallStandbyRules.put(uid, rule);
4775 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4776 mUidFirewallPowerSaveRules.put(uid, rule);
4777 }
4778
4779 try {
4780 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004781 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004782 } catch (IllegalStateException e) {
4783 Log.wtf(TAG, "problem setting firewall uid rules", e);
4784 } catch (RemoteException e) {
4785 // ignored; service lives in system_server
4786 }
4787 } finally {
4788 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004789 }
4790 }
4791
4792 /**
4793 * Add or remove a uid to the firewall blacklist for all network ifaces.
4794 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004795 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004796 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004797 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4798 mFirewallChainStates.get(chain) == enable) {
4799 // All is the same, nothing to do.
4800 return;
4801 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004802 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004803 try {
4804 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004805 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004806 } catch (IllegalStateException e) {
4807 Log.wtf(TAG, "problem enable firewall chain", e);
4808 } catch (RemoteException e) {
4809 // ignored; service lives in system_server
4810 }
4811 }
4812
Felipe Leme03e95e22016-09-09 09:25:31 -07004813 /**
4814 * Resets all firewall rules associated with an UID.
4815 */
4816 private void resetUidFirewallRules(int uid) {
4817 try {
4818 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4819 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4820 mNetworkManager
4821 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4822 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4823 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4824 } catch (IllegalStateException e) {
4825 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4826 } catch (RemoteException e) {
4827 // ignored; service lives in system_server
4828 }
4829 }
4830
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004831 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004832 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004833 return getNetworkTotalBytes(template, start, end);
4834 }
4835
4836 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004837 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004838 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004839 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004840 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004841 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004842 }
4843 }
4844
4845 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4846 try {
4847 return mNetworkStats.getNetworkUidBytes(template, start, end);
4848 } catch (RuntimeException e) {
4849 Slog.w(TAG, "Failed to read network stats: " + e);
4850 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004851 }
4852 }
4853
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004854 private boolean isBandwidthControlEnabled() {
4855 final long token = Binder.clearCallingIdentity();
4856 try {
4857 return mNetworkManager.isBandwidthControlEnabled();
4858 } catch (RemoteException e) {
4859 // ignored; service lives in system_server
4860 return false;
4861 } finally {
4862 Binder.restoreCallingIdentity(token);
4863 }
4864 }
4865
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004866 private static Intent buildAllowBackgroundDataIntent() {
4867 return new Intent(ACTION_ALLOW_BACKGROUND);
4868 }
4869
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004870 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4871 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004872 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4873 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4874 return intent;
4875 }
4876
4877 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4878 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4879 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004880 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4881 return intent;
4882 }
4883
Wei Liu546cb772016-07-21 16:19:01 -07004884 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004885 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004886 intent.setComponent(ComponentName.unflattenFromString(
4887 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004888 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4889 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4890 return intent;
4891 }
4892
Wei Liu546cb772016-07-21 16:19:01 -07004893 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004894 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004895 intent.setComponent(ComponentName.unflattenFromString(
4896 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004897 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4898 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4899 return intent;
4900 }
4901
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004902 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004903 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004904 mHandler.getLooper().getQueue().addIdleHandler(handler);
4905 }
4906
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004907 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004908 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004909 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004910 mRestrictBackgroundPowerState = result;
4911
4912 boolean restrictBackground = result.batterySaverEnabled;
4913 boolean shouldInvokeRestrictBackground;
4914 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4915 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4916
4917 if (result.globalBatterySaverEnabled) {
4918 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4919 // turn it on.
4920 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4921 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4922 localRestrictBgChangedInBsm = false;
4923 } else {
4924 // Try to restore the restrictBackground if it doesn't change in bsm
4925 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4926 restrictBackground = mRestrictBackgroundBeforeBsm;
4927 }
4928
4929 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004930 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004931 }
4932
4933 // Change it at last so setRestrictBackground() won't affect this variable
4934 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4935 }
4936
Jeff Sharkey1b861272011-05-22 00:34:52 -07004937 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4938 final int size = source.size();
4939 for (int i = 0; i < size; i++) {
4940 target.put(source.keyAt(i), true);
4941 }
4942 }
4943
Stuart Scottf1fb3972015-04-02 18:00:02 -07004944 @Override
4945 public void factoryReset(String subscriber) {
4946 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4947
Stuart Scotte3e314d2015-04-20 14:07:45 -07004948 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4949 return;
4950 }
4951
Stuart Scottf1fb3972015-04-02 18:00:02 -07004952 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004953 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004954 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4955 for (NetworkPolicy policy : policies) {
4956 if (policy.template.equals(template)) {
4957 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4958 policy.inferred = false;
4959 policy.clearSnooze();
4960 }
4961 }
4962 setNetworkPolicies(policies);
4963
4964 // Turn restrict background data off
4965 setRestrictBackground(false);
4966
Stuart Scotte3e314d2015-04-20 14:07:45 -07004967 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4968 // Remove app's "restrict background data" flag
4969 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4970 setUidPolicy(uid, POLICY_NONE);
4971 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004972 }
4973 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004974
Sudheer Shankab8f23162017-08-04 13:30:10 -07004975 @Override
4976 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004977 final long startTime = mStatLogger.getTime();
4978
Sudheer Shankab8f23162017-08-04 13:30:10 -07004979 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004980 final int uidRules;
4981 final boolean isBackgroundRestricted;
4982 synchronized (mUidRulesFirstLock) {
4983 uidRules = mUidRules.get(uid, RULE_NONE);
4984 isBackgroundRestricted = mRestrictBackground;
4985 }
junyulai05986c62018-08-07 19:50:45 +08004986 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
4987 isBackgroundRestricted, mLogger);
4988
4989 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4990
4991 return ret;
4992 }
4993
4994 private static boolean isSystem(int uid) {
4995 return uid < Process.FIRST_APPLICATION_UID;
4996 }
4997
4998 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
4999 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5000 final int reason;
5001 // Networks are never blocked for system components
5002 if (isSystem(uid)) {
5003 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005004 }
junyulai05986c62018-08-07 19:50:45 +08005005 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5006 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005007 }
junyulai05986c62018-08-07 19:50:45 +08005008 else if (!isNetworkMetered) {
5009 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005010 }
junyulai05986c62018-08-07 19:50:45 +08005011 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5012 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005013 }
junyulai05986c62018-08-07 19:50:45 +08005014 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5015 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005016 }
junyulai05986c62018-08-07 19:50:45 +08005017 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5018 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005019 }
junyulai05986c62018-08-07 19:50:45 +08005020 else if (isBackgroundRestricted) {
5021 reason = NTWK_BLOCKED_BG_RESTRICT;
5022 }
5023 else {
5024 reason = NTWK_ALLOWED_DEFAULT;
5025 }
5026
5027 final boolean blocked;
5028 switch(reason) {
5029 case NTWK_ALLOWED_DEFAULT:
5030 case NTWK_ALLOWED_NON_METERED:
5031 case NTWK_ALLOWED_TMP_WHITELIST:
5032 case NTWK_ALLOWED_WHITELIST:
5033 case NTWK_ALLOWED_SYSTEM:
5034 blocked = false;
5035 break;
5036 case NTWK_BLOCKED_POWER:
5037 case NTWK_BLOCKED_BLACKLIST:
5038 case NTWK_BLOCKED_BG_RESTRICT:
5039 blocked = true;
5040 break;
5041 default:
5042 throw new IllegalArgumentException();
5043 }
5044 if (logger != null) {
5045 logger.networkBlocked(uid, reason);
5046 }
5047
5048 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005049 }
5050
Felipe Lemed17fda42016-04-29 11:12:45 -07005051 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5052
5053 @Override
5054 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005055 synchronized (mUidRulesFirstLock) {
5056 boolean changed = removeUserStateUL(userId, false);
5057 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005058 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005059 synchronized (mNetworkPoliciesSecondLock) {
5060 writePolicyAL();
5061 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005062 }
5063 }
5064 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005065
5066 /**
5067 * @return true if the given uid is restricted from doing networking on metered networks.
5068 */
5069 @Override
5070 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5071 final int uidRules;
5072 final boolean isBackgroundRestricted;
5073 synchronized (mUidRulesFirstLock) {
5074 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5075 isBackgroundRestricted = mRestrictBackground;
5076 }
5077 return isBackgroundRestricted
5078 && !hasRule(uidRules, RULE_ALLOW_METERED)
5079 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5080 }
5081
5082 /**
5083 * @return true if networking is blocked on the given interface for the given uid according
5084 * to current networking policies.
5085 */
5086 @Override
5087 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005088 final long startTime = mStatLogger.getTime();
5089
junyulai05986c62018-08-07 19:50:45 +08005090 final int uidRules;
5091 final boolean isBackgroundRestricted;
5092 synchronized (mUidRulesFirstLock) {
5093 uidRules = mUidRules.get(uid, RULE_NONE);
5094 isBackgroundRestricted = mRestrictBackground;
5095 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005096 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005097 synchronized (mNetworkPoliciesSecondLock) {
5098 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005099 }
junyulai05986c62018-08-07 19:50:45 +08005100 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5101 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005102
5103 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5104
5105 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005106 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005107
5108 @Override
5109 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5110 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005111 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005112 if (added) {
5113 mPowerSaveTempWhitelistAppIds.put(appId, true);
5114 } else {
5115 mPowerSaveTempWhitelistAppIds.delete(appId);
5116 }
5117 updateRulesForTempWhitelistChangeUL(appId);
5118 }
5119 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005120
5121 @Override
5122 public SubscriptionPlan getSubscriptionPlan(Network network) {
5123 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005124 final int subId = getSubIdLocked(network);
5125 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005126 }
5127 }
5128
5129 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005130 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5131 synchronized (mNetworkPoliciesSecondLock) {
5132 final int subId = findRelevantSubIdNL(template);
5133 return getPrimarySubscriptionPlanLocked(subId);
5134 }
5135 }
5136
5137 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005138 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005139 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005140 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005141 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005142 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005143 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005144 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5145 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5146 }
5147
5148 if (quotaType == QUOTA_TYPE_JOBS) {
5149 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5150 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5151 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5152 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5153 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5154 } else {
5155 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5156 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005157 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005158
5159 @Override
5160 public void onAdminDataAvailable() {
5161 mAdminDataAvailableLatch.countDown();
5162 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005163
5164 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005165 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5166 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5167 }
5168
5169 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005170 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5171 setMeteredRestrictedPackagesInternal(packageNames, userId);
5172 }
5173
5174 @Override
5175 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5176 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5177 userId, 0, packageNames).sendToTarget();
5178 }
5179 }
5180
5181 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5182 synchronized (mUidRulesFirstLock) {
5183 final Set<Integer> newRestrictedUids = new ArraySet<>();
5184 for (String packageName : packageNames) {
5185 final int uid = getUidForPackage(packageName, userId);
5186 if (uid >= 0) {
5187 newRestrictedUids.add(uid);
5188 }
5189 }
5190 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5191 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5192 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5193 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5194 }
5195 }
5196
5197 private int getUidForPackage(String packageName, int userId) {
5198 try {
5199 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5200 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5201 } catch (NameNotFoundException e) {
5202 return -1;
5203 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005204 }
5205
5206 private int parseSubId(NetworkState state) {
5207 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5208 int subId = INVALID_SUBSCRIPTION_ID;
5209 if (state != null && state.networkCapabilities != null
5210 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5211 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5212 if (spec instanceof StringNetworkSpecifier) {
5213 try {
5214 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5215 } catch (NumberFormatException e) {
5216 }
5217 }
5218 }
5219 return subId;
5220 }
5221
Andreas Gampea36dc622018-02-05 17:19:22 -08005222 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005223 private int getSubIdLocked(Network network) {
5224 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005225 }
5226
Andreas Gampea36dc622018-02-05 17:19:22 -08005227 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005228 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5229 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005230 if (!ArrayUtils.isEmpty(plans)) {
5231 for (SubscriptionPlan plan : plans) {
5232 if (plan.getCycleRule().isRecurring()) {
5233 // Recurring plans will always have an active cycle
5234 return plan;
5235 } else {
5236 // Non-recurring plans need manual test for active cycle
5237 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5238 if (cycle.contains(ZonedDateTime.now(mClock))) {
5239 return plan;
5240 }
5241 }
5242 }
5243 }
5244 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005245 }
5246
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005247 /**
5248 * This will only ever be called once - during device boot.
5249 */
5250 private void waitForAdminData() {
5251 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5252 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5253 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5254 }
5255 }
5256
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005257 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5258 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005259 if (!mNetworkManagerReady) {
5260 return;
5261 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005262 if (oldRestrictedUids == null) {
5263 for (int uid : newRestrictedUids) {
5264 updateRulesForDataUsageRestrictionsUL(uid);
5265 }
5266 return;
5267 }
5268 for (int uid : oldRestrictedUids) {
5269 if (!newRestrictedUids.contains(uid)) {
5270 updateRulesForDataUsageRestrictionsUL(uid);
5271 }
5272 }
5273 for (int uid : newRestrictedUids) {
5274 if (!oldRestrictedUids.contains(uid)) {
5275 updateRulesForDataUsageRestrictionsUL(uid);
5276 }
5277 }
5278 }
5279
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005280 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005281 private boolean isRestrictedByAdminUL(int uid) {
5282 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5283 UserHandle.getUserId(uid));
5284 return restrictedUids != null && restrictedUids.contains(uid);
5285 }
5286
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005287 private static boolean hasRule(int uidRules, int rule) {
5288 return (uidRules & rule) != 0;
5289 }
5290
Jeff Sharkey2e471452018-01-19 18:02:47 +09005291 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5292 return (val != null) ? val : new NetworkState[0];
5293 }
5294
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005295 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5296 String key, boolean defaultValue) {
5297 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5298 }
5299
Heemin Seogb9820d42019-05-21 16:17:43 -07005300 private static boolean isHeadlessSystemUserBuild() {
5301 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
5302 }
5303
Chris Wren193ae6b2017-03-31 15:17:11 -04005304 private class NotificationId {
5305 private final String mTag;
5306 private final int mId;
5307
5308 NotificationId(NetworkPolicy policy, int type) {
5309 mTag = buildNotificationTag(policy, type);
5310 mId = type;
5311 }
5312
5313 @Override
5314 public boolean equals(Object o) {
5315 if (this == o) return true;
5316 if (!(o instanceof NotificationId)) return false;
5317 NotificationId that = (NotificationId) o;
5318 return Objects.equals(mTag, that.mTag);
5319 }
5320
5321 @Override
5322 public int hashCode() {
5323 return Objects.hash(mTag);
5324 }
5325
5326 /**
5327 * Build unique tag that identifies an active {@link NetworkPolicy}
5328 * notification of a specific type, like {@link #TYPE_LIMIT}.
5329 */
5330 private String buildNotificationTag(NetworkPolicy policy, int type) {
5331 return TAG + ":" + policy.template.hashCode() + ":" + type;
5332 }
5333
5334 public String getTag() {
5335 return mTag;
5336 }
5337
5338 public int getId() {
5339 return mId;
5340 }
5341 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005342}