blob: 72c4c5e85f66735ff9ab88b449d8a91ecff32a09 [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;
Sarah Chin92860a702019-08-19 18:08:21 -0700220import com.android.internal.os.SomeArgs;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700221import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800222import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800223import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600224import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700225import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700226import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600227import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700228import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700229import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700230import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700231import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800232import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600233
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600234import libcore.io.IoUtils;
235
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700240import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241import java.io.FileInputStream;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700245import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700246import java.lang.annotation.Retention;
247import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100248import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700249import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900250import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600251import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700252import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600253import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900254import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600256import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700257import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600258import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400259import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800260import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800261import java.util.concurrent.CountDownLatch;
262import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700264/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700265 * Service that maintains low-level network policy rules, using
266 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700267 * <p>
268 * Derives active rules by combining a given policy with other system status,
269 * and delivers to listeners, such as {@link ConnectivityManager}, for
270 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700271 *
272 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700273 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700274 * <ul>
275 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
276 * rules).
277 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
278 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700279 * </ul>
280 *
281 * <p>
282 * As such, methods that require synchronization have the following prefixes:
283 * <ul>
284 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
285 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000286 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
287 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700288 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700290public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700291 static final String TAG = NetworkPolicyLogger.TAG;
292 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
293 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700294
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900295 /**
296 * No opportunistic quota could be calculated from user data plan or data settings.
297 */
298 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
299
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final int VERSION_INIT = 1;
301 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700302 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800304 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800305 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700306 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700307 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700308 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700309 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600310 private static final int VERSION_ADDED_CYCLE = 11;
311 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800313 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400314 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800315 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400316 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400318 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900319 @VisibleForTesting
320 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700321
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String TAG_POLICY_LIST = "policy-list";
323 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600324 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700326 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800327 private static final String TAG_WHITELIST = "whitelist";
328 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800329 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
331 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700332 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700333 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
334 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700335 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600336 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
337 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
338 private static final String ATTR_CYCLE_START = "cycleStart";
339 private static final String ATTR_CYCLE_END = "cycleEnd";
340 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341 private static final String ATTR_WARNING_BYTES = "warningBytes";
342 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
345 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800346 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700347 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700349 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600351 private static final String ATTR_SUB_ID = "subId";
352 private static final String ATTR_TITLE = "title";
353 private static final String ATTR_SUMMARY = "summary";
354 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
355 private static final String ATTR_USAGE_BYTES = "usageBytes";
356 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600357 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800359 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800360 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800361 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800362 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700363 private static final String ACTION_SNOOZE_RAPID =
364 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700365
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800366 /**
367 * Indicates the maximum wait time for admin data to be available;
368 */
369 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
370
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600371 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
372 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
373 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
374 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
375
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700376 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700377 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800378 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800379 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700380 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700381 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
382 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700383 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700384 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900385 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800386 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700387 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700388
Makoto Onuki8e777332017-03-28 11:25:47 -0700389 private static final int UID_MSG_STATE_CHANGED = 100;
390 private static final int UID_MSG_GONE = 101;
391
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600392 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
393
Jeff Sharkey75279902011-05-24 18:39:45 -0700394 private final Context mContext;
395 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700396 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700397 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700398 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700399 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700400 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700401 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
403 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700404 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 private IDeviceIdleController mDeviceIdleController;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700406
407 /** Current cached value of the current Battery Saver mode's setting for restrict background. */
jackqdyulei29c82ab2017-03-10 14:09:16 -0800408 @GuardedBy("mUidRulesFirstLock")
Kweku Adams25fa3a72019-07-12 17:00:17 -0700409 private boolean mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800410
411 // Store the status of restrict background before turning on battery saver.
412 // Used to restore mRestrictBackground when battery saver is turned off.
413 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700414
Sudheer Shanka543339f2017-07-28 15:18:07 -0700415 // Denotes the status of restrict background read from disk.
416 private boolean mLoadedRestrictBackground;
417
Felipe Lemef0823852016-06-08 13:43:08 -0700418 // See main javadoc for instructions on how to use these locks.
419 final Object mUidRulesFirstLock = new Object();
420 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700421
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700422 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
423 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700424
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
426 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
427 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800428 // Store whether user flipped restrict background in battery saver mode
429 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700430
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700431 private final boolean mSuppressDefaultPolicy;
432
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800433 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
434
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700435 private volatile boolean mNetworkManagerReady;
436
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700437 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600438 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700440
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600441 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600442 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600443 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600445 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600446 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600447
Jeff Sharkey9252b342018-01-19 07:58:35 +0900448 /** Map from subId to daily opportunistic quota. */
449 @GuardedBy("mNetworkPoliciesSecondLock")
450 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
451
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700452 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700454 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700456
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700458 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700460 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700461 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800462 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700463
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700464 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700465 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700466 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
467
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800468 // "Power save mode" is the concept used in the DeviceIdleController that includes various
469 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
470 // and "battery saver" are not equivalent.
471
Jeff Sharkey32566012014-12-02 18:30:14 -0800472 /**
473 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700474 * in power save mode, except device idle (doze) still applies.
475 * TODO: An int array might be sufficient
476 */
Felipe Lemef0823852016-06-08 13:43:08 -0700477 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700478 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
479
480 /**
481 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800482 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700483 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800484 */
Felipe Lemef0823852016-06-08 13:43:08 -0700485 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700486 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700487
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700489 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
490
Felipe Lemeb85a6372016-01-14 16:16:16 -0800491 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800492 * UIDs that have been white-listed temporarily to be able to have network access despite being
493 * idle. Other power saving restrictions still apply.
494 */
495 @GuardedBy("mUidRulesFirstLock")
496 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
497
498 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800499 * UIDs that have been initially white-listed by system to avoid restricted background.
500 */
Felipe Lemef0823852016-06-08 13:43:08 -0700501 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800502 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
503 new SparseBooleanArray();
504
505 /**
506 * UIDs that have been initially white-listed by system to avoid restricted background,
507 * but later revoked by user.
508 */
Felipe Lemef0823852016-06-08 13:43:08 -0700509 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800510 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
511 new SparseBooleanArray();
512
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700513 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700514 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800515 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700516 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700517 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800518 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700519
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700520 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700521 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400522 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700523
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700524 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700525 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800526 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700527
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600528 /** Map from network ID to last observed meteredness state */
529 @GuardedBy("mNetworkPoliciesSecondLock")
530 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900531 /** Map from network ID to last observed roaming state */
532 @GuardedBy("mNetworkPoliciesSecondLock")
533 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
534
Jeff Sharkey9252b342018-01-19 07:58:35 +0900535 /** Map from netId to subId as of last update */
536 @GuardedBy("mNetworkPoliciesSecondLock")
537 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
538
Jeff Sharkey146bb332018-04-18 15:42:57 -0600539 /** Map from subId to subscriberId as of last update */
540 @GuardedBy("mNetworkPoliciesSecondLock")
541 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
542 /** Set of all merged subscriberId as of last update */
543 @GuardedBy("mNetworkPoliciesSecondLock")
Malcolm Chen07fcb5b2019-07-02 22:29:35 -0700544 private List<String[]> mMergedSubscriberIds = new ArrayList<>();
Jeff Sharkey146bb332018-04-18 15:42:57 -0600545
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800546 /**
547 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
548 * userId to restricted uids which belong to that user.
549 */
550 @GuardedBy("mUidRulesFirstLock")
551 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
552
Jeff Sharkey32566012014-12-02 18:30:14 -0800553 private final RemoteCallbackList<INetworkPolicyListener>
554 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700555
Dianne Hackborn497175b2014-07-01 12:56:08 -0700556 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700557 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800558 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700559
560 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700562 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700563 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700564
Svet Ganov16a16892015-04-16 10:32:04 -0700565 private final AppOpsManager mAppOps;
566
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800567 private final IPackageManager mIPm;
568
Sudheer Shankae7361852017-03-07 11:51:46 -0800569 private ActivityManagerInternal mActivityManagerInternal;
570
Sudheer Shanka352dc572017-09-22 17:09:38 -0700571 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800572
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700573 // TODO: keep whitelist of system-critical services that should never have
574 // rules enforced, such as system, phone, and radio UIDs.
575
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700576 // TODO: migrate notifications to SystemUI
577
Makoto Onuki49392d32018-04-11 13:51:02 -0700578
579 interface Stats {
580 int UPDATE_NETWORK_ENABLED = 0;
581 int IS_UID_NETWORKING_BLOCKED = 1;
582
583 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
584 }
585
586 public final StatLogger mStatLogger = new StatLogger(new String[] {
587 "updateNetworkEnabledNL()",
588 "isUidNetworkingBlocked()",
589 });
590
Jeff Sharkey75279902011-05-24 18:39:45 -0700591 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700592 INetworkManagementService networkManagement) {
593 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
594 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700595 }
596
Jeff Sharkey9911a282018-02-14 22:29:11 -0700597 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598 return new File(Environment.getDataDirectory(), "system");
599 }
600
Jeff Sharkey9911a282018-02-14 22:29:11 -0700601 private static @NonNull Clock getDefaultClock() {
602 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
603 Clock.systemUTC());
604 }
605
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700606 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700607 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
608 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700609 mContext = checkNotNull(context, "missing context");
610 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700611 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700612 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700613 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700614 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700615 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700616 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700617 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700618
Amith Yamasani450a16b2013-09-18 16:28:50 -0700619 HandlerThread thread = new HandlerThread(TAG);
620 thread.start();
621 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700622
Makoto Onuki8e777332017-03-28 11:25:47 -0700623 // We create another thread for the UID events, which are more time-critical.
624 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
625 /*allowIo=*/ false);
626 mUidEventThread.start();
627 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
628
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700629 mSuppressDefaultPolicy = suppressDefaultPolicy;
630
Dianne Hackborne17b4452018-01-10 13:15:40 -0800631 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700632
633 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800634
Felipe Lemed17fda42016-04-29 11:12:45 -0700635 // Expose private service for system components to use.
636 LocalServices.addService(NetworkPolicyManagerInternal.class,
637 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700638 }
639
640 public void bindConnectivityManager(IConnectivityManager connManager) {
641 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700642 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700643
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700644 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700645 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700646 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700647 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
648 mPowerSaveWhitelistExceptIdleAppIds.clear();
649 if (whitelist != null) {
650 for (int uid : whitelist) {
651 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
652 }
653 }
654 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700655 mPowerSaveWhitelistAppIds.clear();
656 if (whitelist != null) {
657 for (int uid : whitelist) {
658 mPowerSaveWhitelistAppIds.put(uid, true);
659 }
660 }
661 } catch (RemoteException e) {
662 }
663 }
664
Felipe Lemea9505cc2016-02-26 10:28:41 -0800665 /**
666 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
667 * revoke the whitelist.
668 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700669 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800670 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700671 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700672 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800673 final List<UserInfo> users = mUserManager.getUsers();
674 final int numberUsers = users.size();
675
Felipe Lemea110eec2016-04-29 09:58:06 -0700676 boolean changed = false;
677 for (int i = 0; i < numberUsers; i++) {
678 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700679 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700680 }
681 return changed;
682 }
683
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700684 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700685 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700686 final SystemConfig sysConfig = SystemConfig.getInstance();
687 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800688 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
689 boolean changed = false;
690 for (int i = 0; i < allowDataUsage.size(); i++) {
691 final String pkg = allowDataUsage.valueAt(i);
692 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700693 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
694 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800695 final ApplicationInfo app;
696 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700697 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800698 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700699 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
700 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800701 continue;
702 }
703 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700704 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
705 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800706 continue;
707 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700708 final int uid = UserHandle.getUid(userId, app.uid);
709 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
710 if (LOGD)
711 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
712 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800713 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700714 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700715 if (LOGD)
716 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
717 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700718 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700719 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800720 }
721 }
722 return changed;
723 }
724
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800725 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800727 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700728 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800729 // Boost thread's priority during system server init
730 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 if (!isBandwidthControlEnabled()) {
732 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
733 return;
734 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700735
Felipe Leme873a83a2016-09-07 11:34:10 -0700736 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700737 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700738
Felipe Leme873a83a2016-09-07 11:34:10 -0700739 synchronized (mUidRulesFirstLock) {
740 synchronized (mNetworkPoliciesSecondLock) {
741 updatePowerSaveWhitelistUL();
742 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
743 mPowerManagerInternal.registerLowPowerModeObserver(
744 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800745 @Override
746 public int getServiceType() {
747 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700748 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800749
750 @Override
751 public void onLowPowerModeChanged(PowerSaveState result) {
752 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800753 if (LOGD) {
754 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
755 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800756 synchronized (mUidRulesFirstLock) {
757 if (mRestrictPower != enabled) {
758 mRestrictPower = enabled;
759 updateRulesForRestrictPowerUL();
760 }
761 }
762 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800763 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800764 mRestrictPower = mPowerManagerInternal.getLowPowerState(
765 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700766
767 mSystemReady = true;
768
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800769 waitForAdminData();
770
Felipe Leme873a83a2016-09-07 11:34:10 -0700771 // read policy from disk
772 readPolicyAL();
773
jackqdyulei29c82ab2017-03-10 14:09:16 -0800774 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700775 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -0700776 mRestrictBackgroundLowPowerMode = mPowerManagerInternal
777 .getLowPowerState(ServiceType.DATA_SAVER).batterySaverEnabled;
778 if (mRestrictBackgroundLowPowerMode && !mLoadedRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -0700779 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800780 }
781 mPowerManagerInternal.registerLowPowerModeObserver(
782 new PowerManagerInternal.LowPowerModeListener() {
783 @Override
784 public int getServiceType() {
785 return ServiceType.DATA_SAVER;
786 }
787
788 @Override
789 public void onLowPowerModeChanged(PowerSaveState result) {
790 synchronized (mUidRulesFirstLock) {
791 updateRestrictBackgroundByLowPowerModeUL(result);
792 }
793 }
794 });
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
797 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700798 }
Felipe Lemef0823852016-06-08 13:43:08 -0700799
Sudheer Shanka543339f2017-07-28 15:18:07 -0700800 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700801 updateRulesForGlobalChangeAL(false);
802 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700803 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800804 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700805
Sudheer Shankae7361852017-03-07 11:51:46 -0800806 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700807 try {
808 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000809 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700810 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700811 mNetworkManager.registerObserver(mAlertObserver);
812 } catch (RemoteException e) {
813 // ignored; both services live in system_server
814 }
815
816 // listen for changes to power save whitelist
817 final IntentFilter whitelistFilter = new IntentFilter(
818 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
819 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
820
Felipe Leme873a83a2016-09-07 11:34:10 -0700821 // watch for network interfaces to be claimed
822 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
823 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
824
825 // listen for package changes to update policy
826 final IntentFilter packageFilter = new IntentFilter();
827 packageFilter.addAction(ACTION_PACKAGE_ADDED);
828 packageFilter.addDataScheme("package");
829 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
830
831 // listen for UID changes to update policy
832 mContext.registerReceiver(
833 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
834
835 // listen for user changes to update policy
836 final IntentFilter userFilter = new IntentFilter();
837 userFilter.addAction(ACTION_USER_ADDED);
838 userFilter.addAction(ACTION_USER_REMOVED);
839 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
840
841 // listen for stats update events
842 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
843 mContext.registerReceiver(
844 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
845
846 // listen for restrict background changes from notifications
847 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
848 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
849
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700850 // Listen for snooze from notifications
851 mContext.registerReceiver(mSnoozeReceiver,
852 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
853 mContext.registerReceiver(mSnoozeReceiver,
854 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700855
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600856 // listen for configured wifi networks to be loaded
857 final IntentFilter wifiFilter =
858 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
859 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700860
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700861 // listen for carrier config changes to update data cycle information
862 final IntentFilter carrierConfigFilter = new IntentFilter(
863 ACTION_CARRIER_CONFIG_CHANGED);
864 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
865
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600866 // listen for meteredness changes
867 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
868 new NetworkRequest.Builder().build(), mNetworkCallback);
869
Felipe Leme873a83a2016-09-07 11:34:10 -0700870 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600871
872 // Listen for subscriber changes
873 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
874 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
875 @Override
876 public void onSubscriptionsChanged() {
877 updateNetworksInternal();
878 }
879 });
880
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800881 // tell systemReady() that the service has been initialized
882 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700883 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800884 // Restore the default priority after init is done
885 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700886 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700888 }
889
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800890 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700891 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800892 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
893 mHandler.post(() -> initService(initCompleteSignal));
894 return initCompleteSignal;
895 }
896
897 public void systemReady(CountDownLatch initCompleteSignal) {
898 // wait for initService to complete
899 try {
900 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
901 throw new IllegalStateException("Service " + TAG +" init timeout");
902 }
903 } catch (InterruptedException e) {
904 Thread.currentThread().interrupt();
905 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
906 }
907 }
908
Sudheer Shankac9d94072017-02-22 22:13:55 +0000909 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700910 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700911 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
912 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700913 }
914
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700915 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700916 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700917 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700918
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700919 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700920 }
921
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700922 @Override public void onUidIdle(int uid, boolean disabled) {
923 }
924
925 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700926 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700927 };
928
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700929 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700930 @Override
931 public void onReceive(Context context, Intent intent) {
932 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700933 synchronized (mUidRulesFirstLock) {
934 updatePowerSaveWhitelistUL();
935 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700936 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700937 }
938 }
939 };
940
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700942 @Override
943 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700944 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700945
946 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700947 final int uid = intent.getIntExtra(EXTRA_UID, -1);
948 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700949
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700950 if (ACTION_PACKAGE_ADDED.equals(action)) {
951 // update rules for UID, since it might be subject to
952 // global background data policy
953 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700954 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700955 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700956 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700957 }
958 }
959 };
960
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700961 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700962 @Override
963 public void onReceive(Context context, Intent intent) {
964 // on background handler thread, and UID_REMOVED is protected
965
966 final int uid = intent.getIntExtra(EXTRA_UID, -1);
967 if (uid == -1) return;
968
969 // remove any policy and update rules to clean up
970 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700971 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700972 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700973 synchronized (mNetworkPoliciesSecondLock) {
974 writePolicyAL();
975 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700976 }
977 }
978 };
979
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700980 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700981 @Override
982 public void onReceive(Context context, Intent intent) {
983 // on background handler thread, and USER_ADDED and USER_REMOVED
984 // broadcasts are protected
985
986 final String action = intent.getAction();
987 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
988 if (userId == -1) return;
989
Amith Yamasani15e472352015-04-24 19:06:07 -0700990 switch (action) {
991 case ACTION_USER_REMOVED:
992 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700993 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800994 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700995 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700996 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800997 // Removing outside removeUserStateUL since that can also be called when
998 // user resets app preferences.
999 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001000 if (action == ACTION_USER_ADDED) {
1001 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001002 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001003 }
1004 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001005 synchronized (mNetworkPoliciesSecondLock) {
1006 updateRulesForGlobalChangeAL(true);
1007 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001008 }
1009 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001010 }
1011 }
1012 };
1013
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001014 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015 * Receiver that watches for {@link INetworkStatsService} updates, which we
1016 * use to check against {@link NetworkPolicy#warningBytes}.
1017 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001018 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 @Override
1020 public void onReceive(Context context, Intent intent) {
1021 // on background handler thread, and verified
1022 // READ_NETWORK_USAGE_HISTORY permission above.
1023
Felipe Lemef0823852016-06-08 13:43:08 -07001024 synchronized (mNetworkPoliciesSecondLock) {
1025 updateNetworkEnabledNL();
1026 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 }
1028 }
1029 };
1030
1031 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001032 * Receiver that watches for {@link Notification} control of
1033 * {@link #mRestrictBackground}.
1034 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001035 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001036 @Override
1037 public void onReceive(Context context, Intent intent) {
1038 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1039 // permission above.
1040
1041 setRestrictBackground(false);
1042 }
1043 };
1044
1045 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001046 * Receiver that watches for {@link Notification} control of
1047 * {@link NetworkPolicy#lastWarningSnooze}.
1048 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001049 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001050 @Override
1051 public void onReceive(Context context, Intent intent) {
1052 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1053 // permission above.
1054
1055 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001056 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1057 performSnooze(template, TYPE_WARNING);
1058 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1059 performSnooze(template, TYPE_RAPID);
1060 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 }
1062 };
1063
1064 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001065 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001066 * we can perform upgrade logic. After initial upgrade logic, it updates
1067 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001068 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001069 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001070 @Override
1071 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001072 synchronized (mUidRulesFirstLock) {
1073 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001074 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001075 }
1076 }
1077 // Only need to perform upgrade logic once
1078 mContext.unregisterReceiver(this);
1079 }
1080 };
1081
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001082 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1083 Network network) {
1084 final boolean lastValue = lastValues.get(network.netId, false);
1085 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1086 if (changed) {
1087 lastValues.put(network.netId, newValue);
1088 }
1089 return changed;
1090 }
1091
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001092 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1093 @Override
1094 public void onCapabilitiesChanged(Network network,
1095 NetworkCapabilities networkCapabilities) {
1096 if (network == null || networkCapabilities == null) return;
1097
1098 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001099 final boolean newMetered = !networkCapabilities
1100 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001101 final boolean meteredChanged = updateCapabilityChange(
1102 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001103
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001104 final boolean newRoaming = !networkCapabilities
1105 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1106 final boolean roamingChanged = updateCapabilityChange(
1107 mNetworkRoaming, newRoaming, network);
1108
1109 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001110 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001111 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001112 }
1113 }
1114 }
1115 };
1116
1117 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 * Observer that watches for {@link INetworkManagementService} alerts.
1119 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001120 final private INetworkManagementEventObserver mAlertObserver
1121 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001122 @Override
1123 public void limitReached(String limitName, String iface) {
1124 // only someone like NMS should be calling us
1125 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1126
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001127 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1128 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 }
1130 }
1131 };
1132
1133 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1135 * to show visible notifications as needed.
1136 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001137 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001138 void updateNotificationsNL() {
1139 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001140 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001143 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145
1146 // TODO: when switching to kernel notifications, compute next future
1147 // cycle boundary to recompute notifications.
1148
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001149 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001150 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1152 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001153 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001154
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001156 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001157 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001158
Jeff Sharkey53313d72017-07-13 16:47:32 -06001159 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1160 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001161 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1162 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1163 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001165 // Carrier might want to manage notifications themselves
1166 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001167 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1168 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1169 // Don't show notifications until we confirm that the loaded config is from an
1170 // identified carrier, which may want to manage their own notifications. This method
1171 // should be called every time the carrier config changes anyways, and there's no
1172 // reason to alert if there isn't a carrier.
1173 return;
1174 }
1175
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001176 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1177 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1178 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1179 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1180 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1181 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1182
1183 // Notify when data usage is over warning
1184 if (notifyWarning) {
1185 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1186 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1187 if (!snoozedThisCycle) {
1188 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1189 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001191 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001193 // Notify when data usage is over limit
1194 if (notifyLimit) {
1195 if (policy.isOverLimit(totalBytes)) {
1196 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1197 if (snoozedThisCycle) {
1198 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1199 } else {
1200 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1201 notifyOverLimitNL(policy.template);
1202 }
1203 } else {
1204 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001205 }
1206 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001207
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 // Warn if average usage over last 4 days is on track to blow pretty
1209 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001210 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001211 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001212 final long recentStart = now - recentDuration;
1213 final long recentEnd = now;
1214 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001215
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001216 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001217 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001218 final long alertBytes = (policy.limitBytes * 3) / 2;
1219
1220 if (LOGD) {
1221 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1222 + projectedBytes + " alert " + alertBytes);
1223 }
1224
1225 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1226 - DateUtils.DAY_IN_MILLIS;
1227 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001228 enqueueNotification(policy, TYPE_RAPID, 0,
1229 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001230 }
1231 }
1232 }
1233
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001235 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001236 final NotificationId notificationId = beforeNotifs.valueAt(i);
1237 if (!mActiveNotifs.contains(notificationId)) {
1238 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 }
1240 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001241
1242 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001243 }
1244
1245 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 * Attempt to find a specific app to blame for rapid data usage during the
1247 * given time period.
1248 */
1249 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1250 long start, long end) {
1251 long totalBytes = 0;
1252 long maxBytes = 0;
1253 int maxUid = 0;
1254
1255 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1256 NetworkStats.Entry entry = null;
1257 for (int i = 0; i < stats.size(); i++) {
1258 entry = stats.getValues(i, entry);
1259 final long bytes = entry.rxBytes + entry.txBytes;
1260 totalBytes += bytes;
1261 if (bytes > maxBytes) {
1262 maxBytes = bytes;
1263 maxUid = entry.uid;
1264 }
1265 }
1266
1267 // Only point blame if the majority of usage was done by a single app.
1268 // TODO: support shared UIDs
1269 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1270 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001271 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001272 try {
1273 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1274 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1275 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1276 } catch (NameNotFoundException ignored) {
1277 }
1278 }
1279 }
1280
1281 return null;
1282 }
1283
1284 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001285 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001286 * current device state, such as when
1287 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1288 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001289 *
1290 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1291 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001292 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001293 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001294 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001295 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001296 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1297 final int subId = mSubIdToSubscriberId.keyAt(i);
1298 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001299 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1300 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1301 true);
1302 if (template.matches(probeIdent)) {
1303 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001304 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001305 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001306 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001307 }
1308
1309 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001310 * Notify that given {@link NetworkTemplate} is over
1311 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1312 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001313 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001314 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001316 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001317 mOverLimitNotified.add(template);
1318 }
1319 }
1320
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001321 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001322 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001323 mOverLimitNotified.remove(template);
1324 }
1325
1326 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 * Show notification for combined {@link NetworkPolicy} and specific type,
1328 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1329 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001330 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1331 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001332 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001333 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001334 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001335 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001336 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001337 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001338 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001339
1340 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001341 final CharSequence title;
1342 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001343 switch (type) {
1344 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001345 title = res.getText(R.string.data_usage_warning_title);
1346 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001347 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001349 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001350
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001351 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1352 builder.setDeleteIntent(PendingIntent.getBroadcast(
1353 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1354
Wei Liu546cb772016-07-21 16:19:01 -07001355 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001356 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001357 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001358 builder.setContentIntent(PendingIntent.getActivityAsUser(
1359 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1360 /* options= */ null, UserHandle.CURRENT));
1361 } else {
1362 builder.setContentIntent(PendingIntent.getActivity(
1363 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1364 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001365 break;
1366 }
1367 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001368 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001369 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001370 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001371 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001372 case MATCH_WIFI:
1373 title = res.getText(R.string.data_usage_wifi_limit_title);
1374 break;
1375 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001376 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001377 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001378 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001379
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001380 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001381 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001382
Wei Liu546cb772016-07-21 16:19:01 -07001383 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001384 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001385 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001386 builder.setContentIntent(PendingIntent.getActivityAsUser(
1387 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1388 /* options= */ null, UserHandle.CURRENT));
1389 } else {
1390 builder.setContentIntent(PendingIntent.getActivity(
1391 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1392 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001393 break;
1394 }
1395 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001396 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001397 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001398 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1399 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001400 case MATCH_WIFI:
1401 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1402 break;
1403 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001404 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001405 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001406 final long overBytes = totalBytes - policy.limitBytes;
1407 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001408 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001409
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001410 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001411 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001412 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001413
Wei Liu546cb772016-07-21 16:19:01 -07001414 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001415 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001416 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001417 builder.setContentIntent(PendingIntent.getActivityAsUser(
1418 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT,
1419 /* options= */ null, UserHandle.CURRENT));
1420 } else {
1421 builder.setContentIntent(PendingIntent.getActivity(
1422 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1423 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001424 break;
1425 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001426 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001427 title = res.getText(R.string.data_usage_rapid_title);
1428 if (rapidBlame != null) {
1429 body = res.getString(R.string.data_usage_rapid_app_body,
1430 rapidBlame.loadLabel(mContext.getPackageManager()));
1431 } else {
1432 body = res.getString(R.string.data_usage_rapid_body);
1433 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001434
Jeff Sharkey2e471452018-01-19 18:02:47 +09001435 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001436
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001437 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1438 builder.setDeleteIntent(PendingIntent.getBroadcast(
1439 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1440
1441 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Heemin Seogb9820d42019-05-21 16:17:43 -07001442 // TODO: Resolve to single code path.
Eric Jeonge7ead1b2019-07-18 09:37:08 -07001443 if (UserManager.isHeadlessSystemUserMode()) {
Heemin Seogb9820d42019-05-21 16:17:43 -07001444 builder.setContentIntent(PendingIntent.getActivityAsUser(
1445 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT,
1446 /* options= */ null, UserHandle.CURRENT));
1447 } else {
1448 builder.setContentIntent(PendingIntent.getActivity(
1449 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1450 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001451 break;
1452 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001453 default: {
1454 return;
1455 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001456 }
1457
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001458 builder.setTicker(title);
1459 builder.setContentTitle(title);
1460 builder.setContentText(body);
1461 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001462
1463 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1464 notificationId.getId(), builder.build(), UserHandle.ALL);
1465 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001466 }
1467
Chris Wren193ae6b2017-03-31 15:17:11 -04001468 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001469 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1470 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001471 }
1472
1473 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001474 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001475 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001477 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478 @Override
1479 public void onReceive(Context context, Intent intent) {
1480 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1481 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001482 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483 }
1484 };
1485
Jeff Sharkey146bb332018-04-18 15:42:57 -06001486 private void updateNetworksInternal() {
1487 // Get all of our cross-process communication with telephony out of
1488 // the way before we acquire internal locks.
1489 updateSubscriptions();
1490
1491 synchronized (mUidRulesFirstLock) {
1492 synchronized (mNetworkPoliciesSecondLock) {
1493 ensureActiveMobilePolicyAL();
1494 normalizePoliciesNL();
1495 updateNetworkEnabledNL();
1496 updateNetworkRulesNL();
1497 updateNotificationsNL();
1498 }
1499 }
1500 }
1501
Jeff Sharkey2e471452018-01-19 18:02:47 +09001502 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001503 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001504 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001505 final CountDownLatch latch = new CountDownLatch(1);
1506 mHandler.post(() -> {
1507 latch.countDown();
1508 });
1509 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001510 }
1511
Sudheer Shankac0f85c12019-10-12 15:01:44 -07001512 @VisibleForTesting
1513 Handler getHandlerForTesting() {
1514 return mHandler;
1515 }
1516
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001518 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1519 * if necessary.
1520 *
1521 * @param subId that has its associated NetworkPolicy updated if necessary
1522 * @return if any policies were updated
1523 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001524 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001525 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001526 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001527
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001528 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001529 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001530 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001531 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001532 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1533 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1534 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001535 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1536 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001537 }
1538 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001539 return policyUpdated;
1540 }
1541
1542 /**
1543 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1544 *
1545 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1546 * to do so, it returns the fallback value.
1547 *
1548 * @param config The CarrierConfig to read the value from.
1549 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1550 * @return cycleDay to use in the mobile NetworkPolicy.
1551 */
1552 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001553 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001554 int fallbackCycleDay) {
1555 if (config == null) {
1556 return fallbackCycleDay;
1557 }
1558 int cycleDay =
1559 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1560 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1561 return fallbackCycleDay;
1562 }
1563 // validate cycleDay value
1564 final Calendar cal = Calendar.getInstance();
1565 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1566 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1567 Slog.e(TAG, "Invalid date in "
1568 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1569 return fallbackCycleDay;
1570 }
1571 return cycleDay;
1572 }
1573
1574 /**
1575 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1576 *
1577 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1578 * to do so, it returns the fallback value.
1579 *
1580 * @param config The CarrierConfig to read the value from.
1581 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1582 * @return warningBytes to use in the mobile NetworkPolicy.
1583 */
1584 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001585 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001586 long fallbackWarningBytes) {
1587 if (config == null) {
1588 return fallbackWarningBytes;
1589 }
1590 long warningBytes =
1591 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1592
1593 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1594 return WARNING_DISABLED;
1595 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1596 return getPlatformDefaultWarningBytes();
1597 } else if (warningBytes < 0) {
1598 Slog.e(TAG, "Invalid value in "
1599 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1600 + "non-negative value but got: " + warningBytes);
1601 return fallbackWarningBytes;
1602 }
1603
1604 return warningBytes;
1605 }
1606
1607 /**
1608 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1609 *
1610 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1611 * to do so, it returns the fallback value.
1612 *
1613 * @param config The CarrierConfig to read the value from.
1614 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1615 * @return limitBytes to use in the mobile NetworkPolicy.
1616 */
1617 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001618 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001619 long fallbackLimitBytes) {
1620 if (config == null) {
1621 return fallbackLimitBytes;
1622 }
1623 long limitBytes =
1624 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1625
1626 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1627 return LIMIT_DISABLED;
1628 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1629 return getPlatformDefaultLimitBytes();
1630 } else if (limitBytes < 0) {
1631 Slog.e(TAG, "Invalid value in "
1632 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1633 + "non-negative value but got: " + limitBytes);
1634 return fallbackLimitBytes;
1635 }
1636 return limitBytes;
1637 }
1638
1639 /**
1640 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1641 */
1642 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1643 @Override
1644 public void onReceive(Context context, Intent intent) {
1645 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1646 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1647
1648 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1649 return;
1650 }
1651 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001652
1653 // Get all of our cross-process communication with telephony out of
1654 // the way before we acquire internal locks.
1655 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001656
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001657 synchronized (mUidRulesFirstLock) {
1658 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001659 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1660 if (subscriberId != null) {
1661 ensureActiveMobilePolicyAL(subId, subscriberId);
1662 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1663 } else {
1664 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1665 }
1666
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001667 // update network and notification rules, as the data cycle changed and it's
1668 // possible that we should be triggering warnings/limits now
1669 handleNetworkPoliciesUpdateAL(true);
1670 }
1671 }
1672 }
1673 };
1674
1675 /**
1676 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1677 * one has been updated.
1678 *
1679 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1680 * update.
1681 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001682 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001683 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1684 if (shouldNormalizePolicies) {
1685 normalizePoliciesNL();
1686 }
1687 updateNetworkEnabledNL();
1688 updateNetworkRulesNL();
1689 updateNotificationsNL();
1690 writePolicyAL();
1691 }
1692
1693 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001694 * Proactively control network data connections when they exceed
1695 * {@link NetworkPolicy#limitBytes}.
1696 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001697 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001698 void updateNetworkEnabledNL() {
1699 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001700 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001701
1702 // TODO: reset any policy-disabled networks when any policy is removed
1703 // completely, which is currently rare case.
1704
Makoto Onuki49392d32018-04-11 13:51:02 -07001705 final long startTime = mStatLogger.getTime();
1706
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001707 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1708 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001709 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001710 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001711 setNetworkTemplateEnabled(policy.template, true);
1712 continue;
1713 }
1714
Jeff Sharkey53313d72017-07-13 16:47:32 -06001715 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1716 .cycleIterator(policy).next();
1717 final long start = cycle.first.toInstant().toEpochMilli();
1718 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001719 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001720
1721 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001722 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1723 && policy.lastLimitSnooze < start;
1724 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001725
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001726 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001727 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001728
1729 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001730 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001731 }
1732
1733 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001734 * Proactively disable networks that match the given
1735 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001736 */
1737 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001738 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1739 // held. Call it via the handler.
1740 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1741 .sendToTarget();
1742 }
1743
1744 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001745 // TODO: reach into ConnectivityManager to proactively disable bringing
1746 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001747
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001748 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001749 // If mobile data usage hits the limit or if the user resumes the data, we need to
1750 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001751
Jeff Sharkey146bb332018-04-18 15:42:57 -06001752 final IntArray matchingSubIds = new IntArray();
1753 synchronized (mNetworkPoliciesSecondLock) {
1754 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1755 final int subId = mSubIdToSubscriberId.keyAt(i);
1756 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1757
1758 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1759 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1760 true);
1761 // Template is matched when subscriber id matches.
1762 if (template.matches(probeIdent)) {
1763 matchingSubIds.add(subId);
1764 }
Jack Yu8781b682016-07-08 14:28:51 -07001765 }
1766 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001767
1768 // Only talk with telephony outside of locks
1769 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1770 for (int i = 0; i < matchingSubIds.size(); i++) {
1771 final int subId = matchingSubIds.get(i);
1772 tm.setPolicyDataEnabled(enabled, subId);
1773 }
Jack Yu8781b682016-07-08 14:28:51 -07001774 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001775 }
1776
1777 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001778 * Collect all ifaces from a {@link NetworkState} into the given set.
1779 */
1780 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1781 final String baseIface = state.linkProperties.getInterfaceName();
1782 if (baseIface != null) {
1783 ifaces.add(baseIface);
1784 }
1785 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1786 final String stackedIface = stackedLink.getInterfaceName();
1787 if (stackedIface != null) {
1788 ifaces.add(stackedIface);
1789 }
1790 }
1791 }
1792
1793 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001794 * Examine all currently active subscriptions from
1795 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1796 * internal data structures.
1797 * <p>
1798 * Callers <em>must not</em> hold any locks when this method called.
1799 */
1800 void updateSubscriptions() {
1801 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1802 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1803
1804 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1805 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1806
1807 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001808 final List<String[]> mergedSubscriberIdsList = new ArrayList();
Jeff Sharkey146bb332018-04-18 15:42:57 -06001809
1810 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1811 for (int subId : subIds) {
1812 final String subscriberId = tm.getSubscriberId(subId);
1813 if (!TextUtils.isEmpty(subscriberId)) {
1814 subIdToSubscriberId.put(subId, subscriberId);
1815 } else {
1816 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1817 }
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001818
1819 String[] mergedSubscriberId = ArrayUtils.defeatNullable(
1820 tm.createForSubscriptionId(subId).getMergedSubscriberIdsFromGroup());
1821 mergedSubscriberIdsList.add(mergedSubscriberId);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001822 }
1823
1824 synchronized (mNetworkPoliciesSecondLock) {
1825 mSubIdToSubscriberId.clear();
1826 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1827 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1828 subIdToSubscriberId.valueAt(i));
1829 }
1830
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07001831 mMergedSubscriberIds = mergedSubscriberIdsList;
Jeff Sharkey146bb332018-04-18 15:42:57 -06001832 }
1833
1834 Trace.traceEnd(TRACE_TAG_NETWORK);
1835 }
1836
1837 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001838 * Examine all connected {@link NetworkState}, looking for
1839 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1840 * remaining quota based on usage cycle and historical stats.
1841 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001842 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001843 void updateNetworkRulesNL() {
1844 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001845 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001846
1847 final NetworkState[] states;
1848 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001849 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001851 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001852 return;
1853 }
1854
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001855 // First, generate identities of all connected networks so we can
1856 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001857 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001858 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001859 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001860 if (state.network != null) {
1861 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1862 }
Wei Liub8eaf452016-01-25 10:32:27 -08001863 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001864 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1865 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001866 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001867 }
1868 }
1869
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001870 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001871 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001872
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001873 // For every well-defined policy, compute remaining data based on
1874 // current cycle and historical stats, and push to kernel.
1875 final ArraySet<String> matchingIfaces = new ArraySet<>();
1876 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1877 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1878
1879 // Collect all ifaces that match this policy
1880 matchingIfaces.clear();
1881 for (int j = identified.size() - 1; j >= 0; j--) {
1882 if (policy.template.matches(identified.valueAt(j))) {
1883 collectIfaces(matchingIfaces, identified.keyAt(j));
1884 }
1885 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001886
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001887 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001888 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001889 }
1890
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001891 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001892 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001893 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001894 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001895 if (hasLimit && policy.hasCycle()) {
1896 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1897 .cycleIterator(policy).next();
1898 final long start = cycle.first.toInstant().toEpochMilli();
1899 final long end = cycle.second.toInstant().toEpochMilli();
1900 final long totalBytes = getTotalBytes(policy.template, start, end);
1901
1902 if (policy.lastLimitSnooze >= start) {
1903 // snoozing past quota, but we still need to restrict apps,
1904 // so push really high quota.
1905 quotaBytes = Long.MAX_VALUE;
1906 } else {
1907 // remaining "quota" bytes are based on total usage in
1908 // current cycle. kernel doesn't like 0-byte rules, so we
1909 // set 1-byte quota and disable the radio later.
1910 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1911 }
1912 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001913 // metered network, but no policy limit; we still need to
1914 // restrict apps, so push really high quota.
1915 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001916 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001917
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001918 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001919 // TODO: switch to shared quota once NMS supports
1920 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001921 }
1922
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001923 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1924 final String iface = matchingIfaces.valueAt(j);
1925 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001926 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001927 }
1928 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001929
1930 // keep track of lowest warning or limit of active policies
1931 if (hasWarning && policy.warningBytes < lowestRule) {
1932 lowestRule = policy.warningBytes;
1933 }
1934 if (hasLimit && policy.limitBytes < lowestRule) {
1935 lowestRule = policy.limitBytes;
1936 }
1937 }
1938
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001939 // One final pass to catch any metered ifaces that don't have explicitly
1940 // defined policies; typically Wi-Fi networks.
1941 for (NetworkState state : states) {
1942 if (state.networkInfo != null && state.networkInfo.isConnected()
1943 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1944 matchingIfaces.clear();
1945 collectIfaces(matchingIfaces, state);
1946 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1947 final String iface = matchingIfaces.valueAt(j);
1948 if (!newMeteredIfaces.contains(iface)) {
1949 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1950 newMeteredIfaces.add(iface);
1951 }
1952 }
1953 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001954 }
1955
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001956 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001957 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1958 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001959 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001960 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001961 }
1962 }
1963 mMeteredIfaces = newMeteredIfaces;
1964
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001965 final ContentResolver cr = mContext.getContentResolver();
1966 final boolean quotaEnabled = Settings.Global.getInt(cr,
1967 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1968 final long quotaUnlimited = Settings.Global.getLong(cr,
1969 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1970 final float quotaLimited = Settings.Global.getFloat(cr,
1971 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1972
Jeff Sharkey9252b342018-01-19 07:58:35 +09001973 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001974 mSubscriptionOpportunisticQuota.clear();
1975 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001976 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001977 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001978 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001979 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001980 if (plan == null) continue;
1981
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001982 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001983 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001984 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1985 // Clamp to 0 when roaming
1986 quotaBytes = 0;
1987 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001988 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001989 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001990 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001991 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001992 } else {
1993 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001994 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1995 final long start = cycle.getLower().toInstant().toEpochMilli();
1996 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001997 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001998 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001999 .truncatedTo(ChronoUnit.DAYS)
2000 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09002001 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002002 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
2003 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09002004 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09002005 // Number of remaining days including current day
2006 final long remainingDays =
2007 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09002008
Jeff Sharkey36b414b2018-03-30 11:00:03 -06002009 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09002010 }
2011
2012 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
2013 }
2014
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002015 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002016 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06002017
2018 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06002019
2020 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002021 }
2022
2023 /**
2024 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2025 * have at least a default mobile policy defined.
2026 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002027 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002028 private void ensureActiveMobilePolicyAL() {
2029 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002030 if (mSuppressDefaultPolicy) return;
2031
Jeff Sharkey146bb332018-04-18 15:42:57 -06002032 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
2033 final int subId = mSubIdToSubscriberId.keyAt(i);
2034 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002035
Hugo Benichi446c9c92017-04-10 09:41:10 +09002036 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002037 }
2038 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002039
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002040 /**
2041 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2042 * have at least a default mobile policy defined.
2043 *
2044 * @param subId to build a default policy for
2045 * @param subscriberId that we check for an existing policy
2046 * @return true if a mobile network policy was added, or false one already existed.
2047 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002048 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002049 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002050 // Poke around to see if we already have a policy
2051 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002052 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002053 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2054 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2055 if (template.matches(probeIdent)) {
2056 if (LOGD) {
2057 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2058 + NetworkIdentity.scrubSubscriberId(subscriberId));
2059 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002060 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002061 }
2062 }
2063
Jeff Sharkey32566012014-12-02 18:30:14 -08002064 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2065 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002066 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002067 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002068 return true;
2069 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002070
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002071 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002072 final int dataWarningConfig = mContext.getResources().getInteger(
2073 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002074 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002075 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002076 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002077 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002078 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002079 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002080
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002081 private long getPlatformDefaultLimitBytes() {
2082 return LIMIT_DISABLED;
2083 }
2084
2085 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002086 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002087 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002088 final RecurrenceRule cycleRule = NetworkPolicy
2089 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002090 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002091 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2092 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2093 synchronized (mUidRulesFirstLock) {
2094 synchronized (mNetworkPoliciesSecondLock) {
2095 updateDefaultMobilePolicyAL(subId, policy);
2096 }
2097 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002098 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002099 }
2100
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002101 /**
2102 * Update the given {@link NetworkPolicy} based on any carrier-provided
2103 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2104 * Leaves policy untouched if the user has modified it.
2105 *
2106 * @return if the policy was modified
2107 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002108 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002109 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2110 if (!policy.inferred) {
2111 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2112 return false;
2113 }
2114
2115 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2116 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2117 policy.lastLimitSnooze, policy.metered, policy.inferred);
2118
2119 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2120 if (!ArrayUtils.isEmpty(plans)) {
2121 final SubscriptionPlan plan = plans[0];
2122 policy.cycleRule = plan.getCycleRule();
2123 final long planLimitBytes = plan.getDataLimitBytes();
2124 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2125 policy.warningBytes = getPlatformDefaultWarningBytes();
2126 policy.limitBytes = getPlatformDefaultLimitBytes();
2127 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2128 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2129 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2130 } else {
2131 policy.warningBytes = (planLimitBytes * 9) / 10;
2132 switch (plan.getDataLimitBehavior()) {
2133 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2134 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2135 policy.limitBytes = planLimitBytes;
2136 break;
2137 default:
2138 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2139 break;
2140 }
2141 }
2142 } else {
2143 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2144 final int currentCycleDay;
2145 if (policy.cycleRule.isMonthly()) {
2146 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2147 } else {
2148 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2149 }
2150 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2151 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2152 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2153 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2154 }
2155
2156 if (policy.equals(original)) {
2157 return false;
2158 } else {
2159 Slog.d(TAG, "Updated " + original + " to " + policy);
2160 return true;
2161 }
2162 }
2163
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002164 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002165 private void readPolicyAL() {
2166 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002167
2168 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002169 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002170 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002171 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002172 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173
2174 FileInputStream fis = null;
2175 try {
2176 fis = mPolicyFile.openRead();
2177 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002178 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179
Felipe Leme46b451f2016-08-19 08:46:17 -07002180 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2181 // to skip UIDs that were explicitly blacklisted.
2182 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2183
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002185 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002186 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 while ((type = in.next()) != END_DOCUMENT) {
2188 final String tag = in.getName();
2189 if (type == START_TAG) {
2190 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002191 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002192 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002193 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2194 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002195 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2196 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2197 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002198 final String networkId;
2199 if (version >= VERSION_ADDED_NETWORK_ID) {
2200 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2201 } else {
2202 networkId = null;
2203 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002204 final RecurrenceRule cycleRule;
2205 if (version >= VERSION_ADDED_CYCLE) {
2206 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2207 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2208 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2209 cycleRule = new RecurrenceRule(
2210 RecurrenceRule.convertZonedDateTime(start),
2211 RecurrenceRule.convertZonedDateTime(end),
2212 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002213 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002214 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2215 final String cycleTimezone;
2216 if (version >= VERSION_ADDED_TIMEZONE) {
2217 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2218 } else {
2219 cycleTimezone = "UTC";
2220 }
2221 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002222 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002223 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2224 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002225 final long lastLimitSnooze;
2226 if (version >= VERSION_SPLIT_SNOOZE) {
2227 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2228 } else if (version >= VERSION_ADDED_SNOOZE) {
2229 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002230 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002231 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002232 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002233 final boolean metered;
2234 if (version >= VERSION_ADDED_METERED) {
2235 metered = readBooleanAttribute(in, ATTR_METERED);
2236 } else {
2237 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002238 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002239 metered = true;
2240 break;
2241 default:
2242 metered = false;
2243 }
2244 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002245 final long lastWarningSnooze;
2246 if (version >= VERSION_SPLIT_SNOOZE) {
2247 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2248 } else {
2249 lastWarningSnooze = SNOOZE_NEVER;
2250 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002251 final boolean inferred;
2252 if (version >= VERSION_ADDED_INFERRED) {
2253 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2254 } else {
2255 inferred = false;
2256 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002257
Jeff Sharkey32566012014-12-02 18:30:14 -08002258 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2259 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002260 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002261 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2262 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002263 lastLimitSnooze, metered, inferred));
2264 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002265
2266 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2267 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2268 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2269 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2270 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2271 RecurrenceRule.convertZonedDateTime(start),
2272 RecurrenceRule.convertZonedDateTime(end),
2273 RecurrenceRule.convertPeriod(period));
2274 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2275 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2276
2277 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2278 SubscriptionPlan.BYTES_UNKNOWN);
2279 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2280 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2281 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2282 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2283 builder.setDataLimit(limitBytes, limitBehavior);
2284 }
2285
2286 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2287 SubscriptionPlan.BYTES_UNKNOWN);
2288 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2289 SubscriptionPlan.TIME_UNKNOWN);
2290 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2291 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2292 builder.setDataUsage(usageBytes, usageTime);
2293 }
2294
2295 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2296 final SubscriptionPlan plan = builder.build();
2297 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2298 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2299
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002300 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2301 mSubscriptionPlansOwner.put(subId, ownerPackage);
2302
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002303 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002304 final int uid = readIntAttribute(in, ATTR_UID);
2305 final int policy = readIntAttribute(in, ATTR_POLICY);
2306
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002307 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002308 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002309 } else {
2310 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2311 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002312 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002313 final int appId = readIntAttribute(in, ATTR_APP_ID);
2314 final int policy = readIntAttribute(in, ATTR_POLICY);
2315
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002316 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002317 // app policy is deprecated so this is only used in pre system user split.
2318 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002319 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002320 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002321 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002322 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002323 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002324 } else if (TAG_WHITELIST.equals(tag)) {
2325 insideWhitelist = true;
2326 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2327 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002328 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002329 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2330 final int uid = readIntAttribute(in, ATTR_UID);
2331 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002332 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002333 } else if (type == END_TAG) {
2334 if (TAG_WHITELIST.equals(tag)) {
2335 insideWhitelist = false;
2336 }
2337
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002338 }
2339 }
2340
Felipe Leme46b451f2016-08-19 08:46:17 -07002341 final int size = whitelistedRestrictBackground.size();
2342 for (int i = 0; i < size; i++) {
2343 final int uid = whitelistedRestrictBackground.keyAt(i);
2344 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2345 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2346 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2347 + " because its policy is " + uidPoliciesToString(policy));
2348 continue;
2349 }
2350 if (UserHandle.isApp(uid)) {
2351 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2352 if (LOGV)
2353 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2354 setUidPolicyUncheckedUL(uid, newPolicy, false);
2355 } else {
2356 Slog.w(TAG, "unable to update policy on UID " + uid);
2357 }
2358 }
2359
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002360 } catch (FileNotFoundException e) {
2361 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002362 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002363 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002364 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 } finally {
2366 IoUtils.closeQuietly(fis);
2367 }
2368 }
2369
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002370 /**
2371 * Upgrade legacy background data flags, notifying listeners of one last
2372 * change to always-true.
2373 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002374 private void upgradeDefaultBackgroundDataUL() {
2375 // This method is only called when we're unable to find the network policy flag, which
2376 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002377
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002378 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002379 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002380 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2381
2382 // NOTE: We used to read the legacy setting here :
2383 //
2384 // final int legacyFlagValue = Settings.Secure.getInt(
2385 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2386 //
2387 // This is no longer necessary because we will never upgrade directly from Gingerbread
2388 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2389 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002390 }
2391
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002392 /**
2393 * Perform upgrade step of moving any user-defined meterness overrides over
2394 * into {@link WifiConfiguration}.
2395 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002396 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002397 private void upgradeWifiMeteredOverrideAL() {
2398 boolean modified = false;
2399 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2400 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2401 for (int i = 0; i < mNetworkPolicy.size(); ) {
2402 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2403 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2404 && !policy.inferred) {
2405 mNetworkPolicy.removeAt(i);
2406 modified = true;
2407
2408 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2409 for (WifiConfiguration config : configs) {
2410 if (Objects.equals(resolveNetworkId(config), networkId)) {
2411 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2412 config.meteredOverride = policy.metered
2413 ? WifiConfiguration.METERED_OVERRIDE_METERED
2414 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2415 wm.updateNetwork(config);
2416 }
2417 }
2418 } else {
2419 i++;
2420 }
2421 }
2422 if (modified) {
2423 writePolicyAL();
2424 }
2425 }
2426
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002427 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002428 void writePolicyAL() {
2429 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002430
2431 FileOutputStream fos = null;
2432 try {
2433 fos = mPolicyFile.startWrite();
2434
2435 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002436 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002437 out.startDocument(null, true);
2438
2439 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002440 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002441 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002442
2443 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002444 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2445 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002446 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002447 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002448
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002449 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002450 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2451 final String subscriberId = template.getSubscriberId();
2452 if (subscriberId != null) {
2453 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002454 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002455 final String networkId = template.getNetworkId();
2456 if (networkId != null) {
2457 out.attribute(null, ATTR_NETWORK_ID, networkId);
2458 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002459 writeStringAttribute(out, ATTR_CYCLE_START,
2460 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2461 writeStringAttribute(out, ATTR_CYCLE_END,
2462 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2463 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2464 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002465 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2466 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002467 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2468 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002469 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002470 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002471 out.endTag(null, TAG_NETWORK_POLICY);
2472 }
2473
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002474 // write all known subscription plans
2475 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2476 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002477 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002478 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2479 if (ArrayUtils.isEmpty(plans)) continue;
2480
2481 for (SubscriptionPlan plan : plans) {
2482 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2483 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002484 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002485 final RecurrenceRule cycleRule = plan.getCycleRule();
2486 writeStringAttribute(out, ATTR_CYCLE_START,
2487 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2488 writeStringAttribute(out, ATTR_CYCLE_END,
2489 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2490 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2491 RecurrenceRule.convertPeriod(cycleRule.period));
2492 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2493 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2494 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2495 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2496 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2497 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2498 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2499 }
2500 }
2501
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002502 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002503 for (int i = 0; i < mUidPolicy.size(); i++) {
2504 final int uid = mUidPolicy.keyAt(i);
2505 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002506
Jeff Sharkey497e4432011-06-14 17:27:29 -07002507 // skip writing empty policies
2508 if (policy == POLICY_NONE) continue;
2509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002510 out.startTag(null, TAG_UID_POLICY);
2511 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002512 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002513 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002514 }
2515
2516 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002517
2518 // write all whitelists
2519 out.startTag(null, TAG_WHITELIST);
2520
Felipe Lemea9505cc2016-02-26 10:28:41 -08002521 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002522 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002523 for (int i = 0; i < size; i++) {
2524 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2525 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2526 writeIntAttribute(out, ATTR_UID, uid);
2527 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2528 }
2529
Felipe Lemeb85a6372016-01-14 16:16:16 -08002530 out.endTag(null, TAG_WHITELIST);
2531
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002532 out.endDocument();
2533
2534 mPolicyFile.finishWrite(fos);
2535 } catch (IOException e) {
2536 if (fos != null) {
2537 mPolicyFile.failWrite(fos);
2538 }
2539 }
2540 }
2541
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002542 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002543 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002544 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002545
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002546 if (!UserHandle.isApp(uid)) {
2547 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002548 }
Felipe Lemef0823852016-06-08 13:43:08 -07002549 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002550 final long token = Binder.clearCallingIdentity();
2551 try {
2552 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2553 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002554 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002555 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002556 }
2557 } finally {
2558 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002559 }
2560 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002561 }
2562
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002563 @Override
2564 public void addUidPolicy(int uid, int policy) {
2565 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002566
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002567 if (!UserHandle.isApp(uid)) {
2568 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2569 }
2570
Felipe Lemef0823852016-06-08 13:43:08 -07002571 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002572 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2573 policy |= oldPolicy;
2574 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002575 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002576 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002577 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002578 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002579 }
2580
2581 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002582 public void removeUidPolicy(int uid, int policy) {
2583 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2584
2585 if (!UserHandle.isApp(uid)) {
2586 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2587 }
2588
Felipe Lemef0823852016-06-08 13:43:08 -07002589 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002590 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2591 policy = oldPolicy & ~policy;
2592 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002593 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002594 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002595 }
2596 }
2597 }
2598
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002599 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002600 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002601 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002602
Felipe Leme57e3d312016-08-23 14:42:52 -07002603 final boolean notifyApp;
2604 if (!isUidValidForWhitelistRules(uid)) {
2605 notifyApp = false;
2606 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002607 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2608 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2609 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2610 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002611 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2612 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002613 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2614 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2615 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2616 if (LOGD)
2617 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2618 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2619 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002620 notifyApp = wasBlocked != isBlocked;
2621 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002622 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2623 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002624 if (persist) {
2625 synchronized (mNetworkPoliciesSecondLock) {
2626 writePolicyAL();
2627 }
2628 }
Felipe Leme923845f2016-03-02 13:42:48 -08002629 }
2630
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002631 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002632 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002633 if (policy == POLICY_NONE) {
2634 mUidPolicy.delete(uid);
2635 } else {
2636 mUidPolicy.put(uid, policy);
2637 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002638
2639 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002640 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002641 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002642 synchronized (mNetworkPoliciesSecondLock) {
2643 writePolicyAL();
2644 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002645 }
2646 }
2647
2648 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002649 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002650 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2651
Felipe Lemef0823852016-06-08 13:43:08 -07002652 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002653 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002654 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002655 }
2656
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002657 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002658 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002659 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2660
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002661 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002662 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002663 for (int i = 0; i < mUidPolicy.size(); i++) {
2664 final int uid = mUidPolicy.keyAt(i);
2665 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002666 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2667 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002668 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002669 }
2670 }
2671 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002672 return uids;
2673 }
2674
2675 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002676 * Removes any persistable state associated with given {@link UserHandle}, persisting
2677 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002678 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002679 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002680 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002681
Sudheer Shanka352dc572017-09-22 17:09:38 -07002682 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002683 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002684
Felipe Lemea110eec2016-04-29 09:58:06 -07002685 // Remove entries from revoked default restricted background UID whitelist
2686 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2687 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2688 if (UserHandle.getUserId(uid) == userId) {
2689 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002690 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002691 }
2692 }
2693
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002694 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002695 int[] uids = new int[0];
2696 for (int i = 0; i < mUidPolicy.size(); i++) {
2697 final int uid = mUidPolicy.keyAt(i);
2698 if (UserHandle.getUserId(uid) == userId) {
2699 uids = appendInt(uids, uid);
2700 }
2701 }
2702
2703 if (uids.length > 0) {
2704 for (int uid : uids) {
2705 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002706 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002707 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002708 }
Felipe Lemef0823852016-06-08 13:43:08 -07002709 synchronized (mNetworkPoliciesSecondLock) {
2710 updateRulesForGlobalChangeAL(true);
2711 if (writePolicy && changed) {
2712 writePolicyAL();
2713 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002714 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002715 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002716 }
2717
2718 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002719 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002720 // TODO: create permission for observing network policy
2721 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002722 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002723 }
2724
2725 @Override
2726 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002727 // TODO: create permission for observing network policy
2728 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002729 mListeners.unregister(listener);
2730 }
2731
Jeff Sharkey1b861272011-05-22 00:34:52 -07002732 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002733 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002734 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2735
Felipe Leme6a05eee2016-02-19 14:43:51 -08002736 final long token = Binder.clearCallingIdentity();
2737 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002738 synchronized (mUidRulesFirstLock) {
2739 synchronized (mNetworkPoliciesSecondLock) {
2740 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002741 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002742 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002743 }
2744 } finally {
2745 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002746 }
2747 }
2748
Hugo Benichi446c9c92017-04-10 09:41:10 +09002749 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002750 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002751 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2752 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002753 }
2754
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002755 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002756 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002757 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002758 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002759 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2760 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2761 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002762 } catch (SecurityException e) {
2763 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002764
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002765 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2766 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2767 return new NetworkPolicy[0];
2768 }
Svet Ganov16a16892015-04-16 10:32:04 -07002769 }
2770
Felipe Lemef0823852016-06-08 13:43:08 -07002771 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002772 final int size = mNetworkPolicy.size();
2773 final NetworkPolicy[] policies = new NetworkPolicy[size];
2774 for (int i = 0; i < size; i++) {
2775 policies[i] = mNetworkPolicy.valueAt(i);
2776 }
2777 return policies;
2778 }
2779 }
2780
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002781 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002782 private void normalizePoliciesNL() {
2783 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002784 }
2785
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002786 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002787 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002788 mNetworkPolicy.clear();
2789 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002790 if (policy == null) {
2791 continue;
2792 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002793 // When two normalized templates conflict, prefer the most
2794 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002795 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002796 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2797 if (existing == null || existing.compareTo(policy) > 0) {
2798 if (existing != null) {
2799 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2800 }
2801 mNetworkPolicy.put(policy.template, policy);
2802 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002803 }
2804 }
2805
2806 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002807 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002808 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002809
2810 final long token = Binder.clearCallingIdentity();
2811 try {
2812 performSnooze(template, TYPE_LIMIT);
2813 } finally {
2814 Binder.restoreCallingIdentity(token);
2815 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002816 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002817
Dianne Hackborn497175b2014-07-01 12:56:08 -07002818 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002819 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002820 synchronized (mUidRulesFirstLock) {
2821 synchronized (mNetworkPoliciesSecondLock) {
2822 // find and snooze local policy that matches
2823 final NetworkPolicy policy = mNetworkPolicy.get(template);
2824 if (policy == null) {
2825 throw new IllegalArgumentException("unable to find policy for " + template);
2826 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002827
Felipe Lemef0823852016-06-08 13:43:08 -07002828 switch (type) {
2829 case TYPE_WARNING:
2830 policy.lastWarningSnooze = currentTime;
2831 break;
2832 case TYPE_LIMIT:
2833 policy.lastLimitSnooze = currentTime;
2834 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002835 case TYPE_RAPID:
2836 policy.lastRapidSnooze = currentTime;
2837 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002838 default:
2839 throw new IllegalArgumentException("unexpected type");
2840 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002841
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002842 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002843 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002844 }
2845 }
2846
2847 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002848 public void onTetheringChanged(String iface, boolean tethering) {
2849 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002850 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002851 if (mRestrictBackground && tethering) {
2852 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2853 setRestrictBackground(false);
2854 }
2855 }
2856 }
2857
2858 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002859 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002860 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002861 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002862 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2863 final long token = Binder.clearCallingIdentity();
2864 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002865 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002866 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002867 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002868 } finally {
2869 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002870 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002871 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002872 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002873 }
2874 }
2875
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002876 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002877 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002878 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002879 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002880 if (restrictBackground == mRestrictBackground) {
2881 // Ideally, UI should never allow this scenario...
2882 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002883 return;
2884 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002885 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2886 final boolean oldRestrictBackground = mRestrictBackground;
2887 mRestrictBackground = restrictBackground;
2888 // Must whitelist foreground apps before turning data saver mode on.
2889 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2890 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2891 updateRulesForRestrictBackgroundUL();
2892 try {
2893 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2894 Slog.e(TAG,
2895 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2896 mRestrictBackground = oldRestrictBackground;
2897 // TODO: if it knew the foreground apps (see TODO above), it could call
2898 // updateRulesForRestrictBackgroundUL() again to restore state.
2899 return;
2900 }
2901 } catch (RemoteException e) {
2902 // ignored; service lives in system_server
2903 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002904
Sudheer Shanka543339f2017-07-28 15:18:07 -07002905 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002906 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002907
Kweku Adams25fa3a72019-07-12 17:00:17 -07002908 if (mRestrictBackgroundLowPowerMode) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002909 mRestrictBackgroundChangedInBsm = true;
2910 }
2911 synchronized (mNetworkPoliciesSecondLock) {
2912 updateNotificationsNL();
2913 writePolicyAL();
2914 }
2915 } finally {
2916 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002917 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002918 }
2919
2920 private void sendRestrictBackgroundChangedMsg() {
2921 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2922 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2923 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002924 }
2925
Felipe Lemeb85a6372016-01-14 16:16:16 -08002926 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002927 public int getRestrictBackgroundByCaller() {
2928 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2929 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002930
Felipe Lemef0823852016-06-08 13:43:08 -07002931 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002932 // Must clear identity because getUidPolicy() is restricted to system.
2933 final long token = Binder.clearCallingIdentity();
2934 final int policy;
2935 try {
2936 policy = getUidPolicy(uid);
2937 } finally {
2938 Binder.restoreCallingIdentity(token);
2939 }
2940 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2941 // App is blacklisted.
2942 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2943 }
Felipe Leme1b103232016-01-22 09:44:57 -08002944 if (!mRestrictBackground) {
2945 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2946 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002947 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002948 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2949 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2950 }
2951 }
2952
2953 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002954 public boolean getRestrictBackground() {
2955 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2956
Felipe Lemef0823852016-06-08 13:43:08 -07002957 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002958 return mRestrictBackground;
2959 }
2960 }
2961
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002962 @Override
2963 public void setDeviceIdleMode(boolean enabled) {
2964 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002965 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2966 try {
2967 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002968 if (mDeviceIdleMode == enabled) {
2969 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002970 }
Felipe Lemeea014392016-09-06 13:59:54 -07002971 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002972 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002973 if (mSystemReady) {
2974 // Device idle change means we need to rebuild rules for all
2975 // known apps, so do a global refresh.
2976 updateRulesForRestrictPowerUL();
2977 }
2978 }
2979 if (enabled) {
2980 EventLogTags.writeDeviceIdleOnPhase("net");
2981 } else {
2982 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002983 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002984 } finally {
2985 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002986 }
2987 }
2988
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002989 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002990 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2991 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002992 final long token = Binder.clearCallingIdentity();
2993 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002994 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2995 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2996 for (WifiConfiguration config : configs) {
2997 if (Objects.equals(resolveNetworkId(config), networkId)) {
2998 config.meteredOverride = meteredOverride;
2999 wm.updateNetwork(config);
3000 }
3001 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07003002 } finally {
3003 Binder.restoreCallingIdentity(token);
3004 }
3005 }
3006
Jeff Sharkey46645002011-07-27 21:11:21 -07003007 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003008 @Deprecated
3009 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
3010 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
3011 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
3012 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07003013 }
3014
Jeff Sharkey53313d72017-07-13 16:47:32 -06003015 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
3016 // Verify they're not lying about package name
3017 mAppOps.checkPackage(callingUid, callingPackage);
3018
Jeff Sharkey53313d72017-07-13 16:47:32 -06003019 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003020 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003021 final long token = Binder.clearCallingIdentity();
3022 try {
3023 si = mContext.getSystemService(SubscriptionManager.class)
3024 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003025 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003026 } finally {
3027 Binder.restoreCallingIdentity(token);
3028 }
3029
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003030 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003031 if (si != null) {
3032 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
3033 return;
3034 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003035 }
3036
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003037 // Second check: has the CarrierService delegated access?
3038 if (config != null) {
3039 final String overridePackage = config
3040 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3041 if (!TextUtils.isEmpty(overridePackage)
3042 && Objects.equals(overridePackage, callingPackage)) {
3043 return;
3044 }
3045 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003046
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003047 // Third check: is caller the fallback/default CarrierService?
3048 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3049 if (!TextUtils.isEmpty(defaultPackage)
3050 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003051 return;
3052 }
3053
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003054 // Fourth check: is caller a testing app?
3055 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3056 if (!TextUtils.isEmpty(testPackage)
3057 && Objects.equals(testPackage, callingPackage)) {
3058 return;
3059 }
3060
3061 // Fifth check: is caller a legacy testing app?
3062 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3063 if (!TextUtils.isEmpty(legacyTestPackage)
3064 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003065 return;
3066 }
3067
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003068 // Final check: does the caller hold a permission?
3069 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003070 }
3071
3072 @Override
3073 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3074 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3075
Jeff Sharkey53313d72017-07-13 16:47:32 -06003076 final String fake = SystemProperties.get("fw.fake_plan");
3077 if (!TextUtils.isEmpty(fake)) {
3078 final List<SubscriptionPlan> plans = new ArrayList<>();
3079 if ("month_hard".equals(fake)) {
3080 plans.add(SubscriptionPlan.Builder
3081 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3082 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003083 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3084 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3085 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3086 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3087 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003088 plans.add(SubscriptionPlan.Builder
3089 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3090 .setTitle("G-Mobile Happy")
3091 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3092 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3093 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3094 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3095 .build());
3096 plans.add(SubscriptionPlan.Builder
3097 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3098 .setTitle("G-Mobile, Charged after limit")
3099 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3100 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3101 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3102 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3103 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003104 } else if ("month_soft".equals(fake)) {
3105 plans.add(SubscriptionPlan.Builder
3106 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3107 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3108 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3109 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003110 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3111 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3112 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3113 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3114 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003115 plans.add(SubscriptionPlan.Builder
3116 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3117 .setTitle("G-Mobile, Throttled after limit")
3118 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3119 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3120 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3121 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3122 .build());
3123 plans.add(SubscriptionPlan.Builder
3124 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3125 .setTitle("G-Mobile, No data connection after limit")
3126 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3127 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3128 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3129 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3130 .build());
3131
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003132 } else if ("month_over".equals(fake)) {
3133 plans.add(SubscriptionPlan.Builder
3134 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3135 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3136 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3137 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3138 .setDataUsage(6 * 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, Throttled after limit")
3144 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3145 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3146 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3147 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3148 .build());
3149 plans.add(SubscriptionPlan.Builder
3150 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3151 .setTitle("G-Mobile, No data connection after limit")
3152 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3153 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3154 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3155 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3156 .build());
3157
Jeff Sharkey53313d72017-07-13 16:47:32 -06003158 } else if ("month_none".equals(fake)) {
3159 plans.add(SubscriptionPlan.Builder
3160 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3161 .setTitle("G-Mobile")
3162 .build());
3163 } else if ("prepaid".equals(fake)) {
3164 plans.add(SubscriptionPlan.Builder
3165 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3166 ZonedDateTime.now().plusDays(10))
3167 .setTitle("G-Mobile")
3168 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3169 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3170 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3171 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3172 .build());
3173 } else if ("prepaid_crazy".equals(fake)) {
3174 plans.add(SubscriptionPlan.Builder
3175 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3176 ZonedDateTime.now().plusDays(10))
3177 .setTitle("G-Mobile Anytime")
3178 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3179 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3180 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3181 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3182 .build());
3183 plans.add(SubscriptionPlan.Builder
3184 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3185 ZonedDateTime.now().plusDays(20))
3186 .setTitle("G-Mobile Nickel Nights")
3187 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003188 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3189 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003190 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3191 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3192 .build());
3193 plans.add(SubscriptionPlan.Builder
3194 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3195 ZonedDateTime.now().plusDays(20))
3196 .setTitle("G-Mobile Bonus 3G")
3197 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003198 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003199 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3200 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3201 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3202 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003203 } else if ("unlimited".equals(fake)) {
3204 plans.add(SubscriptionPlan.Builder
3205 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3206 ZonedDateTime.now().plusDays(10))
3207 .setTitle("G-Mobile Awesome")
3208 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3209 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3210 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3211 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3212 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003213 }
3214 return plans.toArray(new SubscriptionPlan[plans.size()]);
3215 }
3216
Jeff Sharkey4635f102017-09-01 11:27:13 -06003217 synchronized (mNetworkPoliciesSecondLock) {
3218 // Only give out plan details to the package that defined them,
3219 // so that we don't risk leaking plans between apps. We always
3220 // let in core system components (like the Settings app).
3221 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3222 if (Objects.equals(ownerPackage, callingPackage)
3223 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3224 return mSubscriptionPlans.get(subId);
3225 } else {
3226 Log.w(TAG, "Not returning plans because caller " + callingPackage
3227 + " doesn't match owner " + ownerPackage);
3228 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003229 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003230 }
3231 }
3232
3233 @Override
3234 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3235 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3236
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003237 for (SubscriptionPlan plan : plans) {
3238 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003239 }
3240
3241 final long token = Binder.clearCallingIdentity();
3242 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003243 synchronized (mUidRulesFirstLock) {
3244 synchronized (mNetworkPoliciesSecondLock) {
3245 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003246 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003247
Jeff Sharkey146bb332018-04-18 15:42:57 -06003248 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3249 if (subscriberId != null) {
3250 ensureActiveMobilePolicyAL(subId, subscriberId);
3251 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3252 } else {
3253 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3254 }
3255
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003256 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003257 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003258 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003259
3260 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3261 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3262 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3263 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003264 } finally {
3265 Binder.restoreCallingIdentity(token);
3266 }
3267 }
3268
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003269 /**
3270 * Only visible for testing purposes. This doesn't give any access to
3271 * existing plans; it simply lets the debug package define new plans.
3272 */
3273 void setSubscriptionPlansOwner(int subId, String packageName) {
3274 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3275 }
3276
Jeff Sharkey53313d72017-07-13 16:47:32 -06003277 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003278 public String getSubscriptionPlansOwner(int subId) {
3279 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3280 throw new SecurityException();
3281 }
3282
3283 synchronized (mNetworkPoliciesSecondLock) {
3284 return mSubscriptionPlansOwner.get(subId);
3285 }
3286 }
3287
3288 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003289 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
Sarah Chin92860a702019-08-19 18:08:21 -07003290 long networkTypeMask, long timeoutMillis, String callingPackage) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003291 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3292
3293 // We can only override when carrier told us about plans
3294 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003295 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3296 if (plan == null
3297 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003298 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003299 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003300 }
3301 }
3302
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003303 // Only allow overrides when feature is enabled. However, we always
3304 // allow disabling of overrides for safety reasons.
3305 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3306 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3307 if (overrideEnabled || overrideValue == 0) {
Sarah Chin92860a702019-08-19 18:08:21 -07003308 SomeArgs args = SomeArgs.obtain();
3309 args.arg1 = subId;
3310 args.arg2 = overrideMask;
3311 args.arg3 = overrideValue;
3312 args.arg4 = networkTypeMask;
3313 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE, args));
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003314 if (timeoutMillis > 0) {
Sarah Chin92860a702019-08-19 18:08:21 -07003315 args.arg3 = 0;
3316 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE, args),
3317 timeoutMillis);
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003318 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003319 }
3320 }
3321
3322 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003323 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003324 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003325
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003326 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3327
Dianne Hackborn497175b2014-07-01 12:56:08 -07003328 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003329 for (String arg : args) {
3330 argSet.add(arg);
3331 }
3332
Felipe Lemef0823852016-06-08 13:43:08 -07003333 synchronized (mUidRulesFirstLock) {
3334 synchronized (mNetworkPoliciesSecondLock) {
3335 if (argSet.contains("--unsnooze")) {
3336 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3337 mNetworkPolicy.valueAt(i).clearSnooze();
3338 }
3339
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003340 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003341
3342 fout.println("Cleared snooze timestamps");
3343 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003344 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003345
Felipe Lemef0823852016-06-08 13:43:08 -07003346 fout.print("System ready: "); fout.println(mSystemReady);
3347 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3348 fout.print("Restrict power: "); fout.println(mRestrictPower);
3349 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003350 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3351
3352 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003353 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003354 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003355 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3356 fout.println(mNetworkPolicy.valueAt(i).toString());
3357 }
3358 fout.decreaseIndent();
3359
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003360 fout.println();
3361 fout.println("Subscription plans:");
3362 fout.increaseIndent();
3363 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3364 final int subId = mSubscriptionPlans.keyAt(i);
3365 fout.println("Subscriber ID " + subId + ":");
3366 fout.increaseIndent();
3367 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3368 if (!ArrayUtils.isEmpty(plans)) {
3369 for (SubscriptionPlan plan : plans) {
3370 fout.println(plan);
3371 }
3372 }
3373 fout.decreaseIndent();
3374 }
3375 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003376
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003377 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003378 fout.println("Active subscriptions:");
3379 fout.increaseIndent();
3380 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3381 final int subId = mSubIdToSubscriberId.keyAt(i);
3382 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3383
3384 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3385 }
3386 fout.decreaseIndent();
3387
3388 fout.println();
Malcolm Chen07fcb5b2019-07-02 22:29:35 -07003389 for (String[] mergedSubscribers : mMergedSubscriberIds) {
3390 fout.println("Merged subscriptions: " + Arrays.toString(
3391 NetworkIdentity.scrubSubscriberId(mergedSubscribers)));
3392 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06003393
3394 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003395 fout.println("Policy for UIDs:");
3396 fout.increaseIndent();
3397 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003398 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003399 final int uid = mUidPolicy.keyAt(i);
3400 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003401 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003402 fout.print(uid);
3403 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003404 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003405 fout.println();
3406 }
3407 fout.decreaseIndent();
3408
3409 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3410 if (size > 0) {
3411 fout.println("Power save whitelist (except idle) app ids:");
3412 fout.increaseIndent();
3413 for (int i = 0; i < size; i++) {
3414 fout.print("UID=");
3415 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3416 fout.print(": ");
3417 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3418 fout.println();
3419 }
3420 fout.decreaseIndent();
3421 }
3422
3423 size = mPowerSaveWhitelistAppIds.size();
3424 if (size > 0) {
3425 fout.println("Power save whitelist app ids:");
3426 fout.increaseIndent();
3427 for (int i = 0; i < size; i++) {
3428 fout.print("UID=");
3429 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3430 fout.print(": ");
3431 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3432 fout.println();
3433 }
3434 fout.decreaseIndent();
3435 }
3436
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003437 size = mAppIdleTempWhitelistAppIds.size();
3438 if (size > 0) {
3439 fout.println("App idle whitelist app ids:");
3440 fout.increaseIndent();
3441 for (int i = 0; i < size; i++) {
3442 fout.print("UID=");
3443 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3444 fout.print(": ");
3445 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3446 fout.println();
3447 }
3448 fout.decreaseIndent();
3449 }
3450
Felipe Lemef0823852016-06-08 13:43:08 -07003451 size = mDefaultRestrictBackgroundWhitelistUids.size();
3452 if (size > 0) {
3453 fout.println("Default restrict background whitelist uids:");
3454 fout.increaseIndent();
3455 for (int i = 0; i < size; i++) {
3456 fout.print("UID=");
3457 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3458 fout.println();
3459 }
3460 fout.decreaseIndent();
3461 }
3462
3463 size = mRestrictBackgroundWhitelistRevokedUids.size();
3464 if (size > 0) {
3465 fout.println("Default restrict background whitelist uids revoked by users:");
3466 fout.increaseIndent();
3467 for (int i = 0; i < size; i++) {
3468 fout.print("UID=");
3469 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3470 fout.println();
3471 }
3472 fout.decreaseIndent();
3473 }
3474
3475 final SparseBooleanArray knownUids = new SparseBooleanArray();
3476 collectKeys(mUidState, knownUids);
3477 collectKeys(mUidRules, knownUids);
3478
3479 fout.println("Status for all known UIDs:");
3480 fout.increaseIndent();
3481 size = knownUids.size();
3482 for (int i = 0; i < size; i++) {
3483 final int uid = knownUids.keyAt(i);
3484 fout.print("UID=");
3485 fout.print(uid);
3486
3487 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3488 fout.print(" state=");
3489 fout.print(state);
3490 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3491 fout.print(" (fg)");
3492 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003493 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003494 ? " (fg svc)" : " (bg)");
3495 }
3496
3497 final int uidRules = mUidRules.get(uid, RULE_NONE);
3498 fout.print(" rules=");
3499 fout.print(uidRulesToString(uidRules));
3500 fout.println();
3501 }
3502 fout.decreaseIndent();
3503
3504 fout.println("Status for just UIDs with rules:");
3505 fout.increaseIndent();
3506 size = mUidRules.size();
3507 for (int i = 0; i < size; i++) {
3508 final int uid = mUidRules.keyAt(i);
3509 fout.print("UID=");
3510 fout.print(uid);
3511 final int uidRules = mUidRules.get(uid, RULE_NONE);
3512 fout.print(" rules=");
3513 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003514 fout.println();
3515 }
3516 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003517
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003518 fout.println("Admin restricted uids for metered data:");
3519 fout.increaseIndent();
3520 size = mMeteredRestrictedUids.size();
3521 for (int i = 0; i < size; ++i) {
3522 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3523 fout.println(mMeteredRestrictedUids.valueAt(i));
3524 }
3525 fout.decreaseIndent();
3526
Makoto Onuki49392d32018-04-11 13:51:02 -07003527 fout.println();
3528 mStatLogger.dump(fout);
3529
Sudheer Shanka352dc572017-09-22 17:09:38 -07003530 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003531 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003532 }
3533 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003534
3535 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003536 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003537 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003538 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003539 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003540 }
3541
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003542 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003543 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003544 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003545 return isUidStateForeground(
3546 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003547 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003548 }
3549
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003550 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003551 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003552 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003553 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003554 }
3555
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003556 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003557 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003558 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3559 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3560 }
3561
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003562 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003563 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003564 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003565 }
3566
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003567 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003568 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003569 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003570 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003571 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003572 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003573 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003574 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3575 try {
3576 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3577 if (oldUidState != uidState) {
3578 // state changed, push updated rules
3579 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003580 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3581 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3582 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003583 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003584 if (mDeviceIdleMode) {
3585 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003586 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003587 if (mRestrictPower) {
3588 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003589 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003590 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003591 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003592 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003593 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003594 } finally {
3595 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003596 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003597 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003598 }
3599
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003600 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003601 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003602 final int index = mUidState.indexOfKey(uid);
3603 if (index >= 0) {
3604 final int oldUidState = mUidState.valueAt(index);
3605 mUidState.removeAt(index);
3606 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003607 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003608 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003609 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003610 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003611 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003612 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003613 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003614 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003615 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003616 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003617 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003618 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003619 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003620 }
3621
Felipe Lemef28983d2016-03-25 12:18:23 -07003622 // adjust stats accounting based on foreground status
3623 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003624 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3625 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3626 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3627 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003628 try {
3629 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003630 } finally {
3631 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003632 }
3633 }
3634
Sudheer Shankac9d94072017-02-22 22:13:55 +00003635 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3636 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003637 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003638 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003639 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003640 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003641 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003642 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003643 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003644 }
3645
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003646 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003647 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003648 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3649 try {
3650 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3651 mUidFirewallPowerSaveRules);
3652 } finally {
3653 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3654 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003655 }
3656
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003657 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003658 void updateRuleForRestrictPowerUL(int uid) {
3659 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003660 }
3661
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003662 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003663 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003664 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3665 try {
3666 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3667 mUidFirewallDozableRules);
3668 } finally {
3669 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3670 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003671 }
3672
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003673 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003674 void updateRuleForDeviceIdleUL(int uid) {
3675 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003676 }
3677
Felipe Lemef28983d2016-03-25 12:18:23 -07003678 // NOTE: since both fw_dozable and fw_powersave uses the same map
3679 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003680 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003681 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003682 SparseIntArray rules) {
3683 if (enabled) {
3684 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003685 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003686 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003687 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003688 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003689 for (int ui = users.size() - 1; ui >= 0; ui--) {
3690 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003691 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3692 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3693 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3694 updateRulesForWhitelistedAppIds(uidRules,
3695 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003696 }
3697 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003698 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003699 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003700 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3701 }
3702 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003703 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003704 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003705 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003706 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003707 }
3708
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003709 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3710 final SparseBooleanArray whitelistedAppIds, int userId) {
3711 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3712 if (whitelistedAppIds.valueAt(i)) {
3713 final int appId = whitelistedAppIds.keyAt(i);
3714 final int uid = UserHandle.getUid(userId, appId);
3715 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3716 }
3717 }
3718 }
3719
3720 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003721 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3722 * mode, and app idle).
3723 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003724 * @param deviceIdleMode if true then we don't consider
3725 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3726 * whitelisted.
3727 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003728 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003729 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003730 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003731 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3732 || mPowerSaveWhitelistAppIds.get(appId);
3733 if (!deviceIdleMode) {
3734 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3735 }
3736 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003737 }
3738
Felipe Lemef28983d2016-03-25 12:18:23 -07003739 // NOTE: since both fw_dozable and fw_powersave uses the same map
3740 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003741 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003742 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003743 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003744 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003745 chain == FIREWALL_CHAIN_DOZABLE);
3746 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003747 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003748 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003749 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003750 }
3751 }
3752 }
3753
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003754 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003755 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003756 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3757 try {
3758 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3759 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003760
Felipe Leme873a83a2016-09-07 11:34:10 -07003761 // Fully update the app idle firewall chain.
3762 final List<UserInfo> users = mUserManager.getUsers();
3763 for (int ui = users.size() - 1; ui >= 0; ui--) {
3764 UserInfo user = users.get(ui);
3765 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3766 for (int uid : idleUids) {
3767 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3768 // quick check: if this uid doesn't have INTERNET permission, it
3769 // doesn't have network access anyway, so it is a waste to mess
3770 // with it here.
3771 if (hasInternetPermissions(uid)) {
3772 uidRules.put(uid, FIREWALL_RULE_DENY);
3773 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003774 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003775 }
3776 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003777
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003778 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003779 } finally {
3780 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3781 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003782 }
3783
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003784 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003785 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003786 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003787
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003788 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3789 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3790 }
3791 try {
3792 int appId = UserHandle.getAppId(uid);
3793 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3794 && !isUidForegroundOnRestrictPowerUL(uid)) {
3795 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003796 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003797 } else {
3798 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003799 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003800 }
3801 } finally {
3802 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003803 }
3804 }
3805
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003806 /**
3807 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3808 * changed.
3809 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003810 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003811 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003812 boolean paroled = mUsageStats.isAppIdleParoleOn();
3813 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003814 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003815
3816 int ruleCount = mUidFirewallStandbyRules.size();
3817 for (int i = 0; i < ruleCount; i++) {
3818 int uid = mUidFirewallStandbyRules.keyAt(i);
3819 int oldRules = mUidRules.get(uid);
3820 if (enableChain) {
3821 // Chain wasn't enabled before and the other power-related
3822 // chains are whitelists, so we can clear the
3823 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3824 // the effective rules result in blocking network access.
3825 oldRules &= MASK_METERED_NETWORKS;
3826 } else {
3827 // Skip if it had no restrictions to begin with
3828 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3829 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003830 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3831 if (newUidRules == RULE_NONE) {
3832 mUidRules.delete(uid);
3833 } else {
3834 mUidRules.put(uid, newUidRules);
3835 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003836 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003837 }
3838
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003839 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003840 * Update rules that might be changed by {@link #mRestrictBackground},
3841 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003842 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003843 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003844 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003845 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3846 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3847 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3848 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003849 try {
Felipe Leme09700462016-09-08 09:33:48 -07003850 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003851 updateRulesForRestrictPowerUL();
3852 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003853
Felipe Leme873a83a2016-09-07 11:34:10 -07003854 // If the set of restricted networks may have changed, re-evaluate those.
3855 if (restrictedNetworksChanged) {
3856 normalizePoliciesNL();
3857 updateNetworkRulesNL();
3858 }
3859 } finally {
3860 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003861 }
3862 }
3863
Felipe Leme09700462016-09-08 09:33:48 -07003864 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003865 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003866 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003867 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3868 try {
3869 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003870 updateRulesForPowerSaveUL();
3871 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3872 } finally {
3873 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3874 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003875 }
3876
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003877 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003878 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003879 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3880 try {
3881 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3882 } finally {
3883 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3884 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003885 }
3886
3887 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3888 private static final int TYPE_RESTRICT_POWER = 2;
3889 @Retention(RetentionPolicy.SOURCE)
3890 @IntDef(flag = false, value = {
3891 TYPE_RESTRICT_BACKGROUND,
3892 TYPE_RESTRICT_POWER,
3893 })
3894 public @interface RestrictType {
3895 }
3896
3897 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003898 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003899 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003900 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3901 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3902 }
3903 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003904 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003905
3906 final PackageManager pm = mContext.getPackageManager();
3907 final List<UserInfo> users;
3908 final List<ApplicationInfo> apps;
3909
3910 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3911 try {
3912 users = mUserManager.getUsers();
3913 } finally {
3914 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3915 }
3916 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3917 try {
3918 apps = pm.getInstalledApplications(
3919 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3920 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3921 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3922 } finally {
3923 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3924 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003925
Felipe Leme873a83a2016-09-07 11:34:10 -07003926 final int usersSize = users.size();
3927 final int appsSize = apps.size();
3928 for (int i = 0; i < usersSize; i++) {
3929 final UserInfo user = users.get(i);
3930 for (int j = 0; j < appsSize; j++) {
3931 final ApplicationInfo app = apps.get(j);
3932 final int uid = UserHandle.getUid(user.id, app.uid);
3933 switch (type) {
3934 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003935 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003936 break;
3937 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003938 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003939 break;
3940 default:
3941 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3942 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003943 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003944 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003945 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003946 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003947 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003948 }
3949
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003950 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003951 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003952 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003953 final int numUsers = users.size();
3954 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003955 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003956 int uid = UserHandle.getUid(user.id, appId);
3957 // Update external firewall rules.
3958 updateRuleForAppIdleUL(uid);
3959 updateRuleForDeviceIdleUL(uid);
3960 updateRuleForRestrictPowerUL(uid);
3961 // Update internal rules.
3962 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003963 }
3964 }
3965
Felipe Leme70c57c22016-03-29 10:45:13 -07003966 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3967 // methods below could be merged into a isUidValidForRules() method.
3968 private boolean isUidValidForBlacklistRules(int uid) {
3969 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003970 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003971 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003972 return true;
3973 }
3974
3975 return false;
3976 }
3977
Felipe Leme70c57c22016-03-29 10:45:13 -07003978 private boolean isUidValidForWhitelistRules(int uid) {
3979 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3980 }
3981
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003982 /**
3983 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3984 * power saving restrictions may still apply.
3985 */
3986 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003987 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003988 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3989
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003990 synchronized (mUidRulesFirstLock) {
3991 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3992 // No change.
3993 return;
3994 }
3995
3996 final long token = Binder.clearCallingIdentity();
3997 try {
3998 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3999 if (shouldWhitelist) {
4000 mAppIdleTempWhitelistAppIds.put(uid, true);
4001 } else {
4002 mAppIdleTempWhitelistAppIds.delete(uid);
4003 }
4004 updateRuleForAppIdleUL(uid);
4005 updateRulesForPowerRestrictionsUL(uid);
4006 } finally {
4007 Binder.restoreCallingIdentity(token);
4008 }
4009 }
4010 }
4011
4012 /** Return the list of UIDs currently in the app idle whitelist. */
4013 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004014 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004015 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4016
4017 synchronized (mUidRulesFirstLock) {
4018 final int len = mAppIdleTempWhitelistAppIds.size();
4019 int[] uids = new int[len];
4020 for (int i = 0; i < len; ++i) {
4021 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
4022 }
4023 return uids;
4024 }
4025 }
4026
4027 /** Returns if the UID is currently considered idle. */
4028 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004029 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004030 synchronized (mUidRulesFirstLock) {
4031 if (mAppIdleTempWhitelistAppIds.get(uid)) {
4032 // UID is temporarily whitelisted.
4033 return false;
4034 }
4035 }
4036
Amith Yamasani15e472352015-04-24 19:06:07 -07004037 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
4038 final int userId = UserHandle.getUserId(uid);
4039
songjinshi0655edd2016-05-18 19:55:32 +08004040 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07004041 for (String packageName : packages) {
4042 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4043 return false;
4044 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004045 }
4046 }
4047 return true;
4048 }
4049
4050 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004051 * Checks if an uid has INTERNET permissions.
4052 * <p>
4053 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004054 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004055 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004056 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004057 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004058 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004059 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004060 }
4061 } catch (RemoteException e) {
4062 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004063 return true;
4064 }
4065
4066 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004067 * Clears all state - internal and external - associated with an UID.
4068 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004069 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004070 private void onUidDeletedUL(int uid) {
4071 // First cleanup in-memory state synchronously...
4072 mUidRules.delete(uid);
4073 mUidPolicy.delete(uid);
4074 mUidFirewallStandbyRules.delete(uid);
4075 mUidFirewallDozableRules.delete(uid);
4076 mUidFirewallPowerSaveRules.delete(uid);
4077 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4078 mPowerSaveWhitelistAppIds.delete(uid);
4079 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004080 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004081
4082 // ...then update iptables asynchronously.
4083 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4084 }
4085
4086 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004087 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004088 *
Felipe Leme781ba142016-05-09 16:24:48 -07004089 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004090 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004091 * <li>Doze mode
4092 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004093 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004094 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004095 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004096 *
4097 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004098 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004099 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004100 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004101 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004102 updateRuleForDeviceIdleUL(uid);
4103 updateRuleForAppIdleUL(uid);
4104 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004105
4106 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004107 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004108
4109 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004110 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004111 }
4112
Felipe Leme70c57c22016-03-29 10:45:13 -07004113 /**
4114 * Applies network rules to bandwidth controllers based on process state and user-defined
4115 * restrictions (blacklist / whitelist).
4116 *
4117 * <p>
4118 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4119 * networks:
4120 * <ul>
4121 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4122 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4123 * also blacklisted.
4124 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004125 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004126 * <ul>
4127 *
4128 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4129 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4130 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4131 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004132 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004133 * {@link INetworkManagementService}, but this method should also be called in events (like
4134 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4135 * following rules should also be applied:
4136 *
4137 * <ul>
4138 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4139 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4140 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4141 * {@code bw_penalty_box}.
4142 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4143 * </ul>
4144 *
4145 * <p>For optimization, the rules are only applied on user apps that have internet access
4146 * permission, since there is no need to change the {@code iptables} rule if the app does not
4147 * have permission to use the internet.
4148 *
4149 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004150 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004151 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004152 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004153 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4154 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4155 "updateRulesForDataUsageRestrictionsUL: " + uid);
4156 }
4157 try {
4158 updateRulesForDataUsageRestrictionsULInner(uid);
4159 } finally {
4160 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4161 }
4162 }
4163
4164 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004165 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004166 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004167 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004168 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004169
Dianne Hackborn497175b2014-07-01 12:56:08 -07004170 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004171 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004172 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004173 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004174
Felipe Leme781ba142016-05-09 16:24:48 -07004175 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004176 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004177 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4178 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004179
Felipe Leme70c57c22016-03-29 10:45:13 -07004180 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004181 if (isRestrictedByAdmin) {
4182 newRule = RULE_REJECT_METERED;
4183 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004184 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4185 newRule = RULE_TEMPORARY_ALLOW_METERED;
4186 } else if (isWhitelisted) {
4187 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004188 }
4189 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004190 if (isBlacklisted) {
4191 newRule = RULE_REJECT_METERED;
4192 } else if (mRestrictBackground && isWhitelisted) {
4193 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004194 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004195 }
Felipe Leme781ba142016-05-09 16:24:48 -07004196 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004197
Felipe Lemef28983d2016-03-25 12:18:23 -07004198 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004199 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004200 + ": isForeground=" +isForeground
4201 + ", isBlacklisted=" + isBlacklisted
4202 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004203 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004204 + ", oldRule=" + uidRulesToString(oldRule)
4205 + ", newRule=" + uidRulesToString(newRule)
4206 + ", newUidRules=" + uidRulesToString(newUidRules)
4207 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004208 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004209
Felipe Leme46c4fc32016-05-04 09:21:43 -07004210 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004211 mUidRules.delete(uid);
4212 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004213 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004214 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004215
Felipe Leme70c57c22016-03-29 10:45:13 -07004216 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004217 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004218 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004219 // Temporarily whitelist foreground app, removing from blacklist if necessary
4220 // (since bw_penalty_box prevails over bw_happy_box).
4221
4222 setMeteredNetworkWhitelist(uid, true);
4223 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4224 // but ideally it should be just:
4225 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004226 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004227 setMeteredNetworkBlacklist(uid, false);
4228 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004229 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004230 // Remove temporary whitelist from app that is not on foreground anymore.
4231
4232 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4233 // but ideally they should be just:
4234 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4235 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004236 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004237 setMeteredNetworkWhitelist(uid, false);
4238 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004239 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004240 setMeteredNetworkBlacklist(uid, true);
4241 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004242 } else if (hasRule(newRule, RULE_REJECT_METERED)
4243 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004244 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004245 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004246 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004247 // Since blacklist prevails over whitelist, we need to handle the special case
4248 // where app is whitelisted and blacklisted at the same time (although such
4249 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004250 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004251 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004252 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4253 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004254 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004255 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004256 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004257 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004258 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4259 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004260 + ", whitelisted=" + isWhitelisted
4261 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004262 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004263 + ", newRule=" + uidRulesToString(newUidRules)
4264 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004265 }
Felipe Leme781ba142016-05-09 16:24:48 -07004266
Sudheer Shankac9d94072017-02-22 22:13:55 +00004267 // Dispatch changed rule to existing listeners.
4268 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004269 }
4270 }
4271
4272 /**
4273 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4274 * listeners in case of change.
4275 * <p>
4276 * There are 3 power-related rules that affects whether an app has background access on
4277 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4278 * restriction, it's added to the equivalent firewall chain:
4279 * <ul>
4280 * <li>App is idle: {@code fw_standby} firewall chain.
4281 * <li>Device is idle: {@code fw_dozable} firewall chain.
4282 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4283 * </ul>
4284 * <p>
4285 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4286 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4287 * <p>
4288 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4289 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004290 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004291 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004292 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4293
Sudheer Shankac9d94072017-02-22 22:13:55 +00004294 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004295
Sudheer Shankac9d94072017-02-22 22:13:55 +00004296 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004297 mUidRules.delete(uid);
4298 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004299 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004300 }
4301 }
4302
4303 /**
4304 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4305 *
4306 * @param uid the uid of the app to update rules for
4307 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4308 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4309 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004310 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004311 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004312 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004313 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4314 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4315 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4316 + (paroled ? "P" : "-"));
4317 }
4318 try {
4319 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4320 } finally {
4321 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4322 }
4323 }
4324
4325 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004326 if (!isUidValidForBlacklistRules(uid)) {
4327 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004328 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004329 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004330
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004331 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004332 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004333 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004334
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004335 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004336 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4337 int newRule = RULE_NONE;
4338
4339 // First step: define the new rule based on user restrictions and foreground state.
4340
4341 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4342 // by considering the foreground and non-foreground states.
4343 if (isForeground) {
4344 if (restrictMode) {
4345 newRule = RULE_ALLOW_ALL;
4346 }
4347 } else if (restrictMode) {
4348 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4349 }
4350
4351 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4352
4353 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004354 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004355 + ", isIdle: " + isIdle
4356 + ", mRestrictPower: " + mRestrictPower
4357 + ", mDeviceIdleMode: " + mDeviceIdleMode
4358 + ", isForeground=" + isForeground
4359 + ", isWhitelisted=" + isWhitelisted
4360 + ", oldRule=" + uidRulesToString(oldRule)
4361 + ", newRule=" + uidRulesToString(newRule)
4362 + ", newUidRules=" + uidRulesToString(newUidRules)
4363 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4364 }
4365
Felipe Leme781ba142016-05-09 16:24:48 -07004366 // Second step: notify listeners if state changed.
4367 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004368 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004369 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004370 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004371 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4372 } else {
4373 // All scenarios should have been covered above
4374 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4375 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004376 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004377 + ", newRule=" + uidRulesToString(newUidRules)
4378 + ", oldRule=" + uidRulesToString(oldUidRules));
4379 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004380 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004381 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004382
Sudheer Shankac9d94072017-02-22 22:13:55 +00004383 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004384 }
4385
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004386 private class AppIdleStateChangeListener
4387 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4388
4389 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004390 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4391 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004392 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004393 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4394 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004395 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004396 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004397 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004398 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004399 }
4400 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004401 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004402 }
4403
4404 @Override
4405 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004406 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004407 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004408 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004409 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004410 }
4411 }
4412
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004413 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4414 if (listener != null) {
4415 try {
4416 listener.onUidRulesChanged(uid, uidRules);
4417 } catch (RemoteException ignored) {
4418 }
4419 }
4420 }
4421
4422 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4423 String[] meteredIfaces) {
4424 if (listener != null) {
4425 try {
4426 listener.onMeteredIfacesChanged(meteredIfaces);
4427 } catch (RemoteException ignored) {
4428 }
4429 }
4430 }
4431
4432 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4433 boolean restrictBackground) {
4434 if (listener != null) {
4435 try {
4436 listener.onRestrictBackgroundChanged(restrictBackground);
4437 } catch (RemoteException ignored) {
4438 }
4439 }
4440 }
4441
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004442 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4443 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004444 if (listener != null) {
4445 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004446 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004447 } catch (RemoteException ignored) {
4448 }
4449 }
4450 }
4451
Jeff Sharkey9252b342018-01-19 07:58:35 +09004452 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
Sarah Chin92860a702019-08-19 18:08:21 -07004453 int overrideMask, int overrideValue, long networkTypeMask) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09004454 if (listener != null) {
4455 try {
Sarah Chin92860a702019-08-19 18:08:21 -07004456 listener.onSubscriptionOverride(subId, overrideMask, overrideValue,
4457 networkTypeMask);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004458 } catch (RemoteException ignored) {
4459 }
4460 }
4461 }
4462
Makoto Onuki8e777332017-03-28 11:25:47 -07004463 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004464 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004465 public boolean handleMessage(Message msg) {
4466 switch (msg.what) {
4467 case MSG_RULES_CHANGED: {
4468 final int uid = msg.arg1;
4469 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004470 final int length = mListeners.beginBroadcast();
4471 for (int i = 0; i < length; i++) {
4472 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4473 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004474 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004475 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004476 return true;
4477 }
4478 case MSG_METERED_IFACES_CHANGED: {
4479 final String[] meteredIfaces = (String[]) msg.obj;
4480 final int length = mListeners.beginBroadcast();
4481 for (int i = 0; i < length; i++) {
4482 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004483 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004484 }
4485 mListeners.finishBroadcast();
4486 return true;
4487 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004488 case MSG_LIMIT_REACHED: {
4489 final String iface = (String) msg.obj;
4490
Felipe Lemef0823852016-06-08 13:43:08 -07004491 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004492 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004493 // force stats update to make sure we have
4494 // numbers that caused alert to trigger.
4495 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004496
Felipe Lemef0823852016-06-08 13:43:08 -07004497 updateNetworkEnabledNL();
4498 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004499 }
4500 }
4501 return true;
4502 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004503 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4504 final boolean restrictBackground = msg.arg1 != 0;
4505 final int length = mListeners.beginBroadcast();
4506 for (int i = 0; i < length; i++) {
4507 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004508 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004509 }
4510 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004511 final Intent intent =
4512 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4513 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4514 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4515 return true;
4516 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004517 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004518 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004519 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004520 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004521 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004522 final int length = mListeners.beginBroadcast();
4523 for (int i = 0; i < length; i++) {
4524 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004525 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004526 }
4527 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004528 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4529 if (notifyApp.booleanValue()) {
4530 broadcastRestrictBackgroundChanged(uid, notifyApp);
4531 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004532 return true;
4533 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004534 case MSG_ADVISE_PERSIST_THRESHOLD: {
4535 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004536 // make sure stats are recorded frequently enough; we aim
4537 // for 2MB threshold for 2GB/month rules.
4538 final long persistThreshold = lowestRule / 1000;
4539 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004540 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004541 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004542 case MSG_UPDATE_INTERFACE_QUOTA: {
4543 removeInterfaceQuota((String) msg.obj);
4544 // int params need to be stitched back into a long
4545 setInterfaceQuota((String) msg.obj,
4546 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4547 return true;
4548 }
4549 case MSG_REMOVE_INTERFACE_QUOTA: {
4550 removeInterfaceQuota((String) msg.obj);
4551 return true;
4552 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004553 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4554 resetUidFirewallRules(msg.arg1);
4555 return true;
4556 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004557 case MSG_SUBSCRIPTION_OVERRIDE: {
Sarah Chin92860a702019-08-19 18:08:21 -07004558 final SomeArgs args = (SomeArgs) msg.obj;
4559 final int subId = (int) args.arg1;
4560 final int overrideMask = (int) args.arg2;
4561 final int overrideValue = (int) args.arg3;
4562 final long networkTypeMask = (long) args.arg4;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004563 final int length = mListeners.beginBroadcast();
4564 for (int i = 0; i < length; i++) {
4565 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Sarah Chin92860a702019-08-19 18:08:21 -07004566 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue,
4567 networkTypeMask);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004568 }
4569 mListeners.finishBroadcast();
4570 return true;
4571 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004572 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4573 final int userId = msg.arg1;
4574 final Set<String> packageNames = (Set<String>) msg.obj;
4575 setMeteredRestrictedPackagesInternal(packageNames, userId);
4576 return true;
4577 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004578 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4579 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4580 final boolean enabled = msg.arg1 != 0;
4581 setNetworkTemplateEnabledInner(template, enabled);
4582 return true;
4583 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004584 default: {
4585 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004586 }
4587 }
4588 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004589 };
4590
4591 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4592 @Override
4593 public boolean handleMessage(Message msg) {
4594 switch (msg.what) {
4595 case UID_MSG_STATE_CHANGED: {
4596 final int uid = msg.arg1;
4597 final int procState = msg.arg2;
4598 final long procStateSeq = (Long) msg.obj;
4599
4600 handleUidChanged(uid, procState, procStateSeq);
4601 return true;
4602 }
4603 case UID_MSG_GONE: {
4604 final int uid = msg.arg1;
4605 handleUidGone(uid);
4606 return true;
4607 }
4608 default: {
4609 return false;
4610 }
4611 }
4612 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004613 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004614
Makoto Onuki8e777332017-03-28 11:25:47 -07004615 void handleUidChanged(int uid, int procState, long procStateSeq) {
4616 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4617 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004618 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004619 synchronized (mUidRulesFirstLock) {
4620 // We received a uid state change callback, add it to the history so that it
4621 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004622 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004623 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004624 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004625 // Updating the network rules is done, so notify AMS about this.
4626 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4627 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004628 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4629 // called from the handler, so there's no multi-threading issue.
4630 if (updated) {
4631 updateNetworkStats(uid, isUidStateForeground(procState));
4632 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004633 } finally {
4634 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4635 }
4636 }
4637
4638 void handleUidGone(int uid) {
4639 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4640 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004641 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004642 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004643 updated = removeUidStateUL(uid);
4644 }
4645 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4646 // called from the handler, so there's no multi-threading issue.
4647 if (updated) {
4648 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004649 }
4650 } finally {
4651 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4652 }
4653 }
4654
Felipe Leme57e3d312016-08-23 14:42:52 -07004655 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4656 final PackageManager pm = mContext.getPackageManager();
4657 final String[] packages = pm.getPackagesForUid(uid);
4658 if (packages != null) {
4659 final int userId = UserHandle.getUserId(uid);
4660 for (String packageName : packages) {
4661 final Intent intent =
4662 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4663 intent.setPackage(packageName);
4664 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4665 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4666 }
4667 }
4668 }
4669
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004670 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4671 // long quotaBytes split up into two ints to fit in message
4672 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4673 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4674 }
4675
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004676 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004677 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004678 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004679 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004680 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004681 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004682 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004683 }
4684 }
4685
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004686 private void removeInterfaceQuotaAsync(String iface) {
4687 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4688 }
4689
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004690 private void removeInterfaceQuota(String iface) {
4691 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004692 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004693 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004694 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004695 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004696 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004697 }
4698 }
4699
Felipe Leme70c57c22016-03-29 10:45:13 -07004700 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4701 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004702 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004703 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004704 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004705 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4706 } catch (RemoteException e) {
4707 // ignored; service lives in system_server
4708 }
4709 }
4710
4711 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4712 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4713 try {
4714 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4715 } catch (IllegalStateException e) {
4716 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004717 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004718 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004719 }
4720 }
4721
Felipe Lemebc853dd2016-09-08 13:26:55 -07004722 private static final int CHAIN_TOGGLE_NONE = 0;
4723 private static final int CHAIN_TOGGLE_ENABLE = 1;
4724 private static final int CHAIN_TOGGLE_DISABLE = 2;
4725 @Retention(RetentionPolicy.SOURCE)
4726 @IntDef(flag = false, value = {
4727 CHAIN_TOGGLE_NONE,
4728 CHAIN_TOGGLE_ENABLE,
4729 CHAIN_TOGGLE_DISABLE
4730 })
4731 public @interface ChainToggleType {
4732 }
4733
4734 /**
4735 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004736 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004737 *
4738 * @param chain firewall chain.
4739 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4740 * @param toggle whether the chain should be enabled, disabled, or not changed.
4741 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004742 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004743 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004744 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004745 if (uidRules != null) {
4746 setUidFirewallRulesUL(chain, uidRules);
4747 }
4748 if (toggle != CHAIN_TOGGLE_NONE) {
4749 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4750 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004751 }
4752
Amith Yamasani15e472352015-04-24 19:06:07 -07004753 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004754 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4755 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4756 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004757 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004758 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004759 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004760 int size = uidRules.size();
4761 int[] uids = new int[size];
4762 int[] rules = new int[size];
4763 for(int index = size - 1; index >= 0; --index) {
4764 uids[index] = uidRules.keyAt(index);
4765 rules[index] = uidRules.valueAt(index);
4766 }
4767 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004768 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004769 } catch (IllegalStateException e) {
4770 Log.wtf(TAG, "problem setting firewall uid rules", e);
4771 } catch (RemoteException e) {
4772 // ignored; service lives in system_server
4773 }
4774 }
4775
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004776 /**
4777 * Add or remove a uid to the firewall blacklist for all network ifaces.
4778 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004779 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004780 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4781 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4782 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004783 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004784 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004785 if (chain == FIREWALL_CHAIN_DOZABLE) {
4786 mUidFirewallDozableRules.put(uid, rule);
4787 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4788 mUidFirewallStandbyRules.put(uid, rule);
4789 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4790 mUidFirewallPowerSaveRules.put(uid, rule);
4791 }
4792
4793 try {
4794 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004795 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004796 } catch (IllegalStateException e) {
4797 Log.wtf(TAG, "problem setting firewall uid rules", e);
4798 } catch (RemoteException e) {
4799 // ignored; service lives in system_server
4800 }
4801 } finally {
4802 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004803 }
4804 }
4805
4806 /**
4807 * Add or remove a uid to the firewall blacklist for all network ifaces.
4808 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004809 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004810 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004811 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4812 mFirewallChainStates.get(chain) == enable) {
4813 // All is the same, nothing to do.
4814 return;
4815 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004816 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004817 try {
4818 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004819 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004820 } catch (IllegalStateException e) {
4821 Log.wtf(TAG, "problem enable firewall chain", e);
4822 } catch (RemoteException e) {
4823 // ignored; service lives in system_server
4824 }
4825 }
4826
Felipe Leme03e95e22016-09-09 09:25:31 -07004827 /**
4828 * Resets all firewall rules associated with an UID.
4829 */
4830 private void resetUidFirewallRules(int uid) {
4831 try {
4832 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4833 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4834 mNetworkManager
4835 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4836 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4837 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4838 } catch (IllegalStateException e) {
4839 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4840 } catch (RemoteException e) {
4841 // ignored; service lives in system_server
4842 }
4843 }
4844
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004845 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004846 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004847 return getNetworkTotalBytes(template, start, end);
4848 }
4849
4850 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004851 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004852 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004853 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004854 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004855 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004856 }
4857 }
4858
4859 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4860 try {
4861 return mNetworkStats.getNetworkUidBytes(template, start, end);
4862 } catch (RuntimeException e) {
4863 Slog.w(TAG, "Failed to read network stats: " + e);
4864 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004865 }
4866 }
4867
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004868 private boolean isBandwidthControlEnabled() {
4869 final long token = Binder.clearCallingIdentity();
4870 try {
4871 return mNetworkManager.isBandwidthControlEnabled();
4872 } catch (RemoteException e) {
4873 // ignored; service lives in system_server
4874 return false;
4875 } finally {
4876 Binder.restoreCallingIdentity(token);
4877 }
4878 }
4879
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004880 private static Intent buildAllowBackgroundDataIntent() {
4881 return new Intent(ACTION_ALLOW_BACKGROUND);
4882 }
4883
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004884 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4885 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004886 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4887 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4888 return intent;
4889 }
4890
4891 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4892 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4893 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004894 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4895 return intent;
4896 }
4897
Wei Liu546cb772016-07-21 16:19:01 -07004898 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004899 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004900 intent.setComponent(ComponentName.unflattenFromString(
4901 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004902 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4903 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4904 return intent;
4905 }
4906
Wei Liu546cb772016-07-21 16:19:01 -07004907 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004908 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004909 intent.setComponent(ComponentName.unflattenFromString(
4910 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004911 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4912 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4913 return intent;
4914 }
4915
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004916 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004917 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004918 mHandler.getLooper().getQueue().addIdleHandler(handler);
4919 }
4920
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004921 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004922 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004923 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
Kweku Adams25fa3a72019-07-12 17:00:17 -07004924 if (mRestrictBackgroundLowPowerMode == result.batterySaverEnabled) {
4925 // Nothing changed. Nothing to do.
4926 return;
4927 }
4928 mRestrictBackgroundLowPowerMode = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004929
Kweku Adams25fa3a72019-07-12 17:00:17 -07004930 boolean restrictBackground = mRestrictBackgroundLowPowerMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004931 boolean shouldInvokeRestrictBackground;
Kweku Adams25fa3a72019-07-12 17:00:17 -07004932 // store the temporary mRestrictBackgroundChangedInBsm and update it at the end.
jackqdyulei29c82ab2017-03-10 14:09:16 -08004933 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4934
Kweku Adams25fa3a72019-07-12 17:00:17 -07004935 if (mRestrictBackgroundLowPowerMode) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004936 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4937 // turn it on.
Kweku Adams25fa3a72019-07-12 17:00:17 -07004938 shouldInvokeRestrictBackground = !mRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -08004939 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4940 localRestrictBgChangedInBsm = false;
4941 } else {
4942 // Try to restore the restrictBackground if it doesn't change in bsm
4943 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4944 restrictBackground = mRestrictBackgroundBeforeBsm;
4945 }
4946
4947 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004948 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004949 }
4950
4951 // Change it at last so setRestrictBackground() won't affect this variable
4952 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4953 }
4954
Jeff Sharkey1b861272011-05-22 00:34:52 -07004955 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4956 final int size = source.size();
4957 for (int i = 0; i < size; i++) {
4958 target.put(source.keyAt(i), true);
4959 }
4960 }
4961
Stuart Scottf1fb3972015-04-02 18:00:02 -07004962 @Override
4963 public void factoryReset(String subscriber) {
4964 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4965
Stuart Scotte3e314d2015-04-20 14:07:45 -07004966 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4967 return;
4968 }
4969
Stuart Scottf1fb3972015-04-02 18:00:02 -07004970 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004971 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004972 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4973 for (NetworkPolicy policy : policies) {
4974 if (policy.template.equals(template)) {
4975 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4976 policy.inferred = false;
4977 policy.clearSnooze();
4978 }
4979 }
4980 setNetworkPolicies(policies);
4981
4982 // Turn restrict background data off
4983 setRestrictBackground(false);
4984
Stuart Scotte3e314d2015-04-20 14:07:45 -07004985 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4986 // Remove app's "restrict background data" flag
4987 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4988 setUidPolicy(uid, POLICY_NONE);
4989 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004990 }
4991 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004992
Sudheer Shankab8f23162017-08-04 13:30:10 -07004993 @Override
4994 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004995 final long startTime = mStatLogger.getTime();
4996
Sudheer Shankab8f23162017-08-04 13:30:10 -07004997 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004998 final int uidRules;
4999 final boolean isBackgroundRestricted;
5000 synchronized (mUidRulesFirstLock) {
5001 uidRules = mUidRules.get(uid, RULE_NONE);
5002 isBackgroundRestricted = mRestrictBackground;
5003 }
junyulai05986c62018-08-07 19:50:45 +08005004 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5005 isBackgroundRestricted, mLogger);
5006
5007 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5008
5009 return ret;
5010 }
5011
5012 private static boolean isSystem(int uid) {
5013 return uid < Process.FIRST_APPLICATION_UID;
5014 }
5015
5016 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
5017 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
5018 final int reason;
5019 // Networks are never blocked for system components
5020 if (isSystem(uid)) {
5021 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005022 }
junyulai05986c62018-08-07 19:50:45 +08005023 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
5024 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005025 }
junyulai05986c62018-08-07 19:50:45 +08005026 else if (!isNetworkMetered) {
5027 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005028 }
junyulai05986c62018-08-07 19:50:45 +08005029 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
5030 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005031 }
junyulai05986c62018-08-07 19:50:45 +08005032 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
5033 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005034 }
junyulai05986c62018-08-07 19:50:45 +08005035 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
5036 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005037 }
junyulai05986c62018-08-07 19:50:45 +08005038 else if (isBackgroundRestricted) {
5039 reason = NTWK_BLOCKED_BG_RESTRICT;
5040 }
5041 else {
5042 reason = NTWK_ALLOWED_DEFAULT;
5043 }
5044
5045 final boolean blocked;
5046 switch(reason) {
5047 case NTWK_ALLOWED_DEFAULT:
5048 case NTWK_ALLOWED_NON_METERED:
5049 case NTWK_ALLOWED_TMP_WHITELIST:
5050 case NTWK_ALLOWED_WHITELIST:
5051 case NTWK_ALLOWED_SYSTEM:
5052 blocked = false;
5053 break;
5054 case NTWK_BLOCKED_POWER:
5055 case NTWK_BLOCKED_BLACKLIST:
5056 case NTWK_BLOCKED_BG_RESTRICT:
5057 blocked = true;
5058 break;
5059 default:
5060 throw new IllegalArgumentException();
5061 }
5062 if (logger != null) {
5063 logger.networkBlocked(uid, reason);
5064 }
5065
5066 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005067 }
5068
Felipe Lemed17fda42016-04-29 11:12:45 -07005069 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5070
5071 @Override
5072 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005073 synchronized (mUidRulesFirstLock) {
5074 boolean changed = removeUserStateUL(userId, false);
5075 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005076 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005077 synchronized (mNetworkPoliciesSecondLock) {
5078 writePolicyAL();
5079 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005080 }
5081 }
5082 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005083
5084 /**
5085 * @return true if the given uid is restricted from doing networking on metered networks.
5086 */
5087 @Override
5088 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5089 final int uidRules;
5090 final boolean isBackgroundRestricted;
5091 synchronized (mUidRulesFirstLock) {
5092 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5093 isBackgroundRestricted = mRestrictBackground;
5094 }
5095 return isBackgroundRestricted
5096 && !hasRule(uidRules, RULE_ALLOW_METERED)
5097 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5098 }
5099
5100 /**
5101 * @return true if networking is blocked on the given interface for the given uid according
5102 * to current networking policies.
5103 */
5104 @Override
5105 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005106 final long startTime = mStatLogger.getTime();
5107
junyulai05986c62018-08-07 19:50:45 +08005108 final int uidRules;
5109 final boolean isBackgroundRestricted;
5110 synchronized (mUidRulesFirstLock) {
5111 uidRules = mUidRules.get(uid, RULE_NONE);
5112 isBackgroundRestricted = mRestrictBackground;
5113 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005114 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005115 synchronized (mNetworkPoliciesSecondLock) {
5116 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005117 }
junyulai05986c62018-08-07 19:50:45 +08005118 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5119 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005120
5121 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5122
5123 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005124 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005125
5126 @Override
5127 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5128 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005129 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005130 if (added) {
5131 mPowerSaveTempWhitelistAppIds.put(appId, true);
5132 } else {
5133 mPowerSaveTempWhitelistAppIds.delete(appId);
5134 }
5135 updateRulesForTempWhitelistChangeUL(appId);
5136 }
5137 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005138
5139 @Override
5140 public SubscriptionPlan getSubscriptionPlan(Network network) {
5141 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005142 final int subId = getSubIdLocked(network);
5143 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005144 }
5145 }
5146
5147 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005148 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5149 synchronized (mNetworkPoliciesSecondLock) {
5150 final int subId = findRelevantSubIdNL(template);
5151 return getPrimarySubscriptionPlanLocked(subId);
5152 }
5153 }
5154
5155 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005156 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005157 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005158 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005159 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005160 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005161 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005162 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5163 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5164 }
5165
5166 if (quotaType == QUOTA_TYPE_JOBS) {
5167 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5168 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5169 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5170 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5171 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5172 } else {
5173 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5174 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005175 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005176
5177 @Override
5178 public void onAdminDataAvailable() {
5179 mAdminDataAvailableLatch.countDown();
5180 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005181
5182 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005183 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5184 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5185 }
5186
5187 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005188 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5189 setMeteredRestrictedPackagesInternal(packageNames, userId);
5190 }
5191
5192 @Override
5193 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5194 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5195 userId, 0, packageNames).sendToTarget();
5196 }
5197 }
5198
5199 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5200 synchronized (mUidRulesFirstLock) {
5201 final Set<Integer> newRestrictedUids = new ArraySet<>();
5202 for (String packageName : packageNames) {
5203 final int uid = getUidForPackage(packageName, userId);
5204 if (uid >= 0) {
5205 newRestrictedUids.add(uid);
5206 }
5207 }
5208 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5209 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5210 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5211 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5212 }
5213 }
5214
5215 private int getUidForPackage(String packageName, int userId) {
5216 try {
5217 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5218 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5219 } catch (NameNotFoundException e) {
5220 return -1;
5221 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005222 }
5223
5224 private int parseSubId(NetworkState state) {
5225 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5226 int subId = INVALID_SUBSCRIPTION_ID;
5227 if (state != null && state.networkCapabilities != null
5228 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5229 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5230 if (spec instanceof StringNetworkSpecifier) {
5231 try {
5232 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5233 } catch (NumberFormatException e) {
5234 }
5235 }
5236 }
5237 return subId;
5238 }
5239
Andreas Gampea36dc622018-02-05 17:19:22 -08005240 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005241 private int getSubIdLocked(Network network) {
5242 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005243 }
5244
Andreas Gampea36dc622018-02-05 17:19:22 -08005245 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005246 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5247 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005248 if (!ArrayUtils.isEmpty(plans)) {
5249 for (SubscriptionPlan plan : plans) {
5250 if (plan.getCycleRule().isRecurring()) {
5251 // Recurring plans will always have an active cycle
5252 return plan;
5253 } else {
5254 // Non-recurring plans need manual test for active cycle
5255 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5256 if (cycle.contains(ZonedDateTime.now(mClock))) {
5257 return plan;
5258 }
5259 }
5260 }
5261 }
5262 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005263 }
5264
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005265 /**
5266 * This will only ever be called once - during device boot.
5267 */
5268 private void waitForAdminData() {
5269 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5270 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5271 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5272 }
5273 }
5274
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005275 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5276 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005277 if (!mNetworkManagerReady) {
5278 return;
5279 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005280 if (oldRestrictedUids == null) {
5281 for (int uid : newRestrictedUids) {
5282 updateRulesForDataUsageRestrictionsUL(uid);
5283 }
5284 return;
5285 }
5286 for (int uid : oldRestrictedUids) {
5287 if (!newRestrictedUids.contains(uid)) {
5288 updateRulesForDataUsageRestrictionsUL(uid);
5289 }
5290 }
5291 for (int uid : newRestrictedUids) {
5292 if (!oldRestrictedUids.contains(uid)) {
5293 updateRulesForDataUsageRestrictionsUL(uid);
5294 }
5295 }
5296 }
5297
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005298 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005299 private boolean isRestrictedByAdminUL(int uid) {
5300 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5301 UserHandle.getUserId(uid));
5302 return restrictedUids != null && restrictedUids.contains(uid);
5303 }
5304
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005305 private static boolean hasRule(int uidRules, int rule) {
5306 return (uidRules & rule) != 0;
5307 }
5308
Jeff Sharkey2e471452018-01-19 18:02:47 +09005309 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5310 return (val != null) ? val : new NetworkState[0];
5311 }
5312
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005313 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5314 String key, boolean defaultValue) {
5315 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5316 }
5317
Chris Wren193ae6b2017-03-31 15:17:11 -04005318 private class NotificationId {
5319 private final String mTag;
5320 private final int mId;
5321
5322 NotificationId(NetworkPolicy policy, int type) {
5323 mTag = buildNotificationTag(policy, type);
5324 mId = type;
5325 }
5326
5327 @Override
5328 public boolean equals(Object o) {
5329 if (this == o) return true;
5330 if (!(o instanceof NotificationId)) return false;
5331 NotificationId that = (NotificationId) o;
5332 return Objects.equals(mTag, that.mTag);
5333 }
5334
5335 @Override
5336 public int hashCode() {
5337 return Objects.hash(mTag);
5338 }
5339
5340 /**
5341 * Build unique tag that identifies an active {@link NetworkPolicy}
5342 * notification of a specific type, like {@link #TYPE_LIMIT}.
5343 */
5344 private String buildNotificationTag(NetworkPolicy policy, int type) {
5345 return TAG + ":" + policy.template.hashCode() + ":" + type;
5346 }
5347
5348 public String getTag() {
5349 return mTag;
5350 }
5351
5352 public int getId() {
5353 return mId;
5354 }
5355 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005356}