blob: 6c34e1313f73235df8a1b8e9a799c93c6231437f [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;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600235import libcore.util.EmptyArray;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600236
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238import org.xmlpull.v1.XmlSerializer;
239
240import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700241import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242import java.io.FileInputStream;
243import java.io.FileNotFoundException;
244import java.io.FileOutputStream;
245import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700246import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700247import java.lang.annotation.Retention;
248import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100249import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700250import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900251import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600252import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700253import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600254import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900255import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700256import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600257import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700258import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600259import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400260import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800261import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800262import java.util.concurrent.CountDownLatch;
263import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700265/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 * Service that maintains low-level network policy rules, using
267 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700268 * <p>
269 * Derives active rules by combining a given policy with other system status,
270 * and delivers to listeners, such as {@link ConnectivityManager}, for
271 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700272 *
273 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700274 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700275 * <ul>
276 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
277 * rules).
278 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
279 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700280 * </ul>
281 *
282 * <p>
283 * As such, methods that require synchronization have the following prefixes:
284 * <ul>
285 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
286 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000287 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
288 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700289 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700290 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700292 static final String TAG = NetworkPolicyLogger.TAG;
293 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
294 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700295
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900296 /**
297 * No opportunistic quota could be calculated from user data plan or data settings.
298 */
299 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
300
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 private static final int VERSION_INIT = 1;
302 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700303 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800304 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800305 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800306 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700307 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700308 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700309 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700310 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600311 private static final int VERSION_ADDED_CYCLE = 11;
312 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400315 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400317 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400319 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900320 @VisibleForTesting
321 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700322
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 private static final String TAG_POLICY_LIST = "policy-list";
324 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600325 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700326 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700327 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800328 private static final String TAG_WHITELIST = "whitelist";
329 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800330 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331
332 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700333 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
335 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700336 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600337 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
338 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
339 private static final String ATTR_CYCLE_START = "cycleStart";
340 private static final String ATTR_CYCLE_END = "cycleEnd";
341 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private static final String ATTR_WARNING_BYTES = "warningBytes";
343 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700344 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800345 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
346 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800347 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700348 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700349 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700350 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700351 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600352 private static final String ATTR_SUB_ID = "subId";
353 private static final String ATTR_TITLE = "title";
354 private static final String ATTR_SUMMARY = "summary";
355 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
356 private static final String ATTR_USAGE_BYTES = "usageBytes";
357 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600358 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800360 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800361 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800362 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800363 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700364 private static final String ACTION_SNOOZE_RAPID =
365 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700366
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800367 /**
368 * Indicates the maximum wait time for admin data to be available;
369 */
370 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
371
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600372 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
373 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
374 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
375 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
376
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700377 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700378 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800379 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800380 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700381 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700382 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
383 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700384 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700385 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900386 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800387 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700388 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700389
Makoto Onuki8e777332017-03-28 11:25:47 -0700390 private static final int UID_MSG_STATE_CHANGED = 100;
391 private static final int UID_MSG_GONE = 101;
392
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600393 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
394
Jeff Sharkey75279902011-05-24 18:39:45 -0700395 private final Context mContext;
396 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700397 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700398 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700399 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700400 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700401 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700402 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403
404 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700405 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700406 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800407 @GuardedBy("mUidRulesFirstLock")
408 private PowerSaveState mRestrictBackgroundPowerState;
409
410 // Store the status of restrict background before turning on battery saver.
411 // Used to restore mRestrictBackground when battery saver is turned off.
412 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700413
Sudheer Shanka543339f2017-07-28 15:18:07 -0700414 // Denotes the status of restrict background read from disk.
415 private boolean mLoadedRestrictBackground;
416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 // See main javadoc for instructions on how to use these locks.
418 final Object mUidRulesFirstLock = new Object();
419 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700421 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
422 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700423
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
425 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
426 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800427 // Store whether user flipped restrict background in battery saver mode
428 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700429
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700430 private final boolean mSuppressDefaultPolicy;
431
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800432 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
433
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700434 private volatile boolean mNetworkManagerReady;
435
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700436 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600437 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800438 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700439
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600440 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600441 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600442 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600443 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600444 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600445 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600446
Jeff Sharkey9252b342018-01-19 07:58:35 +0900447 /** Map from subId to daily opportunistic quota. */
448 @GuardedBy("mNetworkPoliciesSecondLock")
449 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
450
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700451 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700453 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700454 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700455
Felipe Lemef0823852016-06-08 13:43:08 -0700456 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700457 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700459 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700460 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800461 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700462
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700463 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700465 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
466
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800467 // "Power save mode" is the concept used in the DeviceIdleController that includes various
468 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
469 // and "battery saver" are not equivalent.
470
Jeff Sharkey32566012014-12-02 18:30:14 -0800471 /**
472 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700473 * in power save mode, except device idle (doze) still applies.
474 * TODO: An int array might be sufficient
475 */
Felipe Lemef0823852016-06-08 13:43:08 -0700476 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700477 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
478
479 /**
480 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800481 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700482 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800483 */
Felipe Lemef0823852016-06-08 13:43:08 -0700484 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700485 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700486
Felipe Lemef0823852016-06-08 13:43:08 -0700487 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700488 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
489
Felipe Lemeb85a6372016-01-14 16:16:16 -0800490 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800491 * UIDs that have been white-listed temporarily to be able to have network access despite being
492 * idle. Other power saving restrictions still apply.
493 */
494 @GuardedBy("mUidRulesFirstLock")
495 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
496
497 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800498 * UIDs that have been initially white-listed by system to avoid restricted background.
499 */
Felipe Lemef0823852016-06-08 13:43:08 -0700500 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800501 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
502 new SparseBooleanArray();
503
504 /**
505 * UIDs that have been initially white-listed by system to avoid restricted background,
506 * but later revoked by user.
507 */
Felipe Lemef0823852016-06-08 13:43:08 -0700508 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800509 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
510 new SparseBooleanArray();
511
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700512 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700513 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800514 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700515 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700516 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800517 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700518
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700519 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700520 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400521 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700522
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700523 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700524 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800525 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700526
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600527 /** Map from network ID to last observed meteredness state */
528 @GuardedBy("mNetworkPoliciesSecondLock")
529 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900530 /** Map from network ID to last observed roaming state */
531 @GuardedBy("mNetworkPoliciesSecondLock")
532 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
533
Jeff Sharkey9252b342018-01-19 07:58:35 +0900534 /** Map from netId to subId as of last update */
535 @GuardedBy("mNetworkPoliciesSecondLock")
536 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
537
Jeff Sharkey146bb332018-04-18 15:42:57 -0600538 /** Map from subId to subscriberId as of last update */
539 @GuardedBy("mNetworkPoliciesSecondLock")
540 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
541 /** Set of all merged subscriberId as of last update */
542 @GuardedBy("mNetworkPoliciesSecondLock")
543 private String[] mMergedSubscriberIds = EmptyArray.STRING;
544
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800545 /**
546 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
547 * userId to restricted uids which belong to that user.
548 */
549 @GuardedBy("mUidRulesFirstLock")
550 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
551
Jeff Sharkey32566012014-12-02 18:30:14 -0800552 private final RemoteCallbackList<INetworkPolicyListener>
553 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700554
Dianne Hackborn497175b2014-07-01 12:56:08 -0700555 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700556 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800557 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700558
559 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700560
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700561 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700562 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700563
Svet Ganov16a16892015-04-16 10:32:04 -0700564 private final AppOpsManager mAppOps;
565
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800566 private final IPackageManager mIPm;
567
Sudheer Shankae7361852017-03-07 11:51:46 -0800568 private ActivityManagerInternal mActivityManagerInternal;
569
Sudheer Shanka352dc572017-09-22 17:09:38 -0700570 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800571
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700572 // TODO: keep whitelist of system-critical services that should never have
573 // rules enforced, such as system, phone, and radio UIDs.
574
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700575 // TODO: migrate notifications to SystemUI
576
Makoto Onuki49392d32018-04-11 13:51:02 -0700577
578 interface Stats {
579 int UPDATE_NETWORK_ENABLED = 0;
580 int IS_UID_NETWORKING_BLOCKED = 1;
581
582 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
583 }
584
585 public final StatLogger mStatLogger = new StatLogger(new String[] {
586 "updateNetworkEnabledNL()",
587 "isUidNetworkingBlocked()",
588 });
589
Jeff Sharkey75279902011-05-24 18:39:45 -0700590 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700591 INetworkManagementService networkManagement) {
592 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
593 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700594 }
595
Jeff Sharkey9911a282018-02-14 22:29:11 -0700596 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700597 return new File(Environment.getDataDirectory(), "system");
598 }
599
Jeff Sharkey9911a282018-02-14 22:29:11 -0700600 private static @NonNull Clock getDefaultClock() {
601 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
602 Clock.systemUTC());
603 }
604
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700605 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700606 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
607 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700608 mContext = checkNotNull(context, "missing context");
609 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700611 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700612 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700613 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700614 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700615 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700616 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700617
Amith Yamasani450a16b2013-09-18 16:28:50 -0700618 HandlerThread thread = new HandlerThread(TAG);
619 thread.start();
620 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700621
Makoto Onuki8e777332017-03-28 11:25:47 -0700622 // We create another thread for the UID events, which are more time-critical.
623 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
624 /*allowIo=*/ false);
625 mUidEventThread.start();
626 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
627
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700628 mSuppressDefaultPolicy = suppressDefaultPolicy;
629
Dianne Hackborne17b4452018-01-10 13:15:40 -0800630 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700631
632 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800633
Felipe Lemed17fda42016-04-29 11:12:45 -0700634 // Expose private service for system components to use.
635 LocalServices.addService(NetworkPolicyManagerInternal.class,
636 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700637 }
638
639 public void bindConnectivityManager(IConnectivityManager connManager) {
640 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700641 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700642
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700643 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700644 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700645 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700646 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
647 mPowerSaveWhitelistExceptIdleAppIds.clear();
648 if (whitelist != null) {
649 for (int uid : whitelist) {
650 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
651 }
652 }
653 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700654 mPowerSaveWhitelistAppIds.clear();
655 if (whitelist != null) {
656 for (int uid : whitelist) {
657 mPowerSaveWhitelistAppIds.put(uid, true);
658 }
659 }
660 } catch (RemoteException e) {
661 }
662 }
663
Felipe Lemea9505cc2016-02-26 10:28:41 -0800664 /**
665 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
666 * revoke the whitelist.
667 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700668 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800669 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700670 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700671 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800672 final List<UserInfo> users = mUserManager.getUsers();
673 final int numberUsers = users.size();
674
Felipe Lemea110eec2016-04-29 09:58:06 -0700675 boolean changed = false;
676 for (int i = 0; i < numberUsers; i++) {
677 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700678 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700679 }
680 return changed;
681 }
682
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700683 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700684 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700685 final SystemConfig sysConfig = SystemConfig.getInstance();
686 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800687 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
688 boolean changed = false;
689 for (int i = 0; i < allowDataUsage.size(); i++) {
690 final String pkg = allowDataUsage.valueAt(i);
691 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700692 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
693 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800694 final ApplicationInfo app;
695 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700696 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800697 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700698 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
699 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800700 continue;
701 }
702 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700703 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
704 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800705 continue;
706 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700707 final int uid = UserHandle.getUid(userId, app.uid);
708 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
709 if (LOGD)
710 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
711 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800712 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700713 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700714 if (LOGD)
715 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
716 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700717 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700718 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800719 }
720 }
721 return changed;
722 }
723
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800724 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700725 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800726 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700727 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800728 // Boost thread's priority during system server init
729 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700730 if (!isBandwidthControlEnabled()) {
731 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
732 return;
733 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700734
Felipe Leme873a83a2016-09-07 11:34:10 -0700735 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700736 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700737
Felipe Leme873a83a2016-09-07 11:34:10 -0700738 synchronized (mUidRulesFirstLock) {
739 synchronized (mNetworkPoliciesSecondLock) {
740 updatePowerSaveWhitelistUL();
741 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
742 mPowerManagerInternal.registerLowPowerModeObserver(
743 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800744 @Override
745 public int getServiceType() {
746 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700747 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800748
749 @Override
750 public void onLowPowerModeChanged(PowerSaveState result) {
751 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800752 if (LOGD) {
753 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
754 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800755 synchronized (mUidRulesFirstLock) {
756 if (mRestrictPower != enabled) {
757 mRestrictPower = enabled;
758 updateRulesForRestrictPowerUL();
759 }
760 }
761 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800762 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800763 mRestrictPower = mPowerManagerInternal.getLowPowerState(
764 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700765
766 mSystemReady = true;
767
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800768 waitForAdminData();
769
Felipe Leme873a83a2016-09-07 11:34:10 -0700770 // read policy from disk
771 readPolicyAL();
772
jackqdyulei29c82ab2017-03-10 14:09:16 -0800773 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700774 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800775 mRestrictBackgroundPowerState = mPowerManagerInternal
776 .getLowPowerState(ServiceType.DATA_SAVER);
777 final boolean localRestrictBackground =
778 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700779 if (localRestrictBackground && !mLoadedRestrictBackground) {
780 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800781 }
782 mPowerManagerInternal.registerLowPowerModeObserver(
783 new PowerManagerInternal.LowPowerModeListener() {
784 @Override
785 public int getServiceType() {
786 return ServiceType.DATA_SAVER;
787 }
788
789 @Override
790 public void onLowPowerModeChanged(PowerSaveState result) {
791 synchronized (mUidRulesFirstLock) {
792 updateRestrictBackgroundByLowPowerModeUL(result);
793 }
794 }
795 });
796
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
798 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700799 }
Felipe Lemef0823852016-06-08 13:43:08 -0700800
Sudheer Shanka543339f2017-07-28 15:18:07 -0700801 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700802 updateRulesForGlobalChangeAL(false);
803 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700804 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800805 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700806
Sudheer Shankae7361852017-03-07 11:51:46 -0800807 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700808 try {
809 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000810 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700811 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 mNetworkManager.registerObserver(mAlertObserver);
813 } catch (RemoteException e) {
814 // ignored; both services live in system_server
815 }
816
817 // listen for changes to power save whitelist
818 final IntentFilter whitelistFilter = new IntentFilter(
819 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
820 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
821
Felipe Leme873a83a2016-09-07 11:34:10 -0700822 // watch for network interfaces to be claimed
823 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
824 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
825
826 // listen for package changes to update policy
827 final IntentFilter packageFilter = new IntentFilter();
828 packageFilter.addAction(ACTION_PACKAGE_ADDED);
829 packageFilter.addDataScheme("package");
830 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
831
832 // listen for UID changes to update policy
833 mContext.registerReceiver(
834 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
835
836 // listen for user changes to update policy
837 final IntentFilter userFilter = new IntentFilter();
838 userFilter.addAction(ACTION_USER_ADDED);
839 userFilter.addAction(ACTION_USER_REMOVED);
840 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
841
842 // listen for stats update events
843 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
844 mContext.registerReceiver(
845 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
846
847 // listen for restrict background changes from notifications
848 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
849 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
850
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700851 // Listen for snooze from notifications
852 mContext.registerReceiver(mSnoozeReceiver,
853 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
854 mContext.registerReceiver(mSnoozeReceiver,
855 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700856
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600857 // listen for configured wifi networks to be loaded
858 final IntentFilter wifiFilter =
859 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
860 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700861
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700862 // listen for carrier config changes to update data cycle information
863 final IntentFilter carrierConfigFilter = new IntentFilter(
864 ACTION_CARRIER_CONFIG_CHANGED);
865 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
866
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600867 // listen for meteredness changes
868 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
869 new NetworkRequest.Builder().build(), mNetworkCallback);
870
Felipe Leme873a83a2016-09-07 11:34:10 -0700871 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600872
873 // Listen for subscriber changes
874 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
875 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
876 @Override
877 public void onSubscriptionsChanged() {
878 updateNetworksInternal();
879 }
880 });
881
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800882 // tell systemReady() that the service has been initialized
883 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700884 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800885 // Restore the default priority after init is done
886 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700887 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700888 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700889 }
890
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800891 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700892 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800893 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
894 mHandler.post(() -> initService(initCompleteSignal));
895 return initCompleteSignal;
896 }
897
898 public void systemReady(CountDownLatch initCompleteSignal) {
899 // wait for initService to complete
900 try {
901 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
902 throw new IllegalStateException("Service " + TAG +" init timeout");
903 }
904 } catch (InterruptedException e) {
905 Thread.currentThread().interrupt();
906 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
907 }
908 }
909
Sudheer Shankac9d94072017-02-22 22:13:55 +0000910 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700911 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700912 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
913 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700914 }
915
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700916 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700917 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700918 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700919
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700920 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700921 }
922
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700923 @Override public void onUidIdle(int uid, boolean disabled) {
924 }
925
926 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700928 };
929
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700931 @Override
932 public void onReceive(Context context, Intent intent) {
933 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700934 synchronized (mUidRulesFirstLock) {
935 updatePowerSaveWhitelistUL();
936 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700937 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700938 }
939 }
940 };
941
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700942 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700943 @Override
944 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700945 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700946
947 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700948 final int uid = intent.getIntExtra(EXTRA_UID, -1);
949 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700950
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700951 if (ACTION_PACKAGE_ADDED.equals(action)) {
952 // update rules for UID, since it might be subject to
953 // global background data policy
954 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700955 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700956 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700957 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700958 }
959 }
960 };
961
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700963 @Override
964 public void onReceive(Context context, Intent intent) {
965 // on background handler thread, and UID_REMOVED is protected
966
967 final int uid = intent.getIntExtra(EXTRA_UID, -1);
968 if (uid == -1) return;
969
970 // remove any policy and update rules to clean up
971 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700972 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700973 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700974 synchronized (mNetworkPoliciesSecondLock) {
975 writePolicyAL();
976 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700977 }
978 }
979 };
980
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700981 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700982 @Override
983 public void onReceive(Context context, Intent intent) {
984 // on background handler thread, and USER_ADDED and USER_REMOVED
985 // broadcasts are protected
986
987 final String action = intent.getAction();
988 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
989 if (userId == -1) return;
990
Amith Yamasani15e472352015-04-24 19:06:07 -0700991 switch (action) {
992 case ACTION_USER_REMOVED:
993 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700994 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800995 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700996 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700997 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800998 // Removing outside removeUserStateUL since that can also be called when
999 // user resets app preferences.
1000 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001001 if (action == ACTION_USER_ADDED) {
1002 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001003 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001004 }
1005 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001006 synchronized (mNetworkPoliciesSecondLock) {
1007 updateRulesForGlobalChangeAL(true);
1008 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001009 }
1010 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001011 }
1012 }
1013 };
1014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001015 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 * Receiver that watches for {@link INetworkStatsService} updates, which we
1017 * use to check against {@link NetworkPolicy#warningBytes}.
1018 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001019 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 @Override
1021 public void onReceive(Context context, Intent intent) {
1022 // on background handler thread, and verified
1023 // READ_NETWORK_USAGE_HISTORY permission above.
1024
Felipe Lemef0823852016-06-08 13:43:08 -07001025 synchronized (mNetworkPoliciesSecondLock) {
1026 updateNetworkEnabledNL();
1027 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 }
1029 }
1030 };
1031
1032 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001033 * Receiver that watches for {@link Notification} control of
1034 * {@link #mRestrictBackground}.
1035 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001036 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1040 // permission above.
1041
1042 setRestrictBackground(false);
1043 }
1044 };
1045
1046 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001047 * Receiver that watches for {@link Notification} control of
1048 * {@link NetworkPolicy#lastWarningSnooze}.
1049 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001050 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 @Override
1052 public void onReceive(Context context, Intent intent) {
1053 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1054 // permission above.
1055
1056 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001057 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1058 performSnooze(template, TYPE_WARNING);
1059 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1060 performSnooze(template, TYPE_RAPID);
1061 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001062 }
1063 };
1064
1065 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001066 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001067 * we can perform upgrade logic. After initial upgrade logic, it updates
1068 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001069 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001070 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001071 @Override
1072 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001073 synchronized (mUidRulesFirstLock) {
1074 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001075 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001076 }
1077 }
1078 // Only need to perform upgrade logic once
1079 mContext.unregisterReceiver(this);
1080 }
1081 };
1082
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001083 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1084 Network network) {
1085 final boolean lastValue = lastValues.get(network.netId, false);
1086 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1087 if (changed) {
1088 lastValues.put(network.netId, newValue);
1089 }
1090 return changed;
1091 }
1092
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001093 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1094 @Override
1095 public void onCapabilitiesChanged(Network network,
1096 NetworkCapabilities networkCapabilities) {
1097 if (network == null || networkCapabilities == null) return;
1098
1099 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001100 final boolean newMetered = !networkCapabilities
1101 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001102 final boolean meteredChanged = updateCapabilityChange(
1103 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001104
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001105 final boolean newRoaming = !networkCapabilities
1106 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1107 final boolean roamingChanged = updateCapabilityChange(
1108 mNetworkRoaming, newRoaming, network);
1109
1110 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001111 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001112 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001113 }
1114 }
1115 }
1116 };
1117
1118 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 * Observer that watches for {@link INetworkManagementService} alerts.
1120 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001121 final private INetworkManagementEventObserver mAlertObserver
1122 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 @Override
1124 public void limitReached(String limitName, String iface) {
1125 // only someone like NMS should be calling us
1126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1127
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001128 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1129 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001130 }
1131 }
1132 };
1133
1134 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1136 * to show visible notifications as needed.
1137 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001138 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001139 void updateNotificationsNL() {
1140 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001141 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001143 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001144 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146
1147 // TODO: when switching to kernel notifications, compute next future
1148 // cycle boundary to recompute notifications.
1149
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001150 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001151 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1153 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001154 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001155
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001157 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001158 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159
Jeff Sharkey53313d72017-07-13 16:47:32 -06001160 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1161 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001162 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1163 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1164 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001165
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001166 // Carrier might want to manage notifications themselves
1167 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001168 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1169 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1170 // Don't show notifications until we confirm that the loaded config is from an
1171 // identified carrier, which may want to manage their own notifications. This method
1172 // should be called every time the carrier config changes anyways, and there's no
1173 // reason to alert if there isn't a carrier.
1174 return;
1175 }
1176
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001177 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1178 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1179 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1180 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1181 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1182 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1183
1184 // Notify when data usage is over warning
1185 if (notifyWarning) {
1186 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1187 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1188 if (!snoozedThisCycle) {
1189 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1190 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001192 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001194 // Notify when data usage is over limit
1195 if (notifyLimit) {
1196 if (policy.isOverLimit(totalBytes)) {
1197 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1198 if (snoozedThisCycle) {
1199 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1200 } else {
1201 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1202 notifyOverLimitNL(policy.template);
1203 }
1204 } else {
1205 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 }
1207 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001208
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001209 // Warn if average usage over last 4 days is on track to blow pretty
1210 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001211 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001212 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001213 final long recentStart = now - recentDuration;
1214 final long recentEnd = now;
1215 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001216
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001217 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001218 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001219 final long alertBytes = (policy.limitBytes * 3) / 2;
1220
1221 if (LOGD) {
1222 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1223 + projectedBytes + " alert " + alertBytes);
1224 }
1225
1226 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1227 - DateUtils.DAY_IN_MILLIS;
1228 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001229 enqueueNotification(policy, TYPE_RAPID, 0,
1230 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001231 }
1232 }
1233 }
1234
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001235 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001236 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001237 final NotificationId notificationId = beforeNotifs.valueAt(i);
1238 if (!mActiveNotifs.contains(notificationId)) {
1239 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 }
1241 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001242
1243 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001244 }
1245
1246 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001247 * Attempt to find a specific app to blame for rapid data usage during the
1248 * given time period.
1249 */
1250 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1251 long start, long end) {
1252 long totalBytes = 0;
1253 long maxBytes = 0;
1254 int maxUid = 0;
1255
1256 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1257 NetworkStats.Entry entry = null;
1258 for (int i = 0; i < stats.size(); i++) {
1259 entry = stats.getValues(i, entry);
1260 final long bytes = entry.rxBytes + entry.txBytes;
1261 totalBytes += bytes;
1262 if (bytes > maxBytes) {
1263 maxBytes = bytes;
1264 maxUid = entry.uid;
1265 }
1266 }
1267
1268 // Only point blame if the majority of usage was done by a single app.
1269 // TODO: support shared UIDs
1270 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1271 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001272 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001273 try {
1274 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1275 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1276 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1277 } catch (NameNotFoundException ignored) {
1278 }
1279 }
1280 }
1281
1282 return null;
1283 }
1284
1285 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001286 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001287 * current device state, such as when
1288 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1289 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001290 *
1291 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1292 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001293 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001294 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001295 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001296 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001297 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1298 final int subId = mSubIdToSubscriberId.keyAt(i);
1299 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001300 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1301 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1302 true);
1303 if (template.matches(probeIdent)) {
1304 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001305 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001306 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001307 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001308 }
1309
1310 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001311 * Notify that given {@link NetworkTemplate} is over
1312 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1313 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001314 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001315 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001316 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001317 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001318 mOverLimitNotified.add(template);
1319 }
1320 }
1321
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001322 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001323 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001324 mOverLimitNotified.remove(template);
1325 }
1326
1327 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001328 * Show notification for combined {@link NetworkPolicy} and specific type,
1329 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1330 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001331 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1332 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001333 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001334 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001335 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001336 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001337 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001338 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001339 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001340
1341 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001342 final CharSequence title;
1343 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001344 switch (type) {
1345 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001346 title = res.getText(R.string.data_usage_warning_title);
1347 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001348 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001349
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001350 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001351
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001352 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1353 builder.setDeleteIntent(PendingIntent.getBroadcast(
1354 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1355
Wei Liu546cb772016-07-21 16:19:01 -07001356 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001357 // TODO: Resolve to single code path.
1358 if (isHeadlessSystemUserBuild()) {
1359 builder.setContentIntent(PendingIntent.getActivityAsUser(
1360 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1361 /* options= */ null, UserHandle.CURRENT));
1362 } else {
1363 builder.setContentIntent(PendingIntent.getActivity(
1364 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1365 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001366 break;
1367 }
1368 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001369 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001370 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001371 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001372 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001373 case MATCH_WIFI:
1374 title = res.getText(R.string.data_usage_wifi_limit_title);
1375 break;
1376 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001377 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001378 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001379 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001380
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001381 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001382 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001383
Wei Liu546cb772016-07-21 16:19:01 -07001384 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001385 // TODO: Resolve to single code path.
1386 if (isHeadlessSystemUserBuild()) {
1387 builder.setContentIntent(PendingIntent.getActivityAsUser(
1388 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1389 /* options= */ null, UserHandle.CURRENT));
1390 } else {
1391 builder.setContentIntent(PendingIntent.getActivity(
1392 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1393 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001394 break;
1395 }
1396 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001397 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001398 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1400 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001401 case MATCH_WIFI:
1402 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1403 break;
1404 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001405 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001406 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001407 final long overBytes = totalBytes - policy.limitBytes;
1408 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001409 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001410
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001411 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001412 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001413 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001414
Wei Liu546cb772016-07-21 16:19:01 -07001415 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001416 // TODO: Resolve to single code path.
1417 if (isHeadlessSystemUserBuild()) {
1418 builder.setContentIntent(PendingIntent.getActivityAsUser(
1419 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1420 /* options= */ null, UserHandle.CURRENT));
1421 } else {
1422 builder.setContentIntent(PendingIntent.getActivity(
1423 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1424 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001425 break;
1426 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001427 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001428 title = res.getText(R.string.data_usage_rapid_title);
1429 if (rapidBlame != null) {
1430 body = res.getString(R.string.data_usage_rapid_app_body,
1431 rapidBlame.loadLabel(mContext.getPackageManager()));
1432 } else {
1433 body = res.getString(R.string.data_usage_rapid_body);
1434 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001435
Jeff Sharkey2e471452018-01-19 18:02:47 +09001436 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001437
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001438 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1439 builder.setDeleteIntent(PendingIntent.getBroadcast(
1440 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1441
1442 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001443 // TODO: Resolve to single code path.
1444 if (isHeadlessSystemUserBuild()) {
1445 builder.setContentIntent(PendingIntent.getActivityAsUser(
1446 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1447 /* options= */ null, UserHandle.CURRENT));
1448 } else {
1449 builder.setContentIntent(PendingIntent.getActivity(
1450 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1451 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001452 break;
1453 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001454 default: {
1455 return;
1456 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001457 }
1458
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001459 builder.setTicker(title);
1460 builder.setContentTitle(title);
1461 builder.setContentText(body);
1462 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001463
1464 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1465 notificationId.getId(), builder.build(), UserHandle.ALL);
1466 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001467 }
1468
Chris Wren193ae6b2017-03-31 15:17:11 -04001469 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001470 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1471 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001472 }
1473
1474 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001476 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001477 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001478 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001479 @Override
1480 public void onReceive(Context context, Intent intent) {
1481 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1482 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001483 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484 }
1485 };
1486
Jeff Sharkey146bb332018-04-18 15:42:57 -06001487 private void updateNetworksInternal() {
1488 // Get all of our cross-process communication with telephony out of
1489 // the way before we acquire internal locks.
1490 updateSubscriptions();
1491
1492 synchronized (mUidRulesFirstLock) {
1493 synchronized (mNetworkPoliciesSecondLock) {
1494 ensureActiveMobilePolicyAL();
1495 normalizePoliciesNL();
1496 updateNetworkEnabledNL();
1497 updateNetworkRulesNL();
1498 updateNotificationsNL();
1499 }
1500 }
1501 }
1502
Jeff Sharkey2e471452018-01-19 18:02:47 +09001503 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001504 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001505 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001506 final CountDownLatch latch = new CountDownLatch(1);
1507 mHandler.post(() -> {
1508 latch.countDown();
1509 });
1510 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001511 }
1512
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001513 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001514 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1515 * if necessary.
1516 *
1517 * @param subId that has its associated NetworkPolicy updated if necessary
1518 * @return if any policies were updated
1519 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001520 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001521 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001522 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001523
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001524 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001525 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001526 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001527 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001528 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1529 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1530 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001531 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1532 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001533 }
1534 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001535 return policyUpdated;
1536 }
1537
1538 /**
1539 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1540 *
1541 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1542 * to do so, it returns the fallback value.
1543 *
1544 * @param config The CarrierConfig to read the value from.
1545 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1546 * @return cycleDay to use in the mobile NetworkPolicy.
1547 */
1548 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001549 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001550 int fallbackCycleDay) {
1551 if (config == null) {
1552 return fallbackCycleDay;
1553 }
1554 int cycleDay =
1555 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1556 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1557 return fallbackCycleDay;
1558 }
1559 // validate cycleDay value
1560 final Calendar cal = Calendar.getInstance();
1561 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1562 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1563 Slog.e(TAG, "Invalid date in "
1564 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1565 return fallbackCycleDay;
1566 }
1567 return cycleDay;
1568 }
1569
1570 /**
1571 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1572 *
1573 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1574 * to do so, it returns the fallback value.
1575 *
1576 * @param config The CarrierConfig to read the value from.
1577 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1578 * @return warningBytes to use in the mobile NetworkPolicy.
1579 */
1580 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001581 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001582 long fallbackWarningBytes) {
1583 if (config == null) {
1584 return fallbackWarningBytes;
1585 }
1586 long warningBytes =
1587 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1588
1589 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1590 return WARNING_DISABLED;
1591 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1592 return getPlatformDefaultWarningBytes();
1593 } else if (warningBytes < 0) {
1594 Slog.e(TAG, "Invalid value in "
1595 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1596 + "non-negative value but got: " + warningBytes);
1597 return fallbackWarningBytes;
1598 }
1599
1600 return warningBytes;
1601 }
1602
1603 /**
1604 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1605 *
1606 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1607 * to do so, it returns the fallback value.
1608 *
1609 * @param config The CarrierConfig to read the value from.
1610 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1611 * @return limitBytes to use in the mobile NetworkPolicy.
1612 */
1613 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001614 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001615 long fallbackLimitBytes) {
1616 if (config == null) {
1617 return fallbackLimitBytes;
1618 }
1619 long limitBytes =
1620 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1621
1622 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1623 return LIMIT_DISABLED;
1624 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1625 return getPlatformDefaultLimitBytes();
1626 } else if (limitBytes < 0) {
1627 Slog.e(TAG, "Invalid value in "
1628 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1629 + "non-negative value but got: " + limitBytes);
1630 return fallbackLimitBytes;
1631 }
1632 return limitBytes;
1633 }
1634
1635 /**
1636 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1637 */
1638 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1639 @Override
1640 public void onReceive(Context context, Intent intent) {
1641 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1642 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1643
1644 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1645 return;
1646 }
1647 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001648
1649 // Get all of our cross-process communication with telephony out of
1650 // the way before we acquire internal locks.
1651 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001652
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001653 synchronized (mUidRulesFirstLock) {
1654 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001655 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1656 if (subscriberId != null) {
1657 ensureActiveMobilePolicyAL(subId, subscriberId);
1658 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1659 } else {
1660 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1661 }
1662
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001663 // update network and notification rules, as the data cycle changed and it's
1664 // possible that we should be triggering warnings/limits now
1665 handleNetworkPoliciesUpdateAL(true);
1666 }
1667 }
1668 }
1669 };
1670
1671 /**
1672 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1673 * one has been updated.
1674 *
1675 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1676 * update.
1677 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001678 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001679 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1680 if (shouldNormalizePolicies) {
1681 normalizePoliciesNL();
1682 }
1683 updateNetworkEnabledNL();
1684 updateNetworkRulesNL();
1685 updateNotificationsNL();
1686 writePolicyAL();
1687 }
1688
1689 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001690 * Proactively control network data connections when they exceed
1691 * {@link NetworkPolicy#limitBytes}.
1692 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001693 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001694 void updateNetworkEnabledNL() {
1695 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001696 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001697
1698 // TODO: reset any policy-disabled networks when any policy is removed
1699 // completely, which is currently rare case.
1700
Makoto Onuki49392d32018-04-11 13:51:02 -07001701 final long startTime = mStatLogger.getTime();
1702
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001703 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1704 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001705 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001706 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001707 setNetworkTemplateEnabled(policy.template, true);
1708 continue;
1709 }
1710
Jeff Sharkey53313d72017-07-13 16:47:32 -06001711 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1712 .cycleIterator(policy).next();
1713 final long start = cycle.first.toInstant().toEpochMilli();
1714 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001715 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001716
1717 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001718 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1719 && policy.lastLimitSnooze < start;
1720 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001721
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001722 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001723 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001724
1725 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001726 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001727 }
1728
1729 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001730 * Proactively disable networks that match the given
1731 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001732 */
1733 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001734 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1735 // held. Call it via the handler.
1736 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1737 .sendToTarget();
1738 }
1739
1740 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001741 // TODO: reach into ConnectivityManager to proactively disable bringing
1742 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001743
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001744 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001745 // If mobile data usage hits the limit or if the user resumes the data, we need to
1746 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001747
Jeff Sharkey146bb332018-04-18 15:42:57 -06001748 final IntArray matchingSubIds = new IntArray();
1749 synchronized (mNetworkPoliciesSecondLock) {
1750 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1751 final int subId = mSubIdToSubscriberId.keyAt(i);
1752 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1753
1754 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1755 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1756 true);
1757 // Template is matched when subscriber id matches.
1758 if (template.matches(probeIdent)) {
1759 matchingSubIds.add(subId);
1760 }
Jack Yu8781b682016-07-08 14:28:51 -07001761 }
1762 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001763
1764 // Only talk with telephony outside of locks
1765 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1766 for (int i = 0; i < matchingSubIds.size(); i++) {
1767 final int subId = matchingSubIds.get(i);
1768 tm.setPolicyDataEnabled(enabled, subId);
1769 }
Jack Yu8781b682016-07-08 14:28:51 -07001770 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001771 }
1772
1773 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001774 * Collect all ifaces from a {@link NetworkState} into the given set.
1775 */
1776 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1777 final String baseIface = state.linkProperties.getInterfaceName();
1778 if (baseIface != null) {
1779 ifaces.add(baseIface);
1780 }
1781 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1782 final String stackedIface = stackedLink.getInterfaceName();
1783 if (stackedIface != null) {
1784 ifaces.add(stackedIface);
1785 }
1786 }
1787 }
1788
1789 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001790 * Examine all currently active subscriptions from
1791 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1792 * internal data structures.
1793 * <p>
1794 * Callers <em>must not</em> hold any locks when this method called.
1795 */
1796 void updateSubscriptions() {
1797 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1798 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1799
1800 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1801 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1802
1803 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
1804 final String[] mergedSubscriberIds = ArrayUtils.defeatNullable(tm.getMergedSubscriberIds());
1805
1806 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1807 for (int subId : subIds) {
1808 final String subscriberId = tm.getSubscriberId(subId);
1809 if (!TextUtils.isEmpty(subscriberId)) {
1810 subIdToSubscriberId.put(subId, subscriberId);
1811 } else {
1812 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1813 }
1814 }
1815
1816 synchronized (mNetworkPoliciesSecondLock) {
1817 mSubIdToSubscriberId.clear();
1818 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1819 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1820 subIdToSubscriberId.valueAt(i));
1821 }
1822
1823 mMergedSubscriberIds = mergedSubscriberIds;
1824 }
1825
1826 Trace.traceEnd(TRACE_TAG_NETWORK);
1827 }
1828
1829 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001830 * Examine all connected {@link NetworkState}, looking for
1831 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1832 * remaining quota based on usage cycle and historical stats.
1833 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001834 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001835 void updateNetworkRulesNL() {
1836 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001837 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001838
1839 final NetworkState[] states;
1840 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001841 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001842 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001843 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 return;
1845 }
1846
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001847 // First, generate identities of all connected networks so we can
1848 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001849 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001850 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001852 if (state.network != null) {
1853 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1854 }
Wei Liub8eaf452016-01-25 10:32:27 -08001855 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001856 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1857 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001858 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001859 }
1860 }
1861
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001862 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001863 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001864
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001865 // For every well-defined policy, compute remaining data based on
1866 // current cycle and historical stats, and push to kernel.
1867 final ArraySet<String> matchingIfaces = new ArraySet<>();
1868 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1869 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1870
1871 // Collect all ifaces that match this policy
1872 matchingIfaces.clear();
1873 for (int j = identified.size() - 1; j >= 0; j--) {
1874 if (policy.template.matches(identified.valueAt(j))) {
1875 collectIfaces(matchingIfaces, identified.keyAt(j));
1876 }
1877 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001878
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001879 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001880 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001881 }
1882
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001883 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001884 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001885 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001886 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001887 if (hasLimit && policy.hasCycle()) {
1888 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1889 .cycleIterator(policy).next();
1890 final long start = cycle.first.toInstant().toEpochMilli();
1891 final long end = cycle.second.toInstant().toEpochMilli();
1892 final long totalBytes = getTotalBytes(policy.template, start, end);
1893
1894 if (policy.lastLimitSnooze >= start) {
1895 // snoozing past quota, but we still need to restrict apps,
1896 // so push really high quota.
1897 quotaBytes = Long.MAX_VALUE;
1898 } else {
1899 // remaining "quota" bytes are based on total usage in
1900 // current cycle. kernel doesn't like 0-byte rules, so we
1901 // set 1-byte quota and disable the radio later.
1902 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1903 }
1904 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001905 // metered network, but no policy limit; we still need to
1906 // restrict apps, so push really high quota.
1907 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001908 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001909
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001910 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001911 // TODO: switch to shared quota once NMS supports
1912 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001913 }
1914
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001915 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1916 final String iface = matchingIfaces.valueAt(j);
1917 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001918 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001919 }
1920 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001921
1922 // keep track of lowest warning or limit of active policies
1923 if (hasWarning && policy.warningBytes < lowestRule) {
1924 lowestRule = policy.warningBytes;
1925 }
1926 if (hasLimit && policy.limitBytes < lowestRule) {
1927 lowestRule = policy.limitBytes;
1928 }
1929 }
1930
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001931 // One final pass to catch any metered ifaces that don't have explicitly
1932 // defined policies; typically Wi-Fi networks.
1933 for (NetworkState state : states) {
1934 if (state.networkInfo != null && state.networkInfo.isConnected()
1935 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1936 matchingIfaces.clear();
1937 collectIfaces(matchingIfaces, state);
1938 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1939 final String iface = matchingIfaces.valueAt(j);
1940 if (!newMeteredIfaces.contains(iface)) {
1941 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1942 newMeteredIfaces.add(iface);
1943 }
1944 }
1945 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001946 }
1947
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001948 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001949 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1950 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001951 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001952 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001953 }
1954 }
1955 mMeteredIfaces = newMeteredIfaces;
1956
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001957 final ContentResolver cr = mContext.getContentResolver();
1958 final boolean quotaEnabled = Settings.Global.getInt(cr,
1959 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1960 final long quotaUnlimited = Settings.Global.getLong(cr,
1961 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1962 final float quotaLimited = Settings.Global.getFloat(cr,
1963 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1964
Jeff Sharkey9252b342018-01-19 07:58:35 +09001965 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001966 mSubscriptionOpportunisticQuota.clear();
1967 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001968 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001969 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001970 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001971 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001972 if (plan == null) continue;
1973
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001974 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001975 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001976 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1977 // Clamp to 0 when roaming
1978 quotaBytes = 0;
1979 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001980 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001981 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001982 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001983 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001984 } else {
1985 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001986 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1987 final long start = cycle.getLower().toInstant().toEpochMilli();
1988 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001989 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001990 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001991 .truncatedTo(ChronoUnit.DAYS)
1992 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001993 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001994 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1995 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001996 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001997 // Number of remaining days including current day
1998 final long remainingDays =
1999 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002000
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002001 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002002 }
2003
2004 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2005 }
2006
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002007 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002008 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002009
2010 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002011
2012 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002013 }
2014
2015 /**
2016 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2017 * have at least a default mobile policy defined.
2018 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002019 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002020 private void ensureActiveMobilePolicyAL() {
2021 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002022 if (mSuppressDefaultPolicy) return;
2023
Jeff Sharkey146bb332018-04-18 15:42:57 -06002024 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2025 final int subId = mSubIdToSubscriberId.keyAt(i);
2026 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002027
Hugo Benichi446c9c92017-04-10 09:41:10 +09002028 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002029 }
2030 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002031
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002032 /**
2033 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2034 * have at least a default mobile policy defined.
2035 *
2036 * @param subId to build a default policy for
2037 * @param subscriberId that we check for an existing policy
2038 * @return true if a mobile network policy was added, or false one already existed.
2039 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002040 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002041 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002042 // Poke around to see if we already have a policy
2043 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002044 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002045 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2046 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2047 if (template.matches(probeIdent)) {
2048 if (LOGD) {
2049 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2050 + NetworkIdentity.scrubSubscriberId(subscriberId));
2051 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002052 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002053 }
2054 }
2055
Jeff Sharkey32566012014-12-02 18:30:14 -08002056 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2057 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002058 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002059 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002060 return true;
2061 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002062
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002063 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002064 final int dataWarningConfig = mContext.getResources().getInteger(
2065 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002066 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002067 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002068 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002069 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002070 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002071 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002072
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002073 private long getPlatformDefaultLimitBytes() {
2074 return LIMIT_DISABLED;
2075 }
2076
2077 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002078 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002079 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002080 final RecurrenceRule cycleRule = NetworkPolicy
2081 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002082 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002083 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2084 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2085 synchronized (mUidRulesFirstLock) {
2086 synchronized (mNetworkPoliciesSecondLock) {
2087 updateDefaultMobilePolicyAL(subId, policy);
2088 }
2089 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002090 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002091 }
2092
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002093 /**
2094 * Update the given {@link NetworkPolicy} based on any carrier-provided
2095 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2096 * Leaves policy untouched if the user has modified it.
2097 *
2098 * @return if the policy was modified
2099 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002100 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002101 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2102 if (!policy.inferred) {
2103 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2104 return false;
2105 }
2106
2107 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2108 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2109 policy.lastLimitSnooze, policy.metered, policy.inferred);
2110
2111 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2112 if (!ArrayUtils.isEmpty(plans)) {
2113 final SubscriptionPlan plan = plans[0];
2114 policy.cycleRule = plan.getCycleRule();
2115 final long planLimitBytes = plan.getDataLimitBytes();
2116 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2117 policy.warningBytes = getPlatformDefaultWarningBytes();
2118 policy.limitBytes = getPlatformDefaultLimitBytes();
2119 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2120 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2121 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2122 } else {
2123 policy.warningBytes = (planLimitBytes * 9) / 10;
2124 switch (plan.getDataLimitBehavior()) {
2125 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2126 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2127 policy.limitBytes = planLimitBytes;
2128 break;
2129 default:
2130 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2131 break;
2132 }
2133 }
2134 } else {
2135 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2136 final int currentCycleDay;
2137 if (policy.cycleRule.isMonthly()) {
2138 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2139 } else {
2140 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2141 }
2142 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2143 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2144 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2145 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2146 }
2147
2148 if (policy.equals(original)) {
2149 return false;
2150 } else {
2151 Slog.d(TAG, "Updated " + original + " to " + policy);
2152 return true;
2153 }
2154 }
2155
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002156 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002157 private void readPolicyAL() {
2158 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159
2160 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002161 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002162 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002163 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002164 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002165
2166 FileInputStream fis = null;
2167 try {
2168 fis = mPolicyFile.openRead();
2169 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002170 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171
Felipe Leme46b451f2016-08-19 08:46:17 -07002172 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2173 // to skip UIDs that were explicitly blacklisted.
2174 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2175
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002176 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002177 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002178 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179 while ((type = in.next()) != END_DOCUMENT) {
2180 final String tag = in.getName();
2181 if (type == START_TAG) {
2182 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002183 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002185 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2186 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2188 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2189 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002190 final String networkId;
2191 if (version >= VERSION_ADDED_NETWORK_ID) {
2192 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2193 } else {
2194 networkId = null;
2195 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002196 final RecurrenceRule cycleRule;
2197 if (version >= VERSION_ADDED_CYCLE) {
2198 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2199 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2200 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2201 cycleRule = new RecurrenceRule(
2202 RecurrenceRule.convertZonedDateTime(start),
2203 RecurrenceRule.convertZonedDateTime(end),
2204 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002205 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002206 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2207 final String cycleTimezone;
2208 if (version >= VERSION_ADDED_TIMEZONE) {
2209 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2210 } else {
2211 cycleTimezone = "UTC";
2212 }
2213 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002214 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002215 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2216 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002217 final long lastLimitSnooze;
2218 if (version >= VERSION_SPLIT_SNOOZE) {
2219 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2220 } else if (version >= VERSION_ADDED_SNOOZE) {
2221 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002222 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002223 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002224 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002225 final boolean metered;
2226 if (version >= VERSION_ADDED_METERED) {
2227 metered = readBooleanAttribute(in, ATTR_METERED);
2228 } else {
2229 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002230 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002231 metered = true;
2232 break;
2233 default:
2234 metered = false;
2235 }
2236 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002237 final long lastWarningSnooze;
2238 if (version >= VERSION_SPLIT_SNOOZE) {
2239 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2240 } else {
2241 lastWarningSnooze = SNOOZE_NEVER;
2242 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002243 final boolean inferred;
2244 if (version >= VERSION_ADDED_INFERRED) {
2245 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2246 } else {
2247 inferred = false;
2248 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002249
Jeff Sharkey32566012014-12-02 18:30:14 -08002250 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2251 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002252 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002253 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2254 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002255 lastLimitSnooze, metered, inferred));
2256 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002257
2258 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2259 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2260 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2261 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2262 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2263 RecurrenceRule.convertZonedDateTime(start),
2264 RecurrenceRule.convertZonedDateTime(end),
2265 RecurrenceRule.convertPeriod(period));
2266 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2267 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2268
2269 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2270 SubscriptionPlan.BYTES_UNKNOWN);
2271 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2272 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2273 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2274 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2275 builder.setDataLimit(limitBytes, limitBehavior);
2276 }
2277
2278 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2279 SubscriptionPlan.BYTES_UNKNOWN);
2280 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2281 SubscriptionPlan.TIME_UNKNOWN);
2282 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2283 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2284 builder.setDataUsage(usageBytes, usageTime);
2285 }
2286
2287 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2288 final SubscriptionPlan plan = builder.build();
2289 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2290 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2291
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002292 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2293 mSubscriptionPlansOwner.put(subId, ownerPackage);
2294
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002295 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002296 final int uid = readIntAttribute(in, ATTR_UID);
2297 final int policy = readIntAttribute(in, ATTR_POLICY);
2298
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002299 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002300 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002301 } else {
2302 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2303 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002304 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002305 final int appId = readIntAttribute(in, ATTR_APP_ID);
2306 final int policy = readIntAttribute(in, ATTR_POLICY);
2307
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002308 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002309 // app policy is deprecated so this is only used in pre system user split.
2310 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002312 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002313 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002314 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002315 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002316 } else if (TAG_WHITELIST.equals(tag)) {
2317 insideWhitelist = true;
2318 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2319 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002320 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002321 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2322 final int uid = readIntAttribute(in, ATTR_UID);
2323 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002324 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002325 } else if (type == END_TAG) {
2326 if (TAG_WHITELIST.equals(tag)) {
2327 insideWhitelist = false;
2328 }
2329
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002330 }
2331 }
2332
Felipe Leme46b451f2016-08-19 08:46:17 -07002333 final int size = whitelistedRestrictBackground.size();
2334 for (int i = 0; i < size; i++) {
2335 final int uid = whitelistedRestrictBackground.keyAt(i);
2336 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2337 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2338 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2339 + " because its policy is " + uidPoliciesToString(policy));
2340 continue;
2341 }
2342 if (UserHandle.isApp(uid)) {
2343 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2344 if (LOGV)
2345 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2346 setUidPolicyUncheckedUL(uid, newPolicy, false);
2347 } else {
2348 Slog.w(TAG, "unable to update policy on UID " + uid);
2349 }
2350 }
2351
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002352 } catch (FileNotFoundException e) {
2353 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002354 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002355 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002356 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002357 } finally {
2358 IoUtils.closeQuietly(fis);
2359 }
2360 }
2361
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002362 /**
2363 * Upgrade legacy background data flags, notifying listeners of one last
2364 * change to always-true.
2365 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002366 private void upgradeDefaultBackgroundDataUL() {
2367 // This method is only called when we're unable to find the network policy flag, which
2368 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002369
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002370 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002371 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002372 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2373
2374 // NOTE: We used to read the legacy setting here :
2375 //
2376 // final int legacyFlagValue = Settings.Secure.getInt(
2377 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2378 //
2379 // This is no longer necessary because we will never upgrade directly from Gingerbread
2380 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2381 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002382 }
2383
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002384 /**
2385 * Perform upgrade step of moving any user-defined meterness overrides over
2386 * into {@link WifiConfiguration}.
2387 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002388 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002389 private void upgradeWifiMeteredOverrideAL() {
2390 boolean modified = false;
2391 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2392 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2393 for (int i = 0; i < mNetworkPolicy.size(); ) {
2394 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2395 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2396 && !policy.inferred) {
2397 mNetworkPolicy.removeAt(i);
2398 modified = true;
2399
2400 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2401 for (WifiConfiguration config : configs) {
2402 if (Objects.equals(resolveNetworkId(config), networkId)) {
2403 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2404 config.meteredOverride = policy.metered
2405 ? WifiConfiguration.METERED_OVERRIDE_METERED
2406 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2407 wm.updateNetwork(config);
2408 }
2409 }
2410 } else {
2411 i++;
2412 }
2413 }
2414 if (modified) {
2415 writePolicyAL();
2416 }
2417 }
2418
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002419 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002420 void writePolicyAL() {
2421 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002422
2423 FileOutputStream fos = null;
2424 try {
2425 fos = mPolicyFile.startWrite();
2426
2427 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002428 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002429 out.startDocument(null, true);
2430
2431 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002432 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002433 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002434
2435 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002436 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2437 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002438 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002439 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002440
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002441 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002442 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2443 final String subscriberId = template.getSubscriberId();
2444 if (subscriberId != null) {
2445 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002446 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002447 final String networkId = template.getNetworkId();
2448 if (networkId != null) {
2449 out.attribute(null, ATTR_NETWORK_ID, networkId);
2450 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002451 writeStringAttribute(out, ATTR_CYCLE_START,
2452 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2453 writeStringAttribute(out, ATTR_CYCLE_END,
2454 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2455 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2456 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002457 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2458 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002459 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2460 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002461 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002462 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002463 out.endTag(null, TAG_NETWORK_POLICY);
2464 }
2465
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002466 // write all known subscription plans
2467 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2468 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002469 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002470 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2471 if (ArrayUtils.isEmpty(plans)) continue;
2472
2473 for (SubscriptionPlan plan : plans) {
2474 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2475 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002476 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002477 final RecurrenceRule cycleRule = plan.getCycleRule();
2478 writeStringAttribute(out, ATTR_CYCLE_START,
2479 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2480 writeStringAttribute(out, ATTR_CYCLE_END,
2481 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2482 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2483 RecurrenceRule.convertPeriod(cycleRule.period));
2484 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2485 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2486 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2487 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2488 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2489 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2490 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2491 }
2492 }
2493
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002494 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002495 for (int i = 0; i < mUidPolicy.size(); i++) {
2496 final int uid = mUidPolicy.keyAt(i);
2497 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002498
Jeff Sharkey497e4432011-06-14 17:27:29 -07002499 // skip writing empty policies
2500 if (policy == POLICY_NONE) continue;
2501
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002502 out.startTag(null, TAG_UID_POLICY);
2503 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002504 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002505 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002506 }
2507
2508 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002509
2510 // write all whitelists
2511 out.startTag(null, TAG_WHITELIST);
2512
Felipe Lemea9505cc2016-02-26 10:28:41 -08002513 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002514 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002515 for (int i = 0; i < size; i++) {
2516 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2517 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2518 writeIntAttribute(out, ATTR_UID, uid);
2519 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2520 }
2521
Felipe Lemeb85a6372016-01-14 16:16:16 -08002522 out.endTag(null, TAG_WHITELIST);
2523
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002524 out.endDocument();
2525
2526 mPolicyFile.finishWrite(fos);
2527 } catch (IOException e) {
2528 if (fos != null) {
2529 mPolicyFile.failWrite(fos);
2530 }
2531 }
2532 }
2533
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002534 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002535 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002536 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002537
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002538 if (!UserHandle.isApp(uid)) {
2539 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002540 }
Felipe Lemef0823852016-06-08 13:43:08 -07002541 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002542 final long token = Binder.clearCallingIdentity();
2543 try {
2544 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2545 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002546 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002547 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002548 }
2549 } finally {
2550 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002551 }
2552 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002553 }
2554
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002555 @Override
2556 public void addUidPolicy(int uid, int policy) {
2557 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002558
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002559 if (!UserHandle.isApp(uid)) {
2560 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2561 }
2562
Felipe Lemef0823852016-06-08 13:43:08 -07002563 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002564 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2565 policy |= oldPolicy;
2566 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002567 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002568 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002569 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002570 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002571 }
2572
2573 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002574 public void removeUidPolicy(int uid, int policy) {
2575 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2576
2577 if (!UserHandle.isApp(uid)) {
2578 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2579 }
2580
Felipe Lemef0823852016-06-08 13:43:08 -07002581 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002582 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2583 policy = oldPolicy & ~policy;
2584 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002585 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002586 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002587 }
2588 }
2589 }
2590
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002591 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002592 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002593 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002594
Felipe Leme57e3d312016-08-23 14:42:52 -07002595 final boolean notifyApp;
2596 if (!isUidValidForWhitelistRules(uid)) {
2597 notifyApp = false;
2598 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002599 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2600 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2601 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2602 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002603 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2604 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002605 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2606 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2607 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2608 if (LOGD)
2609 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2610 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2611 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002612 notifyApp = wasBlocked != isBlocked;
2613 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002614 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2615 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002616 if (persist) {
2617 synchronized (mNetworkPoliciesSecondLock) {
2618 writePolicyAL();
2619 }
2620 }
Felipe Leme923845f2016-03-02 13:42:48 -08002621 }
2622
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002623 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002624 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002625 if (policy == POLICY_NONE) {
2626 mUidPolicy.delete(uid);
2627 } else {
2628 mUidPolicy.put(uid, policy);
2629 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002630
2631 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002632 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002633 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002634 synchronized (mNetworkPoliciesSecondLock) {
2635 writePolicyAL();
2636 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002637 }
2638 }
2639
2640 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002641 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002642 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2643
Felipe Lemef0823852016-06-08 13:43:08 -07002644 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002645 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002646 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002647 }
2648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002649 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002650 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002651 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2652
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002653 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002654 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002655 for (int i = 0; i < mUidPolicy.size(); i++) {
2656 final int uid = mUidPolicy.keyAt(i);
2657 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002658 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2659 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002660 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002661 }
2662 }
2663 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002664 return uids;
2665 }
2666
2667 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002668 * Removes any persistable state associated with given {@link UserHandle}, persisting
2669 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002670 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002671 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002672 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002673
Sudheer Shanka352dc572017-09-22 17:09:38 -07002674 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002675 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002676
Felipe Lemea110eec2016-04-29 09:58:06 -07002677 // Remove entries from revoked default restricted background UID whitelist
2678 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2679 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2680 if (UserHandle.getUserId(uid) == userId) {
2681 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002682 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002683 }
2684 }
2685
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002686 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002687 int[] uids = new int[0];
2688 for (int i = 0; i < mUidPolicy.size(); i++) {
2689 final int uid = mUidPolicy.keyAt(i);
2690 if (UserHandle.getUserId(uid) == userId) {
2691 uids = appendInt(uids, uid);
2692 }
2693 }
2694
2695 if (uids.length > 0) {
2696 for (int uid : uids) {
2697 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002698 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002699 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002700 }
Felipe Lemef0823852016-06-08 13:43:08 -07002701 synchronized (mNetworkPoliciesSecondLock) {
2702 updateRulesForGlobalChangeAL(true);
2703 if (writePolicy && changed) {
2704 writePolicyAL();
2705 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002706 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002707 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002708 }
2709
2710 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002711 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002712 // TODO: create permission for observing network policy
2713 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002714 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002715 }
2716
2717 @Override
2718 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002719 // TODO: create permission for observing network policy
2720 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002721 mListeners.unregister(listener);
2722 }
2723
Jeff Sharkey1b861272011-05-22 00:34:52 -07002724 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002725 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002726 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2727
Felipe Leme6a05eee2016-02-19 14:43:51 -08002728 final long token = Binder.clearCallingIdentity();
2729 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002730 synchronized (mUidRulesFirstLock) {
2731 synchronized (mNetworkPoliciesSecondLock) {
2732 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002733 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002734 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002735 }
2736 } finally {
2737 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002738 }
2739 }
2740
Hugo Benichi446c9c92017-04-10 09:41:10 +09002741 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002742 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002743 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2744 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002745 }
2746
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002747 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002748 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002749 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002750 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002751 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2752 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2753 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002754 } catch (SecurityException e) {
2755 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002756
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002757 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2758 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2759 return new NetworkPolicy[0];
2760 }
Svet Ganov16a16892015-04-16 10:32:04 -07002761 }
2762
Felipe Lemef0823852016-06-08 13:43:08 -07002763 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002764 final int size = mNetworkPolicy.size();
2765 final NetworkPolicy[] policies = new NetworkPolicy[size];
2766 for (int i = 0; i < size; i++) {
2767 policies[i] = mNetworkPolicy.valueAt(i);
2768 }
2769 return policies;
2770 }
2771 }
2772
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002773 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002774 private void normalizePoliciesNL() {
2775 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002776 }
2777
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002778 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002779 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002780 mNetworkPolicy.clear();
2781 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002782 if (policy == null) {
2783 continue;
2784 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002785 // When two normalized templates conflict, prefer the most
2786 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002787 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002788 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2789 if (existing == null || existing.compareTo(policy) > 0) {
2790 if (existing != null) {
2791 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2792 }
2793 mNetworkPolicy.put(policy.template, policy);
2794 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002795 }
2796 }
2797
2798 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002799 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002800 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002801
2802 final long token = Binder.clearCallingIdentity();
2803 try {
2804 performSnooze(template, TYPE_LIMIT);
2805 } finally {
2806 Binder.restoreCallingIdentity(token);
2807 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002808 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002809
Dianne Hackborn497175b2014-07-01 12:56:08 -07002810 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002811 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002812 synchronized (mUidRulesFirstLock) {
2813 synchronized (mNetworkPoliciesSecondLock) {
2814 // find and snooze local policy that matches
2815 final NetworkPolicy policy = mNetworkPolicy.get(template);
2816 if (policy == null) {
2817 throw new IllegalArgumentException("unable to find policy for " + template);
2818 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002819
Felipe Lemef0823852016-06-08 13:43:08 -07002820 switch (type) {
2821 case TYPE_WARNING:
2822 policy.lastWarningSnooze = currentTime;
2823 break;
2824 case TYPE_LIMIT:
2825 policy.lastLimitSnooze = currentTime;
2826 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002827 case TYPE_RAPID:
2828 policy.lastRapidSnooze = currentTime;
2829 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002830 default:
2831 throw new IllegalArgumentException("unexpected type");
2832 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002833
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002834 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002835 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002836 }
2837 }
2838
2839 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002840 public void onTetheringChanged(String iface, boolean tethering) {
2841 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002842 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002843 if (mRestrictBackground && tethering) {
2844 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2845 setRestrictBackground(false);
2846 }
2847 }
2848 }
2849
2850 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002851 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002852 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002853 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002854 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2855 final long token = Binder.clearCallingIdentity();
2856 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002857 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002858 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002859 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002860 } finally {
2861 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002862 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002863 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002864 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002865 }
2866 }
2867
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002868 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002869 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002870 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002871 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002872 if (restrictBackground == mRestrictBackground) {
2873 // Ideally, UI should never allow this scenario...
2874 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002875 return;
2876 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002877 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2878 final boolean oldRestrictBackground = mRestrictBackground;
2879 mRestrictBackground = restrictBackground;
2880 // Must whitelist foreground apps before turning data saver mode on.
2881 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2882 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2883 updateRulesForRestrictBackgroundUL();
2884 try {
2885 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2886 Slog.e(TAG,
2887 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2888 mRestrictBackground = oldRestrictBackground;
2889 // TODO: if it knew the foreground apps (see TODO above), it could call
2890 // updateRulesForRestrictBackgroundUL() again to restore state.
2891 return;
2892 }
2893 } catch (RemoteException e) {
2894 // ignored; service lives in system_server
2895 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002896
Sudheer Shanka543339f2017-07-28 15:18:07 -07002897 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002898 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002899
2900 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2901 mRestrictBackgroundChangedInBsm = true;
2902 }
2903 synchronized (mNetworkPoliciesSecondLock) {
2904 updateNotificationsNL();
2905 writePolicyAL();
2906 }
2907 } finally {
2908 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002909 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002910 }
2911
2912 private void sendRestrictBackgroundChangedMsg() {
2913 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2914 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2915 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002916 }
2917
Felipe Lemeb85a6372016-01-14 16:16:16 -08002918 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002919 public int getRestrictBackgroundByCaller() {
2920 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2921 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002922
Felipe Lemef0823852016-06-08 13:43:08 -07002923 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002924 // Must clear identity because getUidPolicy() is restricted to system.
2925 final long token = Binder.clearCallingIdentity();
2926 final int policy;
2927 try {
2928 policy = getUidPolicy(uid);
2929 } finally {
2930 Binder.restoreCallingIdentity(token);
2931 }
2932 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2933 // App is blacklisted.
2934 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2935 }
Felipe Leme1b103232016-01-22 09:44:57 -08002936 if (!mRestrictBackground) {
2937 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2938 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002939 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002940 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2941 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2942 }
2943 }
2944
2945 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002946 public boolean getRestrictBackground() {
2947 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2948
Felipe Lemef0823852016-06-08 13:43:08 -07002949 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002950 return mRestrictBackground;
2951 }
2952 }
2953
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002954 @Override
2955 public void setDeviceIdleMode(boolean enabled) {
2956 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002957 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2958 try {
2959 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002960 if (mDeviceIdleMode == enabled) {
2961 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002962 }
Felipe Lemeea014392016-09-06 13:59:54 -07002963 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002964 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002965 if (mSystemReady) {
2966 // Device idle change means we need to rebuild rules for all
2967 // known apps, so do a global refresh.
2968 updateRulesForRestrictPowerUL();
2969 }
2970 }
2971 if (enabled) {
2972 EventLogTags.writeDeviceIdleOnPhase("net");
2973 } else {
2974 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002975 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002976 } finally {
2977 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002978 }
2979 }
2980
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002981 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002982 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2983 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002984 final long token = Binder.clearCallingIdentity();
2985 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002986 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2987 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2988 for (WifiConfiguration config : configs) {
2989 if (Objects.equals(resolveNetworkId(config), networkId)) {
2990 config.meteredOverride = meteredOverride;
2991 wm.updateNetwork(config);
2992 }
2993 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002994 } finally {
2995 Binder.restoreCallingIdentity(token);
2996 }
2997 }
2998
Jeff Sharkey46645002011-07-27 21:11:21 -07002999 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003000 @Deprecated
3001 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3002 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3003 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3004 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003005 }
3006
Jeff Sharkey53313d72017-07-13 16:47:32 -06003007 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3008 // Verify they're not lying about package name
3009 mAppOps.checkPackage(callingUid, callingPackage);
3010
Jeff Sharkey53313d72017-07-13 16:47:32 -06003011 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003012 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003013 final long token = Binder.clearCallingIdentity();
3014 try {
3015 si = mContext.getSystemService(SubscriptionManager.class)
3016 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003017 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003018 } finally {
3019 Binder.restoreCallingIdentity(token);
3020 }
3021
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003022 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003023 if (si != null) {
3024 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3025 return;
3026 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003027 }
3028
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003029 // Second check: has the CarrierService delegated access?
3030 if (config != null) {
3031 final String overridePackage = config
3032 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3033 if (!TextUtils.isEmpty(overridePackage)
3034 && Objects.equals(overridePackage, callingPackage)) {
3035 return;
3036 }
3037 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003038
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003039 // Third check: is caller the fallback/default CarrierService?
3040 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3041 if (!TextUtils.isEmpty(defaultPackage)
3042 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003043 return;
3044 }
3045
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003046 // Fourth check: is caller a testing app?
3047 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3048 if (!TextUtils.isEmpty(testPackage)
3049 && Objects.equals(testPackage, callingPackage)) {
3050 return;
3051 }
3052
3053 // Fifth check: is caller a legacy testing app?
3054 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3055 if (!TextUtils.isEmpty(legacyTestPackage)
3056 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003057 return;
3058 }
3059
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003060 // Final check: does the caller hold a permission?
3061 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003062 }
3063
3064 @Override
3065 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3066 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3067
Jeff Sharkey53313d72017-07-13 16:47:32 -06003068 final String fake = SystemProperties.get("fw.fake_plan");
3069 if (!TextUtils.isEmpty(fake)) {
3070 final List<SubscriptionPlan> plans = new ArrayList<>();
3071 if ("month_hard".equals(fake)) {
3072 plans.add(SubscriptionPlan.Builder
3073 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3074 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003075 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3076 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3077 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3078 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3079 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003080 plans.add(SubscriptionPlan.Builder
3081 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3082 .setTitle("G-Mobile Happy")
3083 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3084 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3085 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3086 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3087 .build());
3088 plans.add(SubscriptionPlan.Builder
3089 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3090 .setTitle("G-Mobile, Charged after limit")
3091 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3092 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3093 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3094 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3095 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003096 } else if ("month_soft".equals(fake)) {
3097 plans.add(SubscriptionPlan.Builder
3098 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3099 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3100 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3101 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003102 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3103 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3104 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3105 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3106 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003107 plans.add(SubscriptionPlan.Builder
3108 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3109 .setTitle("G-Mobile, Throttled after limit")
3110 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3111 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3112 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3113 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3114 .build());
3115 plans.add(SubscriptionPlan.Builder
3116 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3117 .setTitle("G-Mobile, No data connection after limit")
3118 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3119 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3120 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3121 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3122 .build());
3123
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003124 } else if ("month_over".equals(fake)) {
3125 plans.add(SubscriptionPlan.Builder
3126 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3127 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3128 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3129 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3130 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3131 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3132 .build());
3133 plans.add(SubscriptionPlan.Builder
3134 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3135 .setTitle("G-Mobile, Throttled after limit")
3136 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3137 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3138 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3139 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3140 .build());
3141 plans.add(SubscriptionPlan.Builder
3142 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3143 .setTitle("G-Mobile, No data connection after limit")
3144 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3145 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3146 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3147 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3148 .build());
3149
Jeff Sharkey53313d72017-07-13 16:47:32 -06003150 } else if ("month_none".equals(fake)) {
3151 plans.add(SubscriptionPlan.Builder
3152 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3153 .setTitle("G-Mobile")
3154 .build());
3155 } else if ("prepaid".equals(fake)) {
3156 plans.add(SubscriptionPlan.Builder
3157 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3158 ZonedDateTime.now().plusDays(10))
3159 .setTitle("G-Mobile")
3160 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3161 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3162 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3163 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3164 .build());
3165 } else if ("prepaid_crazy".equals(fake)) {
3166 plans.add(SubscriptionPlan.Builder
3167 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3168 ZonedDateTime.now().plusDays(10))
3169 .setTitle("G-Mobile Anytime")
3170 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3171 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3172 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3173 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3174 .build());
3175 plans.add(SubscriptionPlan.Builder
3176 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3177 ZonedDateTime.now().plusDays(20))
3178 .setTitle("G-Mobile Nickel Nights")
3179 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003180 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3181 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003182 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3183 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3184 .build());
3185 plans.add(SubscriptionPlan.Builder
3186 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3187 ZonedDateTime.now().plusDays(20))
3188 .setTitle("G-Mobile Bonus 3G")
3189 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003190 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003191 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3192 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3193 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3194 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003195 } else if ("unlimited".equals(fake)) {
3196 plans.add(SubscriptionPlan.Builder
3197 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3198 ZonedDateTime.now().plusDays(10))
3199 .setTitle("G-Mobile Awesome")
3200 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3201 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3202 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3203 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3204 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003205 }
3206 return plans.toArray(new SubscriptionPlan[plans.size()]);
3207 }
3208
Jeff Sharkey4635f102017-09-01 11:27:13 -06003209 synchronized (mNetworkPoliciesSecondLock) {
3210 // Only give out plan details to the package that defined them,
3211 // so that we don't risk leaking plans between apps. We always
3212 // let in core system components (like the Settings app).
3213 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3214 if (Objects.equals(ownerPackage, callingPackage)
3215 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3216 return mSubscriptionPlans.get(subId);
3217 } else {
3218 Log.w(TAG, "Not returning plans because caller " + callingPackage
3219 + " doesn't match owner " + ownerPackage);
3220 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003221 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003222 }
3223 }
3224
3225 @Override
3226 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3227 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3228
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003229 for (SubscriptionPlan plan : plans) {
3230 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003231 }
3232
3233 final long token = Binder.clearCallingIdentity();
3234 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003235 synchronized (mUidRulesFirstLock) {
3236 synchronized (mNetworkPoliciesSecondLock) {
3237 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003238 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003239
Jeff Sharkey146bb332018-04-18 15:42:57 -06003240 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3241 if (subscriberId != null) {
3242 ensureActiveMobilePolicyAL(subId, subscriberId);
3243 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3244 } else {
3245 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3246 }
3247
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003248 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003249 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003250 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003251
3252 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3253 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3254 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3255 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003256 } finally {
3257 Binder.restoreCallingIdentity(token);
3258 }
3259 }
3260
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003261 /**
3262 * Only visible for testing purposes. This doesn't give any access to
3263 * existing plans; it simply lets the debug package define new plans.
3264 */
3265 void setSubscriptionPlansOwner(int subId, String packageName) {
3266 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3267 }
3268
Jeff Sharkey53313d72017-07-13 16:47:32 -06003269 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003270 public String getSubscriptionPlansOwner(int subId) {
3271 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3272 throw new SecurityException();
3273 }
3274
3275 synchronized (mNetworkPoliciesSecondLock) {
3276 return mSubscriptionPlansOwner.get(subId);
3277 }
3278 }
3279
3280 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003281 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3282 long timeoutMillis, String callingPackage) {
3283 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3284
3285 // We can only override when carrier told us about plans
3286 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003287 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3288 if (plan == null
3289 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003290 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003291 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003292 }
3293 }
3294
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003295 // Only allow overrides when feature is enabled. However, we always
3296 // allow disabling of overrides for safety reasons.
3297 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3298 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3299 if (overrideEnabled || overrideValue == 0) {
3300 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3301 overrideMask, overrideValue, subId));
3302 if (timeoutMillis > 0) {
3303 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3304 overrideMask, 0, subId), timeoutMillis);
3305 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003306 }
3307 }
3308
3309 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003310 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003311 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003312
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003313 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3314
Dianne Hackborn497175b2014-07-01 12:56:08 -07003315 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003316 for (String arg : args) {
3317 argSet.add(arg);
3318 }
3319
Felipe Lemef0823852016-06-08 13:43:08 -07003320 synchronized (mUidRulesFirstLock) {
3321 synchronized (mNetworkPoliciesSecondLock) {
3322 if (argSet.contains("--unsnooze")) {
3323 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3324 mNetworkPolicy.valueAt(i).clearSnooze();
3325 }
3326
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003327 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003328
3329 fout.println("Cleared snooze timestamps");
3330 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003331 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003332
Felipe Lemef0823852016-06-08 13:43:08 -07003333 fout.print("System ready: "); fout.println(mSystemReady);
3334 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3335 fout.print("Restrict power: "); fout.println(mRestrictPower);
3336 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003337 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3338
3339 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003340 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003341 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003342 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3343 fout.println(mNetworkPolicy.valueAt(i).toString());
3344 }
3345 fout.decreaseIndent();
3346
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003347 fout.println();
3348 fout.println("Subscription plans:");
3349 fout.increaseIndent();
3350 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3351 final int subId = mSubscriptionPlans.keyAt(i);
3352 fout.println("Subscriber ID " + subId + ":");
3353 fout.increaseIndent();
3354 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3355 if (!ArrayUtils.isEmpty(plans)) {
3356 for (SubscriptionPlan plan : plans) {
3357 fout.println(plan);
3358 }
3359 }
3360 fout.decreaseIndent();
3361 }
3362 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003363
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003364 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003365 fout.println("Active subscriptions:");
3366 fout.increaseIndent();
3367 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3368 final int subId = mSubIdToSubscriberId.keyAt(i);
3369 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3370
3371 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3372 }
3373 fout.decreaseIndent();
3374
3375 fout.println();
3376 fout.println("Merged subscriptions: "
3377 + Arrays.toString(NetworkIdentity.scrubSubscriberId(mMergedSubscriberIds)));
3378
3379 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003380 fout.println("Policy for UIDs:");
3381 fout.increaseIndent();
3382 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003383 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003384 final int uid = mUidPolicy.keyAt(i);
3385 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003386 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003387 fout.print(uid);
3388 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003389 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003390 fout.println();
3391 }
3392 fout.decreaseIndent();
3393
3394 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3395 if (size > 0) {
3396 fout.println("Power save whitelist (except idle) app ids:");
3397 fout.increaseIndent();
3398 for (int i = 0; i < size; i++) {
3399 fout.print("UID=");
3400 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3401 fout.print(": ");
3402 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3403 fout.println();
3404 }
3405 fout.decreaseIndent();
3406 }
3407
3408 size = mPowerSaveWhitelistAppIds.size();
3409 if (size > 0) {
3410 fout.println("Power save whitelist app ids:");
3411 fout.increaseIndent();
3412 for (int i = 0; i < size; i++) {
3413 fout.print("UID=");
3414 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3415 fout.print(": ");
3416 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3417 fout.println();
3418 }
3419 fout.decreaseIndent();
3420 }
3421
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003422 size = mAppIdleTempWhitelistAppIds.size();
3423 if (size > 0) {
3424 fout.println("App idle whitelist app ids:");
3425 fout.increaseIndent();
3426 for (int i = 0; i < size; i++) {
3427 fout.print("UID=");
3428 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3429 fout.print(": ");
3430 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3431 fout.println();
3432 }
3433 fout.decreaseIndent();
3434 }
3435
Felipe Lemef0823852016-06-08 13:43:08 -07003436 size = mDefaultRestrictBackgroundWhitelistUids.size();
3437 if (size > 0) {
3438 fout.println("Default restrict background whitelist uids:");
3439 fout.increaseIndent();
3440 for (int i = 0; i < size; i++) {
3441 fout.print("UID=");
3442 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3443 fout.println();
3444 }
3445 fout.decreaseIndent();
3446 }
3447
3448 size = mRestrictBackgroundWhitelistRevokedUids.size();
3449 if (size > 0) {
3450 fout.println("Default restrict background whitelist uids revoked by users:");
3451 fout.increaseIndent();
3452 for (int i = 0; i < size; i++) {
3453 fout.print("UID=");
3454 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3455 fout.println();
3456 }
3457 fout.decreaseIndent();
3458 }
3459
3460 final SparseBooleanArray knownUids = new SparseBooleanArray();
3461 collectKeys(mUidState, knownUids);
3462 collectKeys(mUidRules, knownUids);
3463
3464 fout.println("Status for all known UIDs:");
3465 fout.increaseIndent();
3466 size = knownUids.size();
3467 for (int i = 0; i < size; i++) {
3468 final int uid = knownUids.keyAt(i);
3469 fout.print("UID=");
3470 fout.print(uid);
3471
3472 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3473 fout.print(" state=");
3474 fout.print(state);
3475 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3476 fout.print(" (fg)");
3477 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003478 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003479 ? " (fg svc)" : " (bg)");
3480 }
3481
3482 final int uidRules = mUidRules.get(uid, RULE_NONE);
3483 fout.print(" rules=");
3484 fout.print(uidRulesToString(uidRules));
3485 fout.println();
3486 }
3487 fout.decreaseIndent();
3488
3489 fout.println("Status for just UIDs with rules:");
3490 fout.increaseIndent();
3491 size = mUidRules.size();
3492 for (int i = 0; i < size; i++) {
3493 final int uid = mUidRules.keyAt(i);
3494 fout.print("UID=");
3495 fout.print(uid);
3496 final int uidRules = mUidRules.get(uid, RULE_NONE);
3497 fout.print(" rules=");
3498 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003499 fout.println();
3500 }
3501 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003502
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003503 fout.println("Admin restricted uids for metered data:");
3504 fout.increaseIndent();
3505 size = mMeteredRestrictedUids.size();
3506 for (int i = 0; i < size; ++i) {
3507 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3508 fout.println(mMeteredRestrictedUids.valueAt(i));
3509 }
3510 fout.decreaseIndent();
3511
Makoto Onuki49392d32018-04-11 13:51:02 -07003512 fout.println();
3513 mStatLogger.dump(fout);
3514
Sudheer Shanka352dc572017-09-22 17:09:38 -07003515 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003516 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003517 }
3518 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003519
3520 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003521 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003522 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003523 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003524 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003525 }
3526
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003527 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003528 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003529 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003530 return isUidStateForeground(
3531 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003532 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003533 }
3534
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003535 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003536 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003537 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003538 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003539 }
3540
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003541 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003542 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003543 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3544 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3545 }
3546
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003547 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003548 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003549 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003550 }
3551
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003552 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003553 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003554 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003555 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003556 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003557 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003558 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003559 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3560 try {
3561 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3562 if (oldUidState != uidState) {
3563 // state changed, push updated rules
3564 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003565 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3566 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3567 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003568 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003569 if (mDeviceIdleMode) {
3570 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003571 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003572 if (mRestrictPower) {
3573 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003574 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003575 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003576 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003577 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003578 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003579 } finally {
3580 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003581 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003582 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003583 }
3584
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003585 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003586 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003587 final int index = mUidState.indexOfKey(uid);
3588 if (index >= 0) {
3589 final int oldUidState = mUidState.valueAt(index);
3590 mUidState.removeAt(index);
3591 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003592 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003593 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003594 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003595 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003596 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003597 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003598 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003599 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003600 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003601 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003602 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003603 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003604 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003605 }
3606
Felipe Lemef28983d2016-03-25 12:18:23 -07003607 // adjust stats accounting based on foreground status
3608 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003609 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3610 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3611 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3612 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003613 try {
3614 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003615 } finally {
3616 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003617 }
3618 }
3619
Sudheer Shankac9d94072017-02-22 22:13:55 +00003620 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3621 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003622 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003623 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003624 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003625 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003626 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003627 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003628 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003629 }
3630
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003631 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003632 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003633 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3634 try {
3635 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3636 mUidFirewallPowerSaveRules);
3637 } finally {
3638 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3639 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003640 }
3641
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003642 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003643 void updateRuleForRestrictPowerUL(int uid) {
3644 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
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 updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003649 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3650 try {
3651 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3652 mUidFirewallDozableRules);
3653 } finally {
3654 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3655 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003656 }
3657
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003658 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003659 void updateRuleForDeviceIdleUL(int uid) {
3660 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003661 }
3662
Felipe Lemef28983d2016-03-25 12:18:23 -07003663 // NOTE: since both fw_dozable and fw_powersave uses the same map
3664 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003665 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003666 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003667 SparseIntArray rules) {
3668 if (enabled) {
3669 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003670 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003671 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003672 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003673 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003674 for (int ui = users.size() - 1; ui >= 0; ui--) {
3675 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003676 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3677 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3678 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3679 updateRulesForWhitelistedAppIds(uidRules,
3680 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003681 }
3682 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003683 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003684 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003685 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3686 }
3687 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003688 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003689 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003690 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003691 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003692 }
3693
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003694 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3695 final SparseBooleanArray whitelistedAppIds, int userId) {
3696 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3697 if (whitelistedAppIds.valueAt(i)) {
3698 final int appId = whitelistedAppIds.keyAt(i);
3699 final int uid = UserHandle.getUid(userId, appId);
3700 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3701 }
3702 }
3703 }
3704
3705 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003706 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3707 * mode, and app idle).
3708 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003709 * @param deviceIdleMode if true then we don't consider
3710 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3711 * whitelisted.
3712 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003713 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003714 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003715 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003716 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3717 || mPowerSaveWhitelistAppIds.get(appId);
3718 if (!deviceIdleMode) {
3719 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3720 }
3721 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003722 }
3723
Felipe Lemef28983d2016-03-25 12:18:23 -07003724 // NOTE: since both fw_dozable and fw_powersave uses the same map
3725 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003726 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003727 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003728 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003729 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003730 chain == FIREWALL_CHAIN_DOZABLE);
3731 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003732 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003733 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003734 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003735 }
3736 }
3737 }
3738
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003739 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003740 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003741 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3742 try {
3743 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3744 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003745
Felipe Leme873a83a2016-09-07 11:34:10 -07003746 // Fully update the app idle firewall chain.
3747 final List<UserInfo> users = mUserManager.getUsers();
3748 for (int ui = users.size() - 1; ui >= 0; ui--) {
3749 UserInfo user = users.get(ui);
3750 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3751 for (int uid : idleUids) {
3752 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3753 // quick check: if this uid doesn't have INTERNET permission, it
3754 // doesn't have network access anyway, so it is a waste to mess
3755 // with it here.
3756 if (hasInternetPermissions(uid)) {
3757 uidRules.put(uid, FIREWALL_RULE_DENY);
3758 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003759 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003760 }
3761 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003762
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003763 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003764 } finally {
3765 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3766 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003767 }
3768
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003769 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003770 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003771 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003772
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003773 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3774 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3775 }
3776 try {
3777 int appId = UserHandle.getAppId(uid);
3778 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3779 && !isUidForegroundOnRestrictPowerUL(uid)) {
3780 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003781 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003782 } else {
3783 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003784 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003785 }
3786 } finally {
3787 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003788 }
3789 }
3790
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003791 /**
3792 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3793 * changed.
3794 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003795 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003796 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003797 boolean paroled = mUsageStats.isAppIdleParoleOn();
3798 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003799 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003800
3801 int ruleCount = mUidFirewallStandbyRules.size();
3802 for (int i = 0; i < ruleCount; i++) {
3803 int uid = mUidFirewallStandbyRules.keyAt(i);
3804 int oldRules = mUidRules.get(uid);
3805 if (enableChain) {
3806 // Chain wasn't enabled before and the other power-related
3807 // chains are whitelists, so we can clear the
3808 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3809 // the effective rules result in blocking network access.
3810 oldRules &= MASK_METERED_NETWORKS;
3811 } else {
3812 // Skip if it had no restrictions to begin with
3813 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3814 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003815 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3816 if (newUidRules == RULE_NONE) {
3817 mUidRules.delete(uid);
3818 } else {
3819 mUidRules.put(uid, newUidRules);
3820 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003821 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003822 }
3823
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003824 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003825 * Update rules that might be changed by {@link #mRestrictBackground},
3826 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003827 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003828 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003829 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003830 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3831 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3832 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3833 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003834 try {
Felipe Leme09700462016-09-08 09:33:48 -07003835 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003836 updateRulesForRestrictPowerUL();
3837 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003838
Felipe Leme873a83a2016-09-07 11:34:10 -07003839 // If the set of restricted networks may have changed, re-evaluate those.
3840 if (restrictedNetworksChanged) {
3841 normalizePoliciesNL();
3842 updateNetworkRulesNL();
3843 }
3844 } finally {
3845 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003846 }
3847 }
3848
Felipe Leme09700462016-09-08 09:33:48 -07003849 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003850 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003851 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003852 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3853 try {
3854 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003855 updateRulesForPowerSaveUL();
3856 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3857 } finally {
3858 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3859 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003860 }
3861
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003862 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003863 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003864 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3865 try {
3866 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3867 } finally {
3868 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3869 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003870 }
3871
3872 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3873 private static final int TYPE_RESTRICT_POWER = 2;
3874 @Retention(RetentionPolicy.SOURCE)
3875 @IntDef(flag = false, value = {
3876 TYPE_RESTRICT_BACKGROUND,
3877 TYPE_RESTRICT_POWER,
3878 })
3879 public @interface RestrictType {
3880 }
3881
3882 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003883 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003884 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003885 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3886 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3887 }
3888 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003889 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003890
3891 final PackageManager pm = mContext.getPackageManager();
3892 final List<UserInfo> users;
3893 final List<ApplicationInfo> apps;
3894
3895 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3896 try {
3897 users = mUserManager.getUsers();
3898 } finally {
3899 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3900 }
3901 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3902 try {
3903 apps = pm.getInstalledApplications(
3904 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3905 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3906 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3907 } finally {
3908 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3909 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003910
Felipe Leme873a83a2016-09-07 11:34:10 -07003911 final int usersSize = users.size();
3912 final int appsSize = apps.size();
3913 for (int i = 0; i < usersSize; i++) {
3914 final UserInfo user = users.get(i);
3915 for (int j = 0; j < appsSize; j++) {
3916 final ApplicationInfo app = apps.get(j);
3917 final int uid = UserHandle.getUid(user.id, app.uid);
3918 switch (type) {
3919 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003920 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003921 break;
3922 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003923 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003924 break;
3925 default:
3926 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3927 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003928 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003929 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003930 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003931 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003932 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003933 }
3934
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003935 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003936 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003937 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003938 final int numUsers = users.size();
3939 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003940 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003941 int uid = UserHandle.getUid(user.id, appId);
3942 // Update external firewall rules.
3943 updateRuleForAppIdleUL(uid);
3944 updateRuleForDeviceIdleUL(uid);
3945 updateRuleForRestrictPowerUL(uid);
3946 // Update internal rules.
3947 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003948 }
3949 }
3950
Felipe Leme70c57c22016-03-29 10:45:13 -07003951 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3952 // methods below could be merged into a isUidValidForRules() method.
3953 private boolean isUidValidForBlacklistRules(int uid) {
3954 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003955 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003956 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003957 return true;
3958 }
3959
3960 return false;
3961 }
3962
Felipe Leme70c57c22016-03-29 10:45:13 -07003963 private boolean isUidValidForWhitelistRules(int uid) {
3964 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3965 }
3966
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003967 /**
3968 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3969 * power saving restrictions may still apply.
3970 */
3971 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003972 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003973 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3974
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003975 synchronized (mUidRulesFirstLock) {
3976 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3977 // No change.
3978 return;
3979 }
3980
3981 final long token = Binder.clearCallingIdentity();
3982 try {
3983 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3984 if (shouldWhitelist) {
3985 mAppIdleTempWhitelistAppIds.put(uid, true);
3986 } else {
3987 mAppIdleTempWhitelistAppIds.delete(uid);
3988 }
3989 updateRuleForAppIdleUL(uid);
3990 updateRulesForPowerRestrictionsUL(uid);
3991 } finally {
3992 Binder.restoreCallingIdentity(token);
3993 }
3994 }
3995 }
3996
3997 /** Return the list of UIDs currently in the app idle whitelist. */
3998 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003999 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004000 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4001
4002 synchronized (mUidRulesFirstLock) {
4003 final int len = mAppIdleTempWhitelistAppIds.size();
4004 int[] uids = new int[len];
4005 for (int i = 0; i < len; ++i) {
4006 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4007 }
4008 return uids;
4009 }
4010 }
4011
4012 /** Returns if the UID is currently considered idle. */
4013 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004014 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004015 synchronized (mUidRulesFirstLock) {
4016 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4017 // UID is temporarily whitelisted.
4018 return false;
4019 }
4020 }
4021
Amith Yamasani15e472352015-04-24 19:06:07 -07004022 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4023 final int userId = UserHandle.getUserId(uid);
4024
songjinshi0655edd2016-05-18 19:55:32 +08004025 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004026 for (String packageName : packages) {
4027 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4028 return false;
4029 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004030 }
4031 }
4032 return true;
4033 }
4034
4035 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004036 * Checks if an uid has INTERNET permissions.
4037 * <p>
4038 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004039 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004040 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004041 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004042 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004043 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004044 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004045 }
4046 } catch (RemoteException e) {
4047 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004048 return true;
4049 }
4050
4051 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004052 * Clears all state - internal and external - associated with an UID.
4053 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004054 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004055 private void onUidDeletedUL(int uid) {
4056 // First cleanup in-memory state synchronously...
4057 mUidRules.delete(uid);
4058 mUidPolicy.delete(uid);
4059 mUidFirewallStandbyRules.delete(uid);
4060 mUidFirewallDozableRules.delete(uid);
4061 mUidFirewallPowerSaveRules.delete(uid);
4062 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4063 mPowerSaveWhitelistAppIds.delete(uid);
4064 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004065 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004066
4067 // ...then update iptables asynchronously.
4068 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4069 }
4070
4071 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004072 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004073 *
Felipe Leme781ba142016-05-09 16:24:48 -07004074 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004075 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004076 * <li>Doze mode
4077 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004078 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004079 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004080 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004081 *
4082 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004083 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004084 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004085 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004086 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004087 updateRuleForDeviceIdleUL(uid);
4088 updateRuleForAppIdleUL(uid);
4089 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004090
4091 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004092 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004093
4094 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004095 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004096 }
4097
Felipe Leme70c57c22016-03-29 10:45:13 -07004098 /**
4099 * Applies network rules to bandwidth controllers based on process state and user-defined
4100 * restrictions (blacklist / whitelist).
4101 *
4102 * <p>
4103 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4104 * networks:
4105 * <ul>
4106 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4107 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4108 * also blacklisted.
4109 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004110 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004111 * <ul>
4112 *
4113 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4114 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4115 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4116 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004117 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004118 * {@link INetworkManagementService}, but this method should also be called in events (like
4119 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4120 * following rules should also be applied:
4121 *
4122 * <ul>
4123 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4124 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4125 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4126 * {@code bw_penalty_box}.
4127 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4128 * </ul>
4129 *
4130 * <p>For optimization, the rules are only applied on user apps that have internet access
4131 * permission, since there is no need to change the {@code iptables} rule if the app does not
4132 * have permission to use the internet.
4133 *
4134 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004135 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004136 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004137 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004138 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4139 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4140 "updateRulesForDataUsageRestrictionsUL: " + uid);
4141 }
4142 try {
4143 updateRulesForDataUsageRestrictionsULInner(uid);
4144 } finally {
4145 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4146 }
4147 }
4148
4149 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004150 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004151 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004152 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004153 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004154
Dianne Hackborn497175b2014-07-01 12:56:08 -07004155 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004156 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004157 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004158 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004159
Felipe Leme781ba142016-05-09 16:24:48 -07004160 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004161 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004162 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4163 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004164
Felipe Leme70c57c22016-03-29 10:45:13 -07004165 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004166 if (isRestrictedByAdmin) {
4167 newRule = RULE_REJECT_METERED;
4168 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004169 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4170 newRule = RULE_TEMPORARY_ALLOW_METERED;
4171 } else if (isWhitelisted) {
4172 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004173 }
4174 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004175 if (isBlacklisted) {
4176 newRule = RULE_REJECT_METERED;
4177 } else if (mRestrictBackground && isWhitelisted) {
4178 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004179 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004180 }
Felipe Leme781ba142016-05-09 16:24:48 -07004181 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004182
Felipe Lemef28983d2016-03-25 12:18:23 -07004183 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004184 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004185 + ": isForeground=" +isForeground
4186 + ", isBlacklisted=" + isBlacklisted
4187 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004188 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004189 + ", oldRule=" + uidRulesToString(oldRule)
4190 + ", newRule=" + uidRulesToString(newRule)
4191 + ", newUidRules=" + uidRulesToString(newUidRules)
4192 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004193 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004194
Felipe Leme46c4fc32016-05-04 09:21:43 -07004195 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004196 mUidRules.delete(uid);
4197 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004198 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004199 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004200
Felipe Leme70c57c22016-03-29 10:45:13 -07004201 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004202 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004203 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004204 // Temporarily whitelist foreground app, removing from blacklist if necessary
4205 // (since bw_penalty_box prevails over bw_happy_box).
4206
4207 setMeteredNetworkWhitelist(uid, true);
4208 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4209 // but ideally it should be just:
4210 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004211 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004212 setMeteredNetworkBlacklist(uid, false);
4213 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004214 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004215 // Remove temporary whitelist from app that is not on foreground anymore.
4216
4217 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4218 // but ideally they should be just:
4219 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4220 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004221 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004222 setMeteredNetworkWhitelist(uid, false);
4223 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004224 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004225 setMeteredNetworkBlacklist(uid, true);
4226 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004227 } else if (hasRule(newRule, RULE_REJECT_METERED)
4228 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004229 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004230 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004231 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004232 // Since blacklist prevails over whitelist, we need to handle the special case
4233 // where app is whitelisted and blacklisted at the same time (although such
4234 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004235 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004236 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004237 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4238 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004239 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004240 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004241 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004242 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004243 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4244 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004245 + ", whitelisted=" + isWhitelisted
4246 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004247 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004248 + ", newRule=" + uidRulesToString(newUidRules)
4249 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004250 }
Felipe Leme781ba142016-05-09 16:24:48 -07004251
Sudheer Shankac9d94072017-02-22 22:13:55 +00004252 // Dispatch changed rule to existing listeners.
4253 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004254 }
4255 }
4256
4257 /**
4258 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4259 * listeners in case of change.
4260 * <p>
4261 * There are 3 power-related rules that affects whether an app has background access on
4262 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4263 * restriction, it's added to the equivalent firewall chain:
4264 * <ul>
4265 * <li>App is idle: {@code fw_standby} firewall chain.
4266 * <li>Device is idle: {@code fw_dozable} firewall chain.
4267 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4268 * </ul>
4269 * <p>
4270 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4271 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4272 * <p>
4273 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4274 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004275 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004276 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004277 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4278
Sudheer Shankac9d94072017-02-22 22:13:55 +00004279 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004280
Sudheer Shankac9d94072017-02-22 22:13:55 +00004281 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004282 mUidRules.delete(uid);
4283 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004284 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004285 }
4286 }
4287
4288 /**
4289 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4290 *
4291 * @param uid the uid of the app to update rules for
4292 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4293 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4294 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004295 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004296 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004297 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004298 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4299 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4300 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4301 + (paroled ? "P" : "-"));
4302 }
4303 try {
4304 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4305 } finally {
4306 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4307 }
4308 }
4309
4310 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004311 if (!isUidValidForBlacklistRules(uid)) {
4312 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004313 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004314 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004315
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004316 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004317 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004318 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004319
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004320 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004321 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4322 int newRule = RULE_NONE;
4323
4324 // First step: define the new rule based on user restrictions and foreground state.
4325
4326 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4327 // by considering the foreground and non-foreground states.
4328 if (isForeground) {
4329 if (restrictMode) {
4330 newRule = RULE_ALLOW_ALL;
4331 }
4332 } else if (restrictMode) {
4333 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4334 }
4335
4336 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4337
4338 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004339 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004340 + ", isIdle: " + isIdle
4341 + ", mRestrictPower: " + mRestrictPower
4342 + ", mDeviceIdleMode: " + mDeviceIdleMode
4343 + ", isForeground=" + isForeground
4344 + ", isWhitelisted=" + isWhitelisted
4345 + ", oldRule=" + uidRulesToString(oldRule)
4346 + ", newRule=" + uidRulesToString(newRule)
4347 + ", newUidRules=" + uidRulesToString(newUidRules)
4348 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4349 }
4350
Felipe Leme781ba142016-05-09 16:24:48 -07004351 // Second step: notify listeners if state changed.
4352 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004353 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004354 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004355 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004356 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4357 } else {
4358 // All scenarios should have been covered above
4359 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4360 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004361 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004362 + ", newRule=" + uidRulesToString(newUidRules)
4363 + ", oldRule=" + uidRulesToString(oldUidRules));
4364 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004365 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004366 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004367
Sudheer Shankac9d94072017-02-22 22:13:55 +00004368 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004369 }
4370
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004371 private class AppIdleStateChangeListener
4372 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4373
4374 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004375 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4376 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004377 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004378 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4379 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004380 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004381 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004382 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004383 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004384 }
4385 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004386 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004387 }
4388
4389 @Override
4390 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004391 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004392 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004393 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004394 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004395 }
4396 }
4397
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004398 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4399 if (listener != null) {
4400 try {
4401 listener.onUidRulesChanged(uid, uidRules);
4402 } catch (RemoteException ignored) {
4403 }
4404 }
4405 }
4406
4407 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4408 String[] meteredIfaces) {
4409 if (listener != null) {
4410 try {
4411 listener.onMeteredIfacesChanged(meteredIfaces);
4412 } catch (RemoteException ignored) {
4413 }
4414 }
4415 }
4416
4417 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4418 boolean restrictBackground) {
4419 if (listener != null) {
4420 try {
4421 listener.onRestrictBackgroundChanged(restrictBackground);
4422 } catch (RemoteException ignored) {
4423 }
4424 }
4425 }
4426
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004427 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4428 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004429 if (listener != null) {
4430 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004431 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004432 } catch (RemoteException ignored) {
4433 }
4434 }
4435 }
4436
Jeff Sharkey9252b342018-01-19 07:58:35 +09004437 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4438 int overrideMask, int overrideValue) {
4439 if (listener != null) {
4440 try {
4441 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4442 } catch (RemoteException ignored) {
4443 }
4444 }
4445 }
4446
Makoto Onuki8e777332017-03-28 11:25:47 -07004447 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004448 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004449 public boolean handleMessage(Message msg) {
4450 switch (msg.what) {
4451 case MSG_RULES_CHANGED: {
4452 final int uid = msg.arg1;
4453 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004454 final int length = mListeners.beginBroadcast();
4455 for (int i = 0; i < length; i++) {
4456 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4457 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004458 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004459 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004460 return true;
4461 }
4462 case MSG_METERED_IFACES_CHANGED: {
4463 final String[] meteredIfaces = (String[]) msg.obj;
4464 final int length = mListeners.beginBroadcast();
4465 for (int i = 0; i < length; i++) {
4466 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004467 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004468 }
4469 mListeners.finishBroadcast();
4470 return true;
4471 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004472 case MSG_LIMIT_REACHED: {
4473 final String iface = (String) msg.obj;
4474
Felipe Lemef0823852016-06-08 13:43:08 -07004475 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004476 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004477 // force stats update to make sure we have
4478 // numbers that caused alert to trigger.
4479 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004480
Felipe Lemef0823852016-06-08 13:43:08 -07004481 updateNetworkEnabledNL();
4482 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004483 }
4484 }
4485 return true;
4486 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004487 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4488 final boolean restrictBackground = msg.arg1 != 0;
4489 final int length = mListeners.beginBroadcast();
4490 for (int i = 0; i < length; i++) {
4491 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004492 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004493 }
4494 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004495 final Intent intent =
4496 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4497 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4498 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4499 return true;
4500 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004501 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004502 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004503 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004504 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004505 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004506 final int length = mListeners.beginBroadcast();
4507 for (int i = 0; i < length; i++) {
4508 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004509 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004510 }
4511 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004512 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4513 if (notifyApp.booleanValue()) {
4514 broadcastRestrictBackgroundChanged(uid, notifyApp);
4515 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004516 return true;
4517 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004518 case MSG_ADVISE_PERSIST_THRESHOLD: {
4519 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004520 // make sure stats are recorded frequently enough; we aim
4521 // for 2MB threshold for 2GB/month rules.
4522 final long persistThreshold = lowestRule / 1000;
4523 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004524 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004525 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004526 case MSG_UPDATE_INTERFACE_QUOTA: {
4527 removeInterfaceQuota((String) msg.obj);
4528 // int params need to be stitched back into a long
4529 setInterfaceQuota((String) msg.obj,
4530 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4531 return true;
4532 }
4533 case MSG_REMOVE_INTERFACE_QUOTA: {
4534 removeInterfaceQuota((String) msg.obj);
4535 return true;
4536 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004537 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4538 resetUidFirewallRules(msg.arg1);
4539 return true;
4540 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004541 case MSG_SUBSCRIPTION_OVERRIDE: {
4542 final int overrideMask = msg.arg1;
4543 final int overrideValue = msg.arg2;
4544 final int subId = (int) msg.obj;
4545 final int length = mListeners.beginBroadcast();
4546 for (int i = 0; i < length; i++) {
4547 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4548 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4549 }
4550 mListeners.finishBroadcast();
4551 return true;
4552 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004553 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4554 final int userId = msg.arg1;
4555 final Set<String> packageNames = (Set<String>) msg.obj;
4556 setMeteredRestrictedPackagesInternal(packageNames, userId);
4557 return true;
4558 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004559 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4560 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4561 final boolean enabled = msg.arg1 != 0;
4562 setNetworkTemplateEnabledInner(template, enabled);
4563 return true;
4564 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004565 default: {
4566 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004567 }
4568 }
4569 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004570 };
4571
4572 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4573 @Override
4574 public boolean handleMessage(Message msg) {
4575 switch (msg.what) {
4576 case UID_MSG_STATE_CHANGED: {
4577 final int uid = msg.arg1;
4578 final int procState = msg.arg2;
4579 final long procStateSeq = (Long) msg.obj;
4580
4581 handleUidChanged(uid, procState, procStateSeq);
4582 return true;
4583 }
4584 case UID_MSG_GONE: {
4585 final int uid = msg.arg1;
4586 handleUidGone(uid);
4587 return true;
4588 }
4589 default: {
4590 return false;
4591 }
4592 }
4593 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004594 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004595
Makoto Onuki8e777332017-03-28 11:25:47 -07004596 void handleUidChanged(int uid, int procState, long procStateSeq) {
4597 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4598 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004599 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004600 synchronized (mUidRulesFirstLock) {
4601 // We received a uid state change callback, add it to the history so that it
4602 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004603 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004604 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004605 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004606 // Updating the network rules is done, so notify AMS about this.
4607 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4608 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004609 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4610 // called from the handler, so there's no multi-threading issue.
4611 if (updated) {
4612 updateNetworkStats(uid, isUidStateForeground(procState));
4613 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004614 } finally {
4615 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4616 }
4617 }
4618
4619 void handleUidGone(int uid) {
4620 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4621 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004622 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004623 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004624 updated = removeUidStateUL(uid);
4625 }
4626 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4627 // called from the handler, so there's no multi-threading issue.
4628 if (updated) {
4629 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004630 }
4631 } finally {
4632 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4633 }
4634 }
4635
Felipe Leme57e3d312016-08-23 14:42:52 -07004636 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4637 final PackageManager pm = mContext.getPackageManager();
4638 final String[] packages = pm.getPackagesForUid(uid);
4639 if (packages != null) {
4640 final int userId = UserHandle.getUserId(uid);
4641 for (String packageName : packages) {
4642 final Intent intent =
4643 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4644 intent.setPackage(packageName);
4645 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4646 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4647 }
4648 }
4649 }
4650
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004651 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4652 // long quotaBytes split up into two ints to fit in message
4653 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4654 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4655 }
4656
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004657 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004658 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004659 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004660 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004661 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004662 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004663 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004664 }
4665 }
4666
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004667 private void removeInterfaceQuotaAsync(String iface) {
4668 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4669 }
4670
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004671 private void removeInterfaceQuota(String iface) {
4672 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004673 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004674 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004675 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004676 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004677 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004678 }
4679 }
4680
Felipe Leme70c57c22016-03-29 10:45:13 -07004681 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4682 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004683 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004684 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004685 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004686 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4687 } catch (RemoteException e) {
4688 // ignored; service lives in system_server
4689 }
4690 }
4691
4692 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4693 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4694 try {
4695 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4696 } catch (IllegalStateException e) {
4697 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004698 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004699 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004700 }
4701 }
4702
Felipe Lemebc853dd2016-09-08 13:26:55 -07004703 private static final int CHAIN_TOGGLE_NONE = 0;
4704 private static final int CHAIN_TOGGLE_ENABLE = 1;
4705 private static final int CHAIN_TOGGLE_DISABLE = 2;
4706 @Retention(RetentionPolicy.SOURCE)
4707 @IntDef(flag = false, value = {
4708 CHAIN_TOGGLE_NONE,
4709 CHAIN_TOGGLE_ENABLE,
4710 CHAIN_TOGGLE_DISABLE
4711 })
4712 public @interface ChainToggleType {
4713 }
4714
4715 /**
4716 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004717 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004718 *
4719 * @param chain firewall chain.
4720 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4721 * @param toggle whether the chain should be enabled, disabled, or not changed.
4722 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004723 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004724 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004725 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004726 if (uidRules != null) {
4727 setUidFirewallRulesUL(chain, uidRules);
4728 }
4729 if (toggle != CHAIN_TOGGLE_NONE) {
4730 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4731 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004732 }
4733
Amith Yamasani15e472352015-04-24 19:06:07 -07004734 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004735 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4736 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4737 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004738 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004739 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004740 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004741 int size = uidRules.size();
4742 int[] uids = new int[size];
4743 int[] rules = new int[size];
4744 for(int index = size - 1; index >= 0; --index) {
4745 uids[index] = uidRules.keyAt(index);
4746 rules[index] = uidRules.valueAt(index);
4747 }
4748 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004749 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004750 } catch (IllegalStateException e) {
4751 Log.wtf(TAG, "problem setting firewall uid rules", e);
4752 } catch (RemoteException e) {
4753 // ignored; service lives in system_server
4754 }
4755 }
4756
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004757 /**
4758 * Add or remove a uid to the firewall blacklist for all network ifaces.
4759 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004760 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004761 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4762 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4763 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004764 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004765 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004766 if (chain == FIREWALL_CHAIN_DOZABLE) {
4767 mUidFirewallDozableRules.put(uid, rule);
4768 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4769 mUidFirewallStandbyRules.put(uid, rule);
4770 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4771 mUidFirewallPowerSaveRules.put(uid, rule);
4772 }
4773
4774 try {
4775 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004776 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004777 } catch (IllegalStateException e) {
4778 Log.wtf(TAG, "problem setting firewall uid rules", e);
4779 } catch (RemoteException e) {
4780 // ignored; service lives in system_server
4781 }
4782 } finally {
4783 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004784 }
4785 }
4786
4787 /**
4788 * Add or remove a uid to the firewall blacklist for all network ifaces.
4789 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004790 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004791 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004792 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4793 mFirewallChainStates.get(chain) == enable) {
4794 // All is the same, nothing to do.
4795 return;
4796 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004797 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004798 try {
4799 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004800 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004801 } catch (IllegalStateException e) {
4802 Log.wtf(TAG, "problem enable firewall chain", e);
4803 } catch (RemoteException e) {
4804 // ignored; service lives in system_server
4805 }
4806 }
4807
Felipe Leme03e95e22016-09-09 09:25:31 -07004808 /**
4809 * Resets all firewall rules associated with an UID.
4810 */
4811 private void resetUidFirewallRules(int uid) {
4812 try {
4813 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4814 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4815 mNetworkManager
4816 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4817 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4818 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4819 } catch (IllegalStateException e) {
4820 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4821 } catch (RemoteException e) {
4822 // ignored; service lives in system_server
4823 }
4824 }
4825
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004826 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004827 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004828 return getNetworkTotalBytes(template, start, end);
4829 }
4830
4831 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004832 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004833 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004834 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004835 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004836 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004837 }
4838 }
4839
4840 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4841 try {
4842 return mNetworkStats.getNetworkUidBytes(template, start, end);
4843 } catch (RuntimeException e) {
4844 Slog.w(TAG, "Failed to read network stats: " + e);
4845 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004846 }
4847 }
4848
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004849 private boolean isBandwidthControlEnabled() {
4850 final long token = Binder.clearCallingIdentity();
4851 try {
4852 return mNetworkManager.isBandwidthControlEnabled();
4853 } catch (RemoteException e) {
4854 // ignored; service lives in system_server
4855 return false;
4856 } finally {
4857 Binder.restoreCallingIdentity(token);
4858 }
4859 }
4860
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004861 private static Intent buildAllowBackgroundDataIntent() {
4862 return new Intent(ACTION_ALLOW_BACKGROUND);
4863 }
4864
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004865 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4866 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004867 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4868 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4869 return intent;
4870 }
4871
4872 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4873 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4874 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004875 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4876 return intent;
4877 }
4878
Wei Liu546cb772016-07-21 16:19:01 -07004879 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004880 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004881 intent.setComponent(ComponentName.unflattenFromString(
4882 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004883 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4884 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4885 return intent;
4886 }
4887
Wei Liu546cb772016-07-21 16:19:01 -07004888 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004889 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004890 intent.setComponent(ComponentName.unflattenFromString(
4891 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004892 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4893 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4894 return intent;
4895 }
4896
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004897 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004898 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004899 mHandler.getLooper().getQueue().addIdleHandler(handler);
4900 }
4901
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004902 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004903 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004904 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004905 mRestrictBackgroundPowerState = result;
4906
4907 boolean restrictBackground = result.batterySaverEnabled;
4908 boolean shouldInvokeRestrictBackground;
4909 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4910 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4911
4912 if (result.globalBatterySaverEnabled) {
4913 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4914 // turn it on.
4915 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4916 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4917 localRestrictBgChangedInBsm = false;
4918 } else {
4919 // Try to restore the restrictBackground if it doesn't change in bsm
4920 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4921 restrictBackground = mRestrictBackgroundBeforeBsm;
4922 }
4923
4924 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004925 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004926 }
4927
4928 // Change it at last so setRestrictBackground() won't affect this variable
4929 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4930 }
4931
Jeff Sharkey1b861272011-05-22 00:34:52 -07004932 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4933 final int size = source.size();
4934 for (int i = 0; i < size; i++) {
4935 target.put(source.keyAt(i), true);
4936 }
4937 }
4938
Stuart Scottf1fb3972015-04-02 18:00:02 -07004939 @Override
4940 public void factoryReset(String subscriber) {
4941 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4942
Stuart Scotte3e314d2015-04-20 14:07:45 -07004943 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4944 return;
4945 }
4946
Stuart Scottf1fb3972015-04-02 18:00:02 -07004947 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004948 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004949 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4950 for (NetworkPolicy policy : policies) {
4951 if (policy.template.equals(template)) {
4952 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4953 policy.inferred = false;
4954 policy.clearSnooze();
4955 }
4956 }
4957 setNetworkPolicies(policies);
4958
4959 // Turn restrict background data off
4960 setRestrictBackground(false);
4961
Stuart Scotte3e314d2015-04-20 14:07:45 -07004962 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4963 // Remove app's "restrict background data" flag
4964 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4965 setUidPolicy(uid, POLICY_NONE);
4966 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004967 }
4968 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004969
Sudheer Shankab8f23162017-08-04 13:30:10 -07004970 @Override
4971 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004972 final long startTime = mStatLogger.getTime();
4973
Sudheer Shankab8f23162017-08-04 13:30:10 -07004974 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004975 final int uidRules;
4976 final boolean isBackgroundRestricted;
4977 synchronized (mUidRulesFirstLock) {
4978 uidRules = mUidRules.get(uid, RULE_NONE);
4979 isBackgroundRestricted = mRestrictBackground;
4980 }
junyulai05986c62018-08-07 19:50:45 +08004981 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
4982 isBackgroundRestricted, mLogger);
4983
4984 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4985
4986 return ret;
4987 }
4988
4989 private static boolean isSystem(int uid) {
4990 return uid < Process.FIRST_APPLICATION_UID;
4991 }
4992
4993 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
4994 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
4995 final int reason;
4996 // Networks are never blocked for system components
4997 if (isSystem(uid)) {
4998 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004999 }
junyulai05986c62018-08-07 19:50:45 +08005000 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5001 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005002 }
junyulai05986c62018-08-07 19:50:45 +08005003 else if (!isNetworkMetered) {
5004 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005005 }
junyulai05986c62018-08-07 19:50:45 +08005006 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5007 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005008 }
junyulai05986c62018-08-07 19:50:45 +08005009 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5010 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005011 }
junyulai05986c62018-08-07 19:50:45 +08005012 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5013 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005014 }
junyulai05986c62018-08-07 19:50:45 +08005015 else if (isBackgroundRestricted) {
5016 reason = NTWK_BLOCKED_BG_RESTRICT;
5017 }
5018 else {
5019 reason = NTWK_ALLOWED_DEFAULT;
5020 }
5021
5022 final boolean blocked;
5023 switch(reason) {
5024 case NTWK_ALLOWED_DEFAULT:
5025 case NTWK_ALLOWED_NON_METERED:
5026 case NTWK_ALLOWED_TMP_WHITELIST:
5027 case NTWK_ALLOWED_WHITELIST:
5028 case NTWK_ALLOWED_SYSTEM:
5029 blocked = false;
5030 break;
5031 case NTWK_BLOCKED_POWER:
5032 case NTWK_BLOCKED_BLACKLIST:
5033 case NTWK_BLOCKED_BG_RESTRICT:
5034 blocked = true;
5035 break;
5036 default:
5037 throw new IllegalArgumentException();
5038 }
5039 if (logger != null) {
5040 logger.networkBlocked(uid, reason);
5041 }
5042
5043 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005044 }
5045
Felipe Lemed17fda42016-04-29 11:12:45 -07005046 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5047
5048 @Override
5049 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005050 synchronized (mUidRulesFirstLock) {
5051 boolean changed = removeUserStateUL(userId, false);
5052 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005053 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005054 synchronized (mNetworkPoliciesSecondLock) {
5055 writePolicyAL();
5056 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005057 }
5058 }
5059 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005060
5061 /**
5062 * @return true if the given uid is restricted from doing networking on metered networks.
5063 */
5064 @Override
5065 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5066 final int uidRules;
5067 final boolean isBackgroundRestricted;
5068 synchronized (mUidRulesFirstLock) {
5069 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5070 isBackgroundRestricted = mRestrictBackground;
5071 }
5072 return isBackgroundRestricted
5073 && !hasRule(uidRules, RULE_ALLOW_METERED)
5074 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5075 }
5076
5077 /**
5078 * @return true if networking is blocked on the given interface for the given uid according
5079 * to current networking policies.
5080 */
5081 @Override
5082 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005083 final long startTime = mStatLogger.getTime();
5084
junyulai05986c62018-08-07 19:50:45 +08005085 final int uidRules;
5086 final boolean isBackgroundRestricted;
5087 synchronized (mUidRulesFirstLock) {
5088 uidRules = mUidRules.get(uid, RULE_NONE);
5089 isBackgroundRestricted = mRestrictBackground;
5090 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005091 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005092 synchronized (mNetworkPoliciesSecondLock) {
5093 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005094 }
junyulai05986c62018-08-07 19:50:45 +08005095 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5096 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005097
5098 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5099
5100 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005101 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005102
5103 @Override
5104 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5105 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005106 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005107 if (added) {
5108 mPowerSaveTempWhitelistAppIds.put(appId, true);
5109 } else {
5110 mPowerSaveTempWhitelistAppIds.delete(appId);
5111 }
5112 updateRulesForTempWhitelistChangeUL(appId);
5113 }
5114 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005115
5116 @Override
5117 public SubscriptionPlan getSubscriptionPlan(Network network) {
5118 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005119 final int subId = getSubIdLocked(network);
5120 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005121 }
5122 }
5123
5124 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005125 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5126 synchronized (mNetworkPoliciesSecondLock) {
5127 final int subId = findRelevantSubIdNL(template);
5128 return getPrimarySubscriptionPlanLocked(subId);
5129 }
5130 }
5131
5132 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005133 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005134 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005135 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005136 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005137 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005138 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005139 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5140 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5141 }
5142
5143 if (quotaType == QUOTA_TYPE_JOBS) {
5144 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5145 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5146 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5147 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5148 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5149 } else {
5150 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5151 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005152 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005153
5154 @Override
5155 public void onAdminDataAvailable() {
5156 mAdminDataAvailableLatch.countDown();
5157 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005158
5159 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005160 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5161 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5162 }
5163
5164 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005165 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5166 setMeteredRestrictedPackagesInternal(packageNames, userId);
5167 }
5168
5169 @Override
5170 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5171 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5172 userId, 0, packageNames).sendToTarget();
5173 }
5174 }
5175
5176 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5177 synchronized (mUidRulesFirstLock) {
5178 final Set<Integer> newRestrictedUids = new ArraySet<>();
5179 for (String packageName : packageNames) {
5180 final int uid = getUidForPackage(packageName, userId);
5181 if (uid >= 0) {
5182 newRestrictedUids.add(uid);
5183 }
5184 }
5185 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5186 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5187 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5188 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5189 }
5190 }
5191
5192 private int getUidForPackage(String packageName, int userId) {
5193 try {
5194 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5195 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5196 } catch (NameNotFoundException e) {
5197 return -1;
5198 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005199 }
5200
5201 private int parseSubId(NetworkState state) {
5202 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5203 int subId = INVALID_SUBSCRIPTION_ID;
5204 if (state != null && state.networkCapabilities != null
5205 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5206 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5207 if (spec instanceof StringNetworkSpecifier) {
5208 try {
5209 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5210 } catch (NumberFormatException e) {
5211 }
5212 }
5213 }
5214 return subId;
5215 }
5216
Andreas Gampea36dc622018-02-05 17:19:22 -08005217 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005218 private int getSubIdLocked(Network network) {
5219 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005220 }
5221
Andreas Gampea36dc622018-02-05 17:19:22 -08005222 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005223 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5224 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005225 if (!ArrayUtils.isEmpty(plans)) {
5226 for (SubscriptionPlan plan : plans) {
5227 if (plan.getCycleRule().isRecurring()) {
5228 // Recurring plans will always have an active cycle
5229 return plan;
5230 } else {
5231 // Non-recurring plans need manual test for active cycle
5232 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5233 if (cycle.contains(ZonedDateTime.now(mClock))) {
5234 return plan;
5235 }
5236 }
5237 }
5238 }
5239 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005240 }
5241
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005242 /**
5243 * This will only ever be called once - during device boot.
5244 */
5245 private void waitForAdminData() {
5246 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5247 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5248 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5249 }
5250 }
5251
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005252 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5253 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005254 if (!mNetworkManagerReady) {
5255 return;
5256 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005257 if (oldRestrictedUids == null) {
5258 for (int uid : newRestrictedUids) {
5259 updateRulesForDataUsageRestrictionsUL(uid);
5260 }
5261 return;
5262 }
5263 for (int uid : oldRestrictedUids) {
5264 if (!newRestrictedUids.contains(uid)) {
5265 updateRulesForDataUsageRestrictionsUL(uid);
5266 }
5267 }
5268 for (int uid : newRestrictedUids) {
5269 if (!oldRestrictedUids.contains(uid)) {
5270 updateRulesForDataUsageRestrictionsUL(uid);
5271 }
5272 }
5273 }
5274
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005275 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005276 private boolean isRestrictedByAdminUL(int uid) {
5277 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5278 UserHandle.getUserId(uid));
5279 return restrictedUids != null && restrictedUids.contains(uid);
5280 }
5281
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005282 private static boolean hasRule(int uidRules, int rule) {
5283 return (uidRules & rule) != 0;
5284 }
5285
Jeff Sharkey2e471452018-01-19 18:02:47 +09005286 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5287 return (val != null) ? val : new NetworkState[0];
5288 }
5289
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005290 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5291 String key, boolean defaultValue) {
5292 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5293 }
5294
Heemin Seogb9820d42019-05-21 16:17:43 -07005295 private static boolean isHeadlessSystemUserBuild() {
5296 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
5297 }
5298
Chris Wren193ae6b2017-03-31 15:17:11 -04005299 private class NotificationId {
5300 private final String mTag;
5301 private final int mId;
5302
5303 NotificationId(NetworkPolicy policy, int type) {
5304 mTag = buildNotificationTag(policy, type);
5305 mId = type;
5306 }
5307
5308 @Override
5309 public boolean equals(Object o) {
5310 if (this == o) return true;
5311 if (!(o instanceof NotificationId)) return false;
5312 NotificationId that = (NotificationId) o;
5313 return Objects.equals(mTag, that.mTag);
5314 }
5315
5316 @Override
5317 public int hashCode() {
5318 return Objects.hash(mTag);
5319 }
5320
5321 /**
5322 * Build unique tag that identifies an active {@link NetworkPolicy}
5323 * notification of a specific type, like {@link #TYPE_LIMIT}.
5324 */
5325 private String buildNotificationTag(NetworkPolicy policy, int type) {
5326 return TAG + ":" + policy.template.hashCode() + ":" + type;
5327 }
5328
5329 public String getTag() {
5330 return mTag;
5331 }
5332
5333 public int getId() {
5334 return mId;
5335 }
5336 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005337}