blob: 19ff2c11d14cf64ac614a48b46258bc5365551bb [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070031import static android.content.pm.PackageManager.MATCH_ANY_USER;
32import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
33import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
34import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
35import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
Erik Klinef851d6d2015-04-20 16:03:48 +090036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080037import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
38import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
39import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060040import static android.net.ConnectivityManager.TYPE_MOBILE;
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +090041import static android.net.INetd.FIREWALL_CHAIN_DOZABLE;
42import static android.net.INetd.FIREWALL_CHAIN_POWERSAVE;
43import static android.net.INetd.FIREWALL_CHAIN_STANDBY;
44import static android.net.INetd.FIREWALL_RULE_ALLOW;
45import static android.net.INetd.FIREWALL_RULE_DENY;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060046import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090047import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey9252b342018-01-19 07:58:35 +090048import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070049import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070050import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070051import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070052import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeydc988062015-09-14 10:09:47 -070053import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060054import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070056import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070057import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070060import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070061import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070063import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070064import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080065import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
66import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060067import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070068import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070069import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070070import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070071import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070072import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080073import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey00072392018-04-12 14:26:32 -060074import static android.os.Trace.TRACE_TAG_NETWORK;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060075import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
79import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
80import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070081import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070082import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060083import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey0a5570d2018-04-10 12:38:29 -060084import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_NOTIFICATION_BOOL;
85import static android.telephony.CarrierConfigManager.KEY_DATA_RAPID_NOTIFICATION_BOOL;
86import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_NOTIFICATION_BOOL;
Jeff Sharkey9252b342018-01-19 07:58:35 +090087import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080088
Jeff Sharkey854b2b12012-04-13 16:03:40 -070089import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070091import static com.android.internal.util.XmlUtils.readBooleanAttribute;
92import static com.android.internal.util.XmlUtils.readIntAttribute;
93import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060094import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070095import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
96import static com.android.internal.util.XmlUtils.writeIntAttribute;
97import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060098import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070099import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700100import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
junyulai05986c62018-08-07 19:50:45 +0800102import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_SYSTEM;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700103import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
104import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
106import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
107import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700108import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600109
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800111import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700113
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700114import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700115import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900116import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700117import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700118import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800119import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700120import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700121import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700123import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700125import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700127import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700128import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700129import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600130import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700132import android.content.Intent;
133import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700134import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700135import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700136import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700137import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700138import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700139import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700143import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700144import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700145import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700146import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700147import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600148import android.net.Network;
149import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700150import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600152import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700153import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600154import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900155import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700157import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700158import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900159import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700161import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700162import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700163import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700164import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.os.Environment;
166import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700167import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700169import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700170import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700171import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700172import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700173import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700174import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600176import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800177import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700178import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700179import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600180import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700181import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700182import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700183import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600184import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700185import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700186import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700187import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700188import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100189import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700190import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600191import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800192import android.telephony.SubscriptionManager;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600193import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600194import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700195import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400196import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700197import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700198import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700199import android.util.ArrayMap;
200import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700201import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900202import android.util.DataUnit;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600203import android.util.IntArray;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700204import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700205import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600206import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600207import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700208import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900212import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700214
Jeff Sharkey497e4432011-06-14 17:27:29 -0700215import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700216import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400218import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500219import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700220import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800221import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800222import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600223import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700225import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600226import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700227import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700228import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700229import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700230import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800231import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600232
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600233import libcore.io.IoUtils;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600234import libcore.util.EmptyArray;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600235
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700240import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241import java.io.FileInputStream;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700245import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700246import java.lang.annotation.Retention;
247import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100248import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700249import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900250import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600251import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700252import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600253import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900254import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600256import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700257import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600258import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400259import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800260import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800261import java.util.concurrent.CountDownLatch;
262import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700264/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700265 * Service that maintains low-level network policy rules, using
266 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700267 * <p>
268 * Derives active rules by combining a given policy with other system status,
269 * and delivers to listeners, such as {@link ConnectivityManager}, for
270 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700271 *
272 * <p>
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700273 * This class uses 2 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700274 * <ul>
275 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
276 * rules).
277 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
278 * as network policies).
Felipe Lemef0823852016-06-08 13:43:08 -0700279 * </ul>
280 *
281 * <p>
282 * As such, methods that require synchronization have the following prefixes:
283 * <ul>
284 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
285 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000286 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
287 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700288 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700290public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700291 static final String TAG = NetworkPolicyLogger.TAG;
292 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
293 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700294
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900295 /**
296 * No opportunistic quota could be calculated from user data plan or data settings.
297 */
298 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
299
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final int VERSION_INIT = 1;
301 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700302 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800304 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800305 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700306 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700307 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700308 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700309 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600310 private static final int VERSION_ADDED_CYCLE = 11;
311 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800313 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400314 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800315 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400316 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400318 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900319 @VisibleForTesting
320 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700321
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String TAG_POLICY_LIST = "policy-list";
323 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600324 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700326 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800327 private static final String TAG_WHITELIST = "whitelist";
328 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800329 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
331 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700332 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700333 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
334 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700335 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600336 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
337 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
338 private static final String ATTR_CYCLE_START = "cycleStart";
339 private static final String ATTR_CYCLE_END = "cycleEnd";
340 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341 private static final String ATTR_WARNING_BYTES = "warningBytes";
342 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
345 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800346 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700347 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700349 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600351 private static final String ATTR_SUB_ID = "subId";
352 private static final String ATTR_TITLE = "title";
353 private static final String ATTR_SUMMARY = "summary";
354 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
355 private static final String ATTR_USAGE_BYTES = "usageBytes";
356 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600357 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800359 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800360 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800361 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800362 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700363 private static final String ACTION_SNOOZE_RAPID =
364 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700365
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800366 /**
367 * Indicates the maximum wait time for admin data to be available;
368 */
369 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
370
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600371 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
372 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
373 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
374 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
375
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700376 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700377 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800378 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800379 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700380 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700381 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
382 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700383 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700384 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900385 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800386 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700387 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700388
Makoto Onuki8e777332017-03-28 11:25:47 -0700389 private static final int UID_MSG_STATE_CHANGED = 100;
390 private static final int UID_MSG_GONE = 101;
391
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600392 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
393
Jeff Sharkey75279902011-05-24 18:39:45 -0700394 private final Context mContext;
395 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700396 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700397 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700398 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700399 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700400 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700401 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
403 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700404 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800406 @GuardedBy("mUidRulesFirstLock")
407 private PowerSaveState mRestrictBackgroundPowerState;
408
409 // Store the status of restrict background before turning on battery saver.
410 // Used to restore mRestrictBackground when battery saver is turned off.
411 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700412
Sudheer Shanka543339f2017-07-28 15:18:07 -0700413 // Denotes the status of restrict background read from disk.
414 private boolean mLoadedRestrictBackground;
415
Felipe Lemef0823852016-06-08 13:43:08 -0700416 // See main javadoc for instructions on how to use these locks.
417 final Object mUidRulesFirstLock = new Object();
418 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700419
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700420 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
421 volatile boolean mSystemReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700422
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
424 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
425 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800426 // Store whether user flipped restrict background in battery saver mode
427 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700428
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700429 private final boolean mSuppressDefaultPolicy;
430
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800431 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
432
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700433 private volatile boolean mNetworkManagerReady;
434
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700435 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600436 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800437 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700438
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600439 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600440 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600441 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600442 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600443 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600444 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600445
Jeff Sharkey9252b342018-01-19 07:58:35 +0900446 /** Map from subId to daily opportunistic quota. */
447 @GuardedBy("mNetworkPoliciesSecondLock")
448 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
449
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700450 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700451 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700452 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700454
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700456 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700458 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800460 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700461
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700462 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700464 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
465
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800466 // "Power save mode" is the concept used in the DeviceIdleController that includes various
467 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
468 // and "battery saver" are not equivalent.
469
Jeff Sharkey32566012014-12-02 18:30:14 -0800470 /**
471 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700472 * in power save mode, except device idle (doze) still applies.
473 * TODO: An int array might be sufficient
474 */
Felipe Lemef0823852016-06-08 13:43:08 -0700475 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700476 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
477
478 /**
479 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800480 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700481 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800482 */
Felipe Lemef0823852016-06-08 13:43:08 -0700483 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700484 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700485
Felipe Lemef0823852016-06-08 13:43:08 -0700486 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700487 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
488
Felipe Lemeb85a6372016-01-14 16:16:16 -0800489 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800490 * UIDs that have been white-listed temporarily to be able to have network access despite being
491 * idle. Other power saving restrictions still apply.
492 */
493 @GuardedBy("mUidRulesFirstLock")
494 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
495
496 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800497 * UIDs that have been initially white-listed by system to avoid restricted background.
498 */
Felipe Lemef0823852016-06-08 13:43:08 -0700499 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800500 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
501 new SparseBooleanArray();
502
503 /**
504 * UIDs that have been initially white-listed by system to avoid restricted background,
505 * but later revoked by user.
506 */
Felipe Lemef0823852016-06-08 13:43:08 -0700507 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800508 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
509 new SparseBooleanArray();
510
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700511 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800513 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700514 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700515 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800516 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700517
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700518 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700519 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400520 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700521
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700522 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700523 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800524 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700525
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600526 /** Map from network ID to last observed meteredness state */
527 @GuardedBy("mNetworkPoliciesSecondLock")
528 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900529 /** Map from network ID to last observed roaming state */
530 @GuardedBy("mNetworkPoliciesSecondLock")
531 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
532
Jeff Sharkey9252b342018-01-19 07:58:35 +0900533 /** Map from netId to subId as of last update */
534 @GuardedBy("mNetworkPoliciesSecondLock")
535 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
536
Jeff Sharkey146bb332018-04-18 15:42:57 -0600537 /** Map from subId to subscriberId as of last update */
538 @GuardedBy("mNetworkPoliciesSecondLock")
539 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
540 /** Set of all merged subscriberId as of last update */
541 @GuardedBy("mNetworkPoliciesSecondLock")
542 private String[] mMergedSubscriberIds = EmptyArray.STRING;
543
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800544 /**
545 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
546 * userId to restricted uids which belong to that user.
547 */
548 @GuardedBy("mUidRulesFirstLock")
549 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
550
Jeff Sharkey32566012014-12-02 18:30:14 -0800551 private final RemoteCallbackList<INetworkPolicyListener>
552 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700553
Dianne Hackborn497175b2014-07-01 12:56:08 -0700554 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700555 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800556 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700557
558 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700559
Andreas Gampee8e2ebd2018-10-24 19:42:52 -0700560 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700562
Svet Ganov16a16892015-04-16 10:32:04 -0700563 private final AppOpsManager mAppOps;
564
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800565 private final IPackageManager mIPm;
566
Sudheer Shankae7361852017-03-07 11:51:46 -0800567 private ActivityManagerInternal mActivityManagerInternal;
568
Sudheer Shanka352dc572017-09-22 17:09:38 -0700569 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800570
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700571 // TODO: keep whitelist of system-critical services that should never have
572 // rules enforced, such as system, phone, and radio UIDs.
573
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700574 // TODO: migrate notifications to SystemUI
575
Makoto Onuki49392d32018-04-11 13:51:02 -0700576
577 interface Stats {
578 int UPDATE_NETWORK_ENABLED = 0;
579 int IS_UID_NETWORKING_BLOCKED = 1;
580
581 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
582 }
583
584 public final StatLogger mStatLogger = new StatLogger(new String[] {
585 "updateNetworkEnabledNL()",
586 "isUidNetworkingBlocked()",
587 });
588
Jeff Sharkey75279902011-05-24 18:39:45 -0700589 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700590 INetworkManagementService networkManagement) {
591 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
592 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700593 }
594
Jeff Sharkey9911a282018-02-14 22:29:11 -0700595 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700596 return new File(Environment.getDataDirectory(), "system");
597 }
598
Jeff Sharkey9911a282018-02-14 22:29:11 -0700599 private static @NonNull Clock getDefaultClock() {
600 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
601 Clock.systemUTC());
602 }
603
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700604 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700605 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
606 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700607 mContext = checkNotNull(context, "missing context");
608 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700609 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700610 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700611 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700612 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700613 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700614 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700615 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700616
Amith Yamasani450a16b2013-09-18 16:28:50 -0700617 HandlerThread thread = new HandlerThread(TAG);
618 thread.start();
619 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700620
Makoto Onuki8e777332017-03-28 11:25:47 -0700621 // We create another thread for the UID events, which are more time-critical.
622 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
623 /*allowIo=*/ false);
624 mUidEventThread.start();
625 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
626
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700627 mSuppressDefaultPolicy = suppressDefaultPolicy;
628
Dianne Hackborne17b4452018-01-10 13:15:40 -0800629 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700630
631 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800632
Felipe Lemed17fda42016-04-29 11:12:45 -0700633 // Expose private service for system components to use.
634 LocalServices.addService(NetworkPolicyManagerInternal.class,
635 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700636 }
637
638 public void bindConnectivityManager(IConnectivityManager connManager) {
639 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700640 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700641
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700642 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700643 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700644 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700645 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
646 mPowerSaveWhitelistExceptIdleAppIds.clear();
647 if (whitelist != null) {
648 for (int uid : whitelist) {
649 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
650 }
651 }
652 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700653 mPowerSaveWhitelistAppIds.clear();
654 if (whitelist != null) {
655 for (int uid : whitelist) {
656 mPowerSaveWhitelistAppIds.put(uid, true);
657 }
658 }
659 } catch (RemoteException e) {
660 }
661 }
662
Felipe Lemea9505cc2016-02-26 10:28:41 -0800663 /**
664 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
665 * revoke the whitelist.
666 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700667 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800668 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700669 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700670 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800671 final List<UserInfo> users = mUserManager.getUsers();
672 final int numberUsers = users.size();
673
Felipe Lemea110eec2016-04-29 09:58:06 -0700674 boolean changed = false;
675 for (int i = 0; i < numberUsers; i++) {
676 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700677 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700678 }
679 return changed;
680 }
681
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700682 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700683 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700684 final SystemConfig sysConfig = SystemConfig.getInstance();
685 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800686 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
687 boolean changed = false;
688 for (int i = 0; i < allowDataUsage.size(); i++) {
689 final String pkg = allowDataUsage.valueAt(i);
690 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700691 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
692 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800693 final ApplicationInfo app;
694 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700695 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800696 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700697 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
698 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800699 continue;
700 }
701 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700702 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
703 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 continue;
705 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700706 final int uid = UserHandle.getUid(userId, app.uid);
707 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
708 if (LOGD)
709 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
710 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800711 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700712 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700713 if (LOGD)
714 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
715 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700716 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700717 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800718 }
719 }
720 return changed;
721 }
722
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800723 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700724 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800725 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800727 // Boost thread's priority during system server init
728 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700729 if (!isBandwidthControlEnabled()) {
730 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
731 return;
732 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700733
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700735 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700736
Felipe Leme873a83a2016-09-07 11:34:10 -0700737 synchronized (mUidRulesFirstLock) {
738 synchronized (mNetworkPoliciesSecondLock) {
739 updatePowerSaveWhitelistUL();
740 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
741 mPowerManagerInternal.registerLowPowerModeObserver(
742 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800743 @Override
744 public int getServiceType() {
745 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700746 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800747
748 @Override
749 public void onLowPowerModeChanged(PowerSaveState result) {
750 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800751 if (LOGD) {
752 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
753 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800754 synchronized (mUidRulesFirstLock) {
755 if (mRestrictPower != enabled) {
756 mRestrictPower = enabled;
757 updateRulesForRestrictPowerUL();
758 }
759 }
760 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800761 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800762 mRestrictPower = mPowerManagerInternal.getLowPowerState(
763 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700764
765 mSystemReady = true;
766
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800767 waitForAdminData();
768
Felipe Leme873a83a2016-09-07 11:34:10 -0700769 // read policy from disk
770 readPolicyAL();
771
jackqdyulei29c82ab2017-03-10 14:09:16 -0800772 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700773 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800774 mRestrictBackgroundPowerState = mPowerManagerInternal
775 .getLowPowerState(ServiceType.DATA_SAVER);
776 final boolean localRestrictBackground =
777 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700778 if (localRestrictBackground && !mLoadedRestrictBackground) {
779 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800780 }
781 mPowerManagerInternal.registerLowPowerModeObserver(
782 new PowerManagerInternal.LowPowerModeListener() {
783 @Override
784 public int getServiceType() {
785 return ServiceType.DATA_SAVER;
786 }
787
788 @Override
789 public void onLowPowerModeChanged(PowerSaveState result) {
790 synchronized (mUidRulesFirstLock) {
791 updateRestrictBackgroundByLowPowerModeUL(result);
792 }
793 }
794 });
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
797 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700798 }
Felipe Lemef0823852016-06-08 13:43:08 -0700799
Sudheer Shanka543339f2017-07-28 15:18:07 -0700800 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700801 updateRulesForGlobalChangeAL(false);
802 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700803 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800804 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700805
Sudheer Shankae7361852017-03-07 11:51:46 -0800806 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700807 try {
808 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000809 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700810 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700811 mNetworkManager.registerObserver(mAlertObserver);
812 } catch (RemoteException e) {
813 // ignored; both services live in system_server
814 }
815
816 // listen for changes to power save whitelist
817 final IntentFilter whitelistFilter = new IntentFilter(
818 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
819 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
820
Felipe Leme873a83a2016-09-07 11:34:10 -0700821 // watch for network interfaces to be claimed
822 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
823 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
824
825 // listen for package changes to update policy
826 final IntentFilter packageFilter = new IntentFilter();
827 packageFilter.addAction(ACTION_PACKAGE_ADDED);
828 packageFilter.addDataScheme("package");
829 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
830
831 // listen for UID changes to update policy
832 mContext.registerReceiver(
833 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
834
835 // listen for user changes to update policy
836 final IntentFilter userFilter = new IntentFilter();
837 userFilter.addAction(ACTION_USER_ADDED);
838 userFilter.addAction(ACTION_USER_REMOVED);
839 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
840
841 // listen for stats update events
842 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
843 mContext.registerReceiver(
844 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
845
846 // listen for restrict background changes from notifications
847 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
848 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
849
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700850 // Listen for snooze from notifications
851 mContext.registerReceiver(mSnoozeReceiver,
852 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
853 mContext.registerReceiver(mSnoozeReceiver,
854 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700855
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600856 // listen for configured wifi networks to be loaded
857 final IntentFilter wifiFilter =
858 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
859 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700860
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700861 // listen for carrier config changes to update data cycle information
862 final IntentFilter carrierConfigFilter = new IntentFilter(
863 ACTION_CARRIER_CONFIG_CHANGED);
864 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
865
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600866 // listen for meteredness changes
867 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
868 new NetworkRequest.Builder().build(), mNetworkCallback);
869
Felipe Leme873a83a2016-09-07 11:34:10 -0700870 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600871
872 // Listen for subscriber changes
873 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
874 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
875 @Override
876 public void onSubscriptionsChanged() {
877 updateNetworksInternal();
878 }
879 });
880
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800881 // tell systemReady() that the service has been initialized
882 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700883 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800884 // Restore the default priority after init is done
885 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700886 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700888 }
889
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800890 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700891 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800892 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
893 mHandler.post(() -> initService(initCompleteSignal));
894 return initCompleteSignal;
895 }
896
897 public void systemReady(CountDownLatch initCompleteSignal) {
898 // wait for initService to complete
899 try {
900 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
901 throw new IllegalStateException("Service " + TAG +" init timeout");
902 }
903 } catch (InterruptedException e) {
904 Thread.currentThread().interrupt();
905 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
906 }
907 }
908
Sudheer Shankac9d94072017-02-22 22:13:55 +0000909 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700910 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700911 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
912 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700913 }
914
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700915 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700916 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700917 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700918
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700919 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700920 }
921
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700922 @Override public void onUidIdle(int uid, boolean disabled) {
923 }
924
925 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700926 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700927 };
928
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700929 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700930 @Override
931 public void onReceive(Context context, Intent intent) {
932 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700933 synchronized (mUidRulesFirstLock) {
934 updatePowerSaveWhitelistUL();
935 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700936 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700937 }
938 }
939 };
940
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700942 @Override
943 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700944 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700945
946 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700947 final int uid = intent.getIntExtra(EXTRA_UID, -1);
948 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700949
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700950 if (ACTION_PACKAGE_ADDED.equals(action)) {
951 // update rules for UID, since it might be subject to
952 // global background data policy
953 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700954 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700955 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700956 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700957 }
958 }
959 };
960
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700961 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700962 @Override
963 public void onReceive(Context context, Intent intent) {
964 // on background handler thread, and UID_REMOVED is protected
965
966 final int uid = intent.getIntExtra(EXTRA_UID, -1);
967 if (uid == -1) return;
968
969 // remove any policy and update rules to clean up
970 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700971 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700972 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700973 synchronized (mNetworkPoliciesSecondLock) {
974 writePolicyAL();
975 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700976 }
977 }
978 };
979
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700980 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700981 @Override
982 public void onReceive(Context context, Intent intent) {
983 // on background handler thread, and USER_ADDED and USER_REMOVED
984 // broadcasts are protected
985
986 final String action = intent.getAction();
987 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
988 if (userId == -1) return;
989
Amith Yamasani15e472352015-04-24 19:06:07 -0700990 switch (action) {
991 case ACTION_USER_REMOVED:
992 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700993 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800994 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700995 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700996 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800997 // Removing outside removeUserStateUL since that can also be called when
998 // user resets app preferences.
999 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001000 if (action == ACTION_USER_ADDED) {
1001 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001002 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001003 }
1004 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001005 synchronized (mNetworkPoliciesSecondLock) {
1006 updateRulesForGlobalChangeAL(true);
1007 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001008 }
1009 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001010 }
1011 }
1012 };
1013
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001014 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015 * Receiver that watches for {@link INetworkStatsService} updates, which we
1016 * use to check against {@link NetworkPolicy#warningBytes}.
1017 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001018 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 @Override
1020 public void onReceive(Context context, Intent intent) {
1021 // on background handler thread, and verified
1022 // READ_NETWORK_USAGE_HISTORY permission above.
1023
Felipe Lemef0823852016-06-08 13:43:08 -07001024 synchronized (mNetworkPoliciesSecondLock) {
1025 updateNetworkEnabledNL();
1026 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 }
1028 }
1029 };
1030
1031 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001032 * Receiver that watches for {@link Notification} control of
1033 * {@link #mRestrictBackground}.
1034 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001035 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001036 @Override
1037 public void onReceive(Context context, Intent intent) {
1038 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1039 // permission above.
1040
1041 setRestrictBackground(false);
1042 }
1043 };
1044
1045 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001046 * Receiver that watches for {@link Notification} control of
1047 * {@link NetworkPolicy#lastWarningSnooze}.
1048 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001049 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001050 @Override
1051 public void onReceive(Context context, Intent intent) {
1052 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1053 // permission above.
1054
1055 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001056 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1057 performSnooze(template, TYPE_WARNING);
1058 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1059 performSnooze(template, TYPE_RAPID);
1060 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 }
1062 };
1063
1064 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001065 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001066 * we can perform upgrade logic. After initial upgrade logic, it updates
1067 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001068 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001069 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001070 @Override
1071 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001072 synchronized (mUidRulesFirstLock) {
1073 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001074 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001075 }
1076 }
1077 // Only need to perform upgrade logic once
1078 mContext.unregisterReceiver(this);
1079 }
1080 };
1081
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001082 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1083 Network network) {
1084 final boolean lastValue = lastValues.get(network.netId, false);
1085 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1086 if (changed) {
1087 lastValues.put(network.netId, newValue);
1088 }
1089 return changed;
1090 }
1091
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001092 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1093 @Override
1094 public void onCapabilitiesChanged(Network network,
1095 NetworkCapabilities networkCapabilities) {
1096 if (network == null || networkCapabilities == null) return;
1097
1098 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001099 final boolean newMetered = !networkCapabilities
1100 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001101 final boolean meteredChanged = updateCapabilityChange(
1102 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001103
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001104 final boolean newRoaming = !networkCapabilities
1105 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1106 final boolean roamingChanged = updateCapabilityChange(
1107 mNetworkRoaming, newRoaming, network);
1108
1109 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001110 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001111 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001112 }
1113 }
1114 }
1115 };
1116
1117 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 * Observer that watches for {@link INetworkManagementService} alerts.
1119 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001120 final private INetworkManagementEventObserver mAlertObserver
1121 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001122 @Override
1123 public void limitReached(String limitName, String iface) {
1124 // only someone like NMS should be calling us
1125 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1126
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001127 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1128 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 }
1130 }
1131 };
1132
1133 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1135 * to show visible notifications as needed.
1136 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001137 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001138 void updateNotificationsNL() {
1139 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001140 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001143 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145
1146 // TODO: when switching to kernel notifications, compute next future
1147 // cycle boundary to recompute notifications.
1148
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001149 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001150 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1152 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001153 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001154
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001156 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001157 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001158
Jeff Sharkey53313d72017-07-13 16:47:32 -06001159 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1160 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001161 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1162 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1163 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001165 // Carrier might want to manage notifications themselves
1166 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
Ammar Aijazib0941aa2019-04-26 18:39:50 -07001167 if (!CarrierConfigManager.isConfigForIdentifiedCarrier(config)) {
1168 if (LOGV) Slog.v(TAG, "isConfigForIdentifiedCarrier returned false");
1169 // Don't show notifications until we confirm that the loaded config is from an
1170 // identified carrier, which may want to manage their own notifications. This method
1171 // should be called every time the carrier config changes anyways, and there's no
1172 // reason to alert if there isn't a carrier.
1173 return;
1174 }
1175
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001176 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1177 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1178 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1179 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1180 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1181 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1182
1183 // Notify when data usage is over warning
1184 if (notifyWarning) {
1185 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1186 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1187 if (!snoozedThisCycle) {
1188 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1189 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001191 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001193 // Notify when data usage is over limit
1194 if (notifyLimit) {
1195 if (policy.isOverLimit(totalBytes)) {
1196 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1197 if (snoozedThisCycle) {
1198 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1199 } else {
1200 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1201 notifyOverLimitNL(policy.template);
1202 }
1203 } else {
1204 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001205 }
1206 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001207
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 // Warn if average usage over last 4 days is on track to blow pretty
1209 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001210 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001211 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001212 final long recentStart = now - recentDuration;
1213 final long recentEnd = now;
1214 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001215
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001216 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001217 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001218 final long alertBytes = (policy.limitBytes * 3) / 2;
1219
1220 if (LOGD) {
1221 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1222 + projectedBytes + " alert " + alertBytes);
1223 }
1224
1225 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1226 - DateUtils.DAY_IN_MILLIS;
1227 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001228 enqueueNotification(policy, TYPE_RAPID, 0,
1229 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001230 }
1231 }
1232 }
1233
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001235 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001236 final NotificationId notificationId = beforeNotifs.valueAt(i);
1237 if (!mActiveNotifs.contains(notificationId)) {
1238 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 }
1240 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001241
1242 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001243 }
1244
1245 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 * Attempt to find a specific app to blame for rapid data usage during the
1247 * given time period.
1248 */
1249 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1250 long start, long end) {
1251 long totalBytes = 0;
1252 long maxBytes = 0;
1253 int maxUid = 0;
1254
1255 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1256 NetworkStats.Entry entry = null;
1257 for (int i = 0; i < stats.size(); i++) {
1258 entry = stats.getValues(i, entry);
1259 final long bytes = entry.rxBytes + entry.txBytes;
1260 totalBytes += bytes;
1261 if (bytes > maxBytes) {
1262 maxBytes = bytes;
1263 maxUid = entry.uid;
1264 }
1265 }
1266
1267 // Only point blame if the majority of usage was done by a single app.
1268 // TODO: support shared UIDs
1269 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1270 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001271 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001272 try {
1273 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1274 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1275 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1276 } catch (NameNotFoundException ignored) {
1277 }
1278 }
1279 }
1280
1281 return null;
1282 }
1283
1284 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001285 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001286 * current device state, such as when
1287 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1288 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001289 *
1290 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1291 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001292 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001293 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001294 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001295 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001296 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1297 final int subId = mSubIdToSubscriberId.keyAt(i);
1298 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001299 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1300 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1301 true);
1302 if (template.matches(probeIdent)) {
1303 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001304 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001305 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001306 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001307 }
1308
1309 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001310 * Notify that given {@link NetworkTemplate} is over
1311 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1312 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001313 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001314 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001316 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001317 mOverLimitNotified.add(template);
1318 }
1319 }
1320
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001321 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001322 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001323 mOverLimitNotified.remove(template);
1324 }
1325
1326 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 * Show notification for combined {@link NetworkPolicy} and specific type,
1328 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1329 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001330 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1331 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001332 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001333 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001334 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001335 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001336 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001337 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001338 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001339
1340 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001341 final CharSequence title;
1342 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001343 switch (type) {
1344 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001345 title = res.getText(R.string.data_usage_warning_title);
1346 body = res.getString(R.string.data_usage_warning_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001347 Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001349 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001350
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001351 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1352 builder.setDeleteIntent(PendingIntent.getBroadcast(
1353 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1354
Wei Liu546cb772016-07-21 16:19:01 -07001355 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001356 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001357 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1358
Jeff Sharkey497e4432011-06-14 17:27:29 -07001359 break;
1360 }
1361 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001362 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001363 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001364 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001365 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001366 case MATCH_WIFI:
1367 title = res.getText(R.string.data_usage_wifi_limit_title);
1368 break;
1369 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001370 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001371 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001372 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001373
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001374 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001375 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001376
Wei Liu546cb772016-07-21 16:19:01 -07001377 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001378 builder.setContentIntent(PendingIntent.getActivity(
1379 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1380 break;
1381 }
1382 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001383 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001384 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001385 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1386 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001387 case MATCH_WIFI:
1388 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1389 break;
1390 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001391 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001392 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001393 final long overBytes = totalBytes - policy.limitBytes;
1394 body = res.getString(R.string.data_usage_limit_snoozed_body,
Anton Hanssona6101e82019-03-29 15:50:09 +00001395 Formatter.formatFileSize(mContext, overBytes, Formatter.FLAG_IEC_UNITS));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001396
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001397 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001398 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001399 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001400
Wei Liu546cb772016-07-21 16:19:01 -07001401 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001402 builder.setContentIntent(PendingIntent.getActivity(
1403 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001404 break;
1405 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001406 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001407 title = res.getText(R.string.data_usage_rapid_title);
1408 if (rapidBlame != null) {
1409 body = res.getString(R.string.data_usage_rapid_app_body,
1410 rapidBlame.loadLabel(mContext.getPackageManager()));
1411 } else {
1412 body = res.getString(R.string.data_usage_rapid_body);
1413 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001414
Jeff Sharkey2e471452018-01-19 18:02:47 +09001415 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001416
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001417 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1418 builder.setDeleteIntent(PendingIntent.getBroadcast(
1419 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1420
1421 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001422 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001423 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001424 break;
1425 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001426 default: {
1427 return;
1428 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001429 }
1430
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001431 builder.setTicker(title);
1432 builder.setContentTitle(title);
1433 builder.setContentText(body);
1434 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001435
1436 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1437 notificationId.getId(), builder.build(), UserHandle.ALL);
1438 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001439 }
1440
Chris Wren193ae6b2017-03-31 15:17:11 -04001441 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001442 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1443 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001444 }
1445
1446 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001447 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001448 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001449 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001450 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001451 @Override
1452 public void onReceive(Context context, Intent intent) {
1453 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1454 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001455 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001456 }
1457 };
1458
Jeff Sharkey146bb332018-04-18 15:42:57 -06001459 private void updateNetworksInternal() {
1460 // Get all of our cross-process communication with telephony out of
1461 // the way before we acquire internal locks.
1462 updateSubscriptions();
1463
1464 synchronized (mUidRulesFirstLock) {
1465 synchronized (mNetworkPoliciesSecondLock) {
1466 ensureActiveMobilePolicyAL();
1467 normalizePoliciesNL();
1468 updateNetworkEnabledNL();
1469 updateNetworkRulesNL();
1470 updateNotificationsNL();
1471 }
1472 }
1473 }
1474
Jeff Sharkey2e471452018-01-19 18:02:47 +09001475 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001476 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001477 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001478 final CountDownLatch latch = new CountDownLatch(1);
1479 mHandler.post(() -> {
1480 latch.countDown();
1481 });
1482 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001483 }
1484
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001485 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001486 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1487 * if necessary.
1488 *
1489 * @param subId that has its associated NetworkPolicy updated if necessary
1490 * @return if any policies were updated
1491 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001492 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001493 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001494 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001495
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001496 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001497 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001498 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001499 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001500 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1501 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1502 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001503 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1504 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001505 }
1506 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001507 return policyUpdated;
1508 }
1509
1510 /**
1511 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1512 *
1513 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1514 * to do so, it returns the fallback value.
1515 *
1516 * @param config The CarrierConfig to read the value from.
1517 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1518 * @return cycleDay to use in the mobile NetworkPolicy.
1519 */
1520 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001521 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001522 int fallbackCycleDay) {
1523 if (config == null) {
1524 return fallbackCycleDay;
1525 }
1526 int cycleDay =
1527 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1528 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1529 return fallbackCycleDay;
1530 }
1531 // validate cycleDay value
1532 final Calendar cal = Calendar.getInstance();
1533 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1534 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1535 Slog.e(TAG, "Invalid date in "
1536 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1537 return fallbackCycleDay;
1538 }
1539 return cycleDay;
1540 }
1541
1542 /**
1543 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1544 *
1545 * It attempts to get an appropriate value 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 fallbackWarningBytes to return if the CarrierConfig can't be read.
1550 * @return warningBytes to use in the mobile NetworkPolicy.
1551 */
1552 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001553 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001554 long fallbackWarningBytes) {
1555 if (config == null) {
1556 return fallbackWarningBytes;
1557 }
1558 long warningBytes =
1559 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1560
1561 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1562 return WARNING_DISABLED;
1563 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1564 return getPlatformDefaultWarningBytes();
1565 } else if (warningBytes < 0) {
1566 Slog.e(TAG, "Invalid value in "
1567 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1568 + "non-negative value but got: " + warningBytes);
1569 return fallbackWarningBytes;
1570 }
1571
1572 return warningBytes;
1573 }
1574
1575 /**
1576 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1577 *
1578 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1579 * to do so, it returns the fallback value.
1580 *
1581 * @param config The CarrierConfig to read the value from.
1582 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1583 * @return limitBytes to use in the mobile NetworkPolicy.
1584 */
1585 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001586 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001587 long fallbackLimitBytes) {
1588 if (config == null) {
1589 return fallbackLimitBytes;
1590 }
1591 long limitBytes =
1592 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1593
1594 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1595 return LIMIT_DISABLED;
1596 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1597 return getPlatformDefaultLimitBytes();
1598 } else if (limitBytes < 0) {
1599 Slog.e(TAG, "Invalid value in "
1600 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1601 + "non-negative value but got: " + limitBytes);
1602 return fallbackLimitBytes;
1603 }
1604 return limitBytes;
1605 }
1606
1607 /**
1608 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1609 */
1610 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1611 @Override
1612 public void onReceive(Context context, Intent intent) {
1613 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1614 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1615
1616 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1617 return;
1618 }
1619 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001620
1621 // Get all of our cross-process communication with telephony out of
1622 // the way before we acquire internal locks.
1623 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001624
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001625 synchronized (mUidRulesFirstLock) {
1626 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001627 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1628 if (subscriberId != null) {
1629 ensureActiveMobilePolicyAL(subId, subscriberId);
1630 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1631 } else {
1632 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1633 }
1634
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001635 // update network and notification rules, as the data cycle changed and it's
1636 // possible that we should be triggering warnings/limits now
1637 handleNetworkPoliciesUpdateAL(true);
1638 }
1639 }
1640 }
1641 };
1642
1643 /**
1644 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1645 * one has been updated.
1646 *
1647 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1648 * update.
1649 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001650 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001651 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1652 if (shouldNormalizePolicies) {
1653 normalizePoliciesNL();
1654 }
1655 updateNetworkEnabledNL();
1656 updateNetworkRulesNL();
1657 updateNotificationsNL();
1658 writePolicyAL();
1659 }
1660
1661 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001662 * Proactively control network data connections when they exceed
1663 * {@link NetworkPolicy#limitBytes}.
1664 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001665 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001666 void updateNetworkEnabledNL() {
1667 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001668 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001669
1670 // TODO: reset any policy-disabled networks when any policy is removed
1671 // completely, which is currently rare case.
1672
Makoto Onuki49392d32018-04-11 13:51:02 -07001673 final long startTime = mStatLogger.getTime();
1674
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001675 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1676 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001677 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001678 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001679 setNetworkTemplateEnabled(policy.template, true);
1680 continue;
1681 }
1682
Jeff Sharkey53313d72017-07-13 16:47:32 -06001683 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1684 .cycleIterator(policy).next();
1685 final long start = cycle.first.toInstant().toEpochMilli();
1686 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001687 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001688
1689 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001690 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1691 && policy.lastLimitSnooze < start;
1692 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001693
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001694 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001695 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001696
1697 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001698 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001699 }
1700
1701 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001702 * Proactively disable networks that match the given
1703 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001704 */
1705 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001706 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1707 // held. Call it via the handler.
1708 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1709 .sendToTarget();
1710 }
1711
1712 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001713 // TODO: reach into ConnectivityManager to proactively disable bringing
1714 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001715
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001716 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001717 // If mobile data usage hits the limit or if the user resumes the data, we need to
1718 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001719
Jeff Sharkey146bb332018-04-18 15:42:57 -06001720 final IntArray matchingSubIds = new IntArray();
1721 synchronized (mNetworkPoliciesSecondLock) {
1722 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1723 final int subId = mSubIdToSubscriberId.keyAt(i);
1724 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1725
1726 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1727 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1728 true);
1729 // Template is matched when subscriber id matches.
1730 if (template.matches(probeIdent)) {
1731 matchingSubIds.add(subId);
1732 }
Jack Yu8781b682016-07-08 14:28:51 -07001733 }
1734 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001735
1736 // Only talk with telephony outside of locks
1737 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1738 for (int i = 0; i < matchingSubIds.size(); i++) {
1739 final int subId = matchingSubIds.get(i);
1740 tm.setPolicyDataEnabled(enabled, subId);
1741 }
Jack Yu8781b682016-07-08 14:28:51 -07001742 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001743 }
1744
1745 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001746 * Collect all ifaces from a {@link NetworkState} into the given set.
1747 */
1748 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1749 final String baseIface = state.linkProperties.getInterfaceName();
1750 if (baseIface != null) {
1751 ifaces.add(baseIface);
1752 }
1753 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1754 final String stackedIface = stackedLink.getInterfaceName();
1755 if (stackedIface != null) {
1756 ifaces.add(stackedIface);
1757 }
1758 }
1759 }
1760
1761 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001762 * Examine all currently active subscriptions from
1763 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1764 * internal data structures.
1765 * <p>
1766 * Callers <em>must not</em> hold any locks when this method called.
1767 */
1768 void updateSubscriptions() {
1769 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1770 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1771
1772 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1773 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1774
1775 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
1776 final String[] mergedSubscriberIds = ArrayUtils.defeatNullable(tm.getMergedSubscriberIds());
1777
1778 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1779 for (int subId : subIds) {
1780 final String subscriberId = tm.getSubscriberId(subId);
1781 if (!TextUtils.isEmpty(subscriberId)) {
1782 subIdToSubscriberId.put(subId, subscriberId);
1783 } else {
1784 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1785 }
1786 }
1787
1788 synchronized (mNetworkPoliciesSecondLock) {
1789 mSubIdToSubscriberId.clear();
1790 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1791 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1792 subIdToSubscriberId.valueAt(i));
1793 }
1794
1795 mMergedSubscriberIds = mergedSubscriberIds;
1796 }
1797
1798 Trace.traceEnd(TRACE_TAG_NETWORK);
1799 }
1800
1801 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802 * Examine all connected {@link NetworkState}, looking for
1803 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1804 * remaining quota based on usage cycle and historical stats.
1805 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001806 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001807 void updateNetworkRulesNL() {
1808 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001809 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001810
1811 final NetworkState[] states;
1812 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001813 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001814 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001815 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001816 return;
1817 }
1818
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001819 // First, generate identities of all connected networks so we can
1820 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001821 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001822 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001823 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001824 if (state.network != null) {
1825 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1826 }
Wei Liub8eaf452016-01-25 10:32:27 -08001827 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001828 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1829 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001830 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001831 }
1832 }
1833
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001834 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001835 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001836
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001837 // For every well-defined policy, compute remaining data based on
1838 // current cycle and historical stats, and push to kernel.
1839 final ArraySet<String> matchingIfaces = new ArraySet<>();
1840 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1841 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1842
1843 // Collect all ifaces that match this policy
1844 matchingIfaces.clear();
1845 for (int j = identified.size() - 1; j >= 0; j--) {
1846 if (policy.template.matches(identified.valueAt(j))) {
1847 collectIfaces(matchingIfaces, identified.keyAt(j));
1848 }
1849 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001852 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001853 }
1854
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001855 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001856 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001857 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001858 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001859 if (hasLimit && policy.hasCycle()) {
1860 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1861 .cycleIterator(policy).next();
1862 final long start = cycle.first.toInstant().toEpochMilli();
1863 final long end = cycle.second.toInstant().toEpochMilli();
1864 final long totalBytes = getTotalBytes(policy.template, start, end);
1865
1866 if (policy.lastLimitSnooze >= start) {
1867 // snoozing past quota, but we still need to restrict apps,
1868 // so push really high quota.
1869 quotaBytes = Long.MAX_VALUE;
1870 } else {
1871 // remaining "quota" bytes are based on total usage in
1872 // current cycle. kernel doesn't like 0-byte rules, so we
1873 // set 1-byte quota and disable the radio later.
1874 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1875 }
1876 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001877 // metered network, but no policy limit; we still need to
1878 // restrict apps, so push really high quota.
1879 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001880 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001881
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001882 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001883 // TODO: switch to shared quota once NMS supports
1884 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001885 }
1886
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001887 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1888 final String iface = matchingIfaces.valueAt(j);
1889 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001890 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001891 }
1892 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001893
1894 // keep track of lowest warning or limit of active policies
1895 if (hasWarning && policy.warningBytes < lowestRule) {
1896 lowestRule = policy.warningBytes;
1897 }
1898 if (hasLimit && policy.limitBytes < lowestRule) {
1899 lowestRule = policy.limitBytes;
1900 }
1901 }
1902
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001903 // One final pass to catch any metered ifaces that don't have explicitly
1904 // defined policies; typically Wi-Fi networks.
1905 for (NetworkState state : states) {
1906 if (state.networkInfo != null && state.networkInfo.isConnected()
1907 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1908 matchingIfaces.clear();
1909 collectIfaces(matchingIfaces, state);
1910 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1911 final String iface = matchingIfaces.valueAt(j);
1912 if (!newMeteredIfaces.contains(iface)) {
1913 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1914 newMeteredIfaces.add(iface);
1915 }
1916 }
1917 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001918 }
1919
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001920 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001921 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1922 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001923 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001924 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001925 }
1926 }
1927 mMeteredIfaces = newMeteredIfaces;
1928
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001929 final ContentResolver cr = mContext.getContentResolver();
1930 final boolean quotaEnabled = Settings.Global.getInt(cr,
1931 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1932 final long quotaUnlimited = Settings.Global.getLong(cr,
1933 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1934 final float quotaLimited = Settings.Global.getFloat(cr,
1935 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1936
Jeff Sharkey9252b342018-01-19 07:58:35 +09001937 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001938 mSubscriptionOpportunisticQuota.clear();
1939 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001940 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001941 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001942 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001943 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001944 if (plan == null) continue;
1945
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001946 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001947 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001948 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1949 // Clamp to 0 when roaming
1950 quotaBytes = 0;
1951 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001952 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001953 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001954 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001955 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001956 } else {
1957 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001958 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1959 final long start = cycle.getLower().toInstant().toEpochMilli();
1960 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001961 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001962 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001963 .truncatedTo(ChronoUnit.DAYS)
1964 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001965 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001966 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1967 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001968 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001969 // Number of remaining days including current day
1970 final long remainingDays =
1971 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001972
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001973 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001974 }
1975
1976 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1977 }
1978
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001979 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001980 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001981
1982 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06001983
1984 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001985 }
1986
1987 /**
1988 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1989 * have at least a default mobile policy defined.
1990 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001991 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09001992 private void ensureActiveMobilePolicyAL() {
1993 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001994 if (mSuppressDefaultPolicy) return;
1995
Jeff Sharkey146bb332018-04-18 15:42:57 -06001996 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1997 final int subId = mSubIdToSubscriberId.keyAt(i);
1998 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001999
Hugo Benichi446c9c92017-04-10 09:41:10 +09002000 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08002001 }
2002 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002003
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002004 /**
2005 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
2006 * have at least a default mobile policy defined.
2007 *
2008 * @param subId to build a default policy for
2009 * @param subscriberId that we check for an existing policy
2010 * @return true if a mobile network policy was added, or false one already existed.
2011 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002012 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002013 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002014 // Poke around to see if we already have a policy
2015 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002016 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002017 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2018 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2019 if (template.matches(probeIdent)) {
2020 if (LOGD) {
2021 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2022 + NetworkIdentity.scrubSubscriberId(subscriberId));
2023 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002024 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002025 }
2026 }
2027
Jeff Sharkey32566012014-12-02 18:30:14 -08002028 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2029 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002030 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002031 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002032 return true;
2033 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002034
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002035 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002036 final int dataWarningConfig = mContext.getResources().getInteger(
2037 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002038 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002039 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002040 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002041 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002042 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002043 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002044
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002045 private long getPlatformDefaultLimitBytes() {
2046 return LIMIT_DISABLED;
2047 }
2048
2049 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002050 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002051 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002052 final RecurrenceRule cycleRule = NetworkPolicy
2053 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002054 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002055 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2056 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2057 synchronized (mUidRulesFirstLock) {
2058 synchronized (mNetworkPoliciesSecondLock) {
2059 updateDefaultMobilePolicyAL(subId, policy);
2060 }
2061 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002062 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002063 }
2064
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002065 /**
2066 * Update the given {@link NetworkPolicy} based on any carrier-provided
2067 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2068 * Leaves policy untouched if the user has modified it.
2069 *
2070 * @return if the policy was modified
2071 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002072 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002073 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2074 if (!policy.inferred) {
2075 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2076 return false;
2077 }
2078
2079 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2080 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2081 policy.lastLimitSnooze, policy.metered, policy.inferred);
2082
2083 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2084 if (!ArrayUtils.isEmpty(plans)) {
2085 final SubscriptionPlan plan = plans[0];
2086 policy.cycleRule = plan.getCycleRule();
2087 final long planLimitBytes = plan.getDataLimitBytes();
2088 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2089 policy.warningBytes = getPlatformDefaultWarningBytes();
2090 policy.limitBytes = getPlatformDefaultLimitBytes();
2091 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2092 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2093 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2094 } else {
2095 policy.warningBytes = (planLimitBytes * 9) / 10;
2096 switch (plan.getDataLimitBehavior()) {
2097 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2098 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2099 policy.limitBytes = planLimitBytes;
2100 break;
2101 default:
2102 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2103 break;
2104 }
2105 }
2106 } else {
2107 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2108 final int currentCycleDay;
2109 if (policy.cycleRule.isMonthly()) {
2110 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2111 } else {
2112 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2113 }
2114 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2115 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2116 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2117 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2118 }
2119
2120 if (policy.equals(original)) {
2121 return false;
2122 } else {
2123 Slog.d(TAG, "Updated " + original + " to " + policy);
2124 return true;
2125 }
2126 }
2127
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002128 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002129 private void readPolicyAL() {
2130 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002131
2132 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002133 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002134 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002135 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002136 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002137
2138 FileInputStream fis = null;
2139 try {
2140 fis = mPolicyFile.openRead();
2141 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002142 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002143
Felipe Leme46b451f2016-08-19 08:46:17 -07002144 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2145 // to skip UIDs that were explicitly blacklisted.
2146 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2147
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002148 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002149 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002150 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002151 while ((type = in.next()) != END_DOCUMENT) {
2152 final String tag = in.getName();
2153 if (type == START_TAG) {
2154 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002155 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002156 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002157 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2158 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2160 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2161 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002162 final String networkId;
2163 if (version >= VERSION_ADDED_NETWORK_ID) {
2164 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2165 } else {
2166 networkId = null;
2167 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002168 final RecurrenceRule cycleRule;
2169 if (version >= VERSION_ADDED_CYCLE) {
2170 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2171 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2172 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2173 cycleRule = new RecurrenceRule(
2174 RecurrenceRule.convertZonedDateTime(start),
2175 RecurrenceRule.convertZonedDateTime(end),
2176 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002177 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002178 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2179 final String cycleTimezone;
2180 if (version >= VERSION_ADDED_TIMEZONE) {
2181 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2182 } else {
2183 cycleTimezone = "UTC";
2184 }
2185 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002186 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2188 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002189 final long lastLimitSnooze;
2190 if (version >= VERSION_SPLIT_SNOOZE) {
2191 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2192 } else if (version >= VERSION_ADDED_SNOOZE) {
2193 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002194 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002195 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002196 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002197 final boolean metered;
2198 if (version >= VERSION_ADDED_METERED) {
2199 metered = readBooleanAttribute(in, ATTR_METERED);
2200 } else {
2201 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002202 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002203 metered = true;
2204 break;
2205 default:
2206 metered = false;
2207 }
2208 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002209 final long lastWarningSnooze;
2210 if (version >= VERSION_SPLIT_SNOOZE) {
2211 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2212 } else {
2213 lastWarningSnooze = SNOOZE_NEVER;
2214 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002215 final boolean inferred;
2216 if (version >= VERSION_ADDED_INFERRED) {
2217 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2218 } else {
2219 inferred = false;
2220 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002221
Jeff Sharkey32566012014-12-02 18:30:14 -08002222 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2223 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002224 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002225 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2226 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002227 lastLimitSnooze, metered, inferred));
2228 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002229
2230 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2231 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2232 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2233 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2234 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2235 RecurrenceRule.convertZonedDateTime(start),
2236 RecurrenceRule.convertZonedDateTime(end),
2237 RecurrenceRule.convertPeriod(period));
2238 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2239 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2240
2241 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2242 SubscriptionPlan.BYTES_UNKNOWN);
2243 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2244 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2245 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2246 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2247 builder.setDataLimit(limitBytes, limitBehavior);
2248 }
2249
2250 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2251 SubscriptionPlan.BYTES_UNKNOWN);
2252 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2253 SubscriptionPlan.TIME_UNKNOWN);
2254 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2255 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2256 builder.setDataUsage(usageBytes, usageTime);
2257 }
2258
2259 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2260 final SubscriptionPlan plan = builder.build();
2261 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2262 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2263
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002264 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2265 mSubscriptionPlansOwner.put(subId, ownerPackage);
2266
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002267 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002268 final int uid = readIntAttribute(in, ATTR_UID);
2269 final int policy = readIntAttribute(in, ATTR_POLICY);
2270
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002271 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002272 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002273 } else {
2274 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2275 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002276 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002277 final int appId = readIntAttribute(in, ATTR_APP_ID);
2278 final int policy = readIntAttribute(in, ATTR_POLICY);
2279
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002280 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002281 // app policy is deprecated so this is only used in pre system user split.
2282 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002283 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002284 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002285 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002286 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002287 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002288 } else if (TAG_WHITELIST.equals(tag)) {
2289 insideWhitelist = true;
2290 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2291 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002292 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002293 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2294 final int uid = readIntAttribute(in, ATTR_UID);
2295 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002296 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002297 } else if (type == END_TAG) {
2298 if (TAG_WHITELIST.equals(tag)) {
2299 insideWhitelist = false;
2300 }
2301
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002302 }
2303 }
2304
Felipe Leme46b451f2016-08-19 08:46:17 -07002305 final int size = whitelistedRestrictBackground.size();
2306 for (int i = 0; i < size; i++) {
2307 final int uid = whitelistedRestrictBackground.keyAt(i);
2308 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2309 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2310 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2311 + " because its policy is " + uidPoliciesToString(policy));
2312 continue;
2313 }
2314 if (UserHandle.isApp(uid)) {
2315 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2316 if (LOGV)
2317 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2318 setUidPolicyUncheckedUL(uid, newPolicy, false);
2319 } else {
2320 Slog.w(TAG, "unable to update policy on UID " + uid);
2321 }
2322 }
2323
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002324 } catch (FileNotFoundException e) {
2325 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002326 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002327 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002328 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002329 } finally {
2330 IoUtils.closeQuietly(fis);
2331 }
2332 }
2333
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002334 /**
2335 * Upgrade legacy background data flags, notifying listeners of one last
2336 * change to always-true.
2337 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002338 private void upgradeDefaultBackgroundDataUL() {
2339 // This method is only called when we're unable to find the network policy flag, which
2340 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002341
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002342 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002343 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002344 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2345
2346 // NOTE: We used to read the legacy setting here :
2347 //
2348 // final int legacyFlagValue = Settings.Secure.getInt(
2349 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2350 //
2351 // This is no longer necessary because we will never upgrade directly from Gingerbread
2352 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2353 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002354 }
2355
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002356 /**
2357 * Perform upgrade step of moving any user-defined meterness overrides over
2358 * into {@link WifiConfiguration}.
2359 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002360 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002361 private void upgradeWifiMeteredOverrideAL() {
2362 boolean modified = false;
2363 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2364 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2365 for (int i = 0; i < mNetworkPolicy.size(); ) {
2366 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2367 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2368 && !policy.inferred) {
2369 mNetworkPolicy.removeAt(i);
2370 modified = true;
2371
2372 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2373 for (WifiConfiguration config : configs) {
2374 if (Objects.equals(resolveNetworkId(config), networkId)) {
2375 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2376 config.meteredOverride = policy.metered
2377 ? WifiConfiguration.METERED_OVERRIDE_METERED
2378 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2379 wm.updateNetwork(config);
2380 }
2381 }
2382 } else {
2383 i++;
2384 }
2385 }
2386 if (modified) {
2387 writePolicyAL();
2388 }
2389 }
2390
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002391 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002392 void writePolicyAL() {
2393 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002394
2395 FileOutputStream fos = null;
2396 try {
2397 fos = mPolicyFile.startWrite();
2398
2399 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002400 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002401 out.startDocument(null, true);
2402
2403 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002404 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002405 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002406
2407 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002408 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2409 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002410 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002411 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002412
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002413 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002414 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2415 final String subscriberId = template.getSubscriberId();
2416 if (subscriberId != null) {
2417 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002418 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002419 final String networkId = template.getNetworkId();
2420 if (networkId != null) {
2421 out.attribute(null, ATTR_NETWORK_ID, networkId);
2422 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002423 writeStringAttribute(out, ATTR_CYCLE_START,
2424 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2425 writeStringAttribute(out, ATTR_CYCLE_END,
2426 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2427 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2428 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002429 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2430 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002431 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2432 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002433 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002434 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002435 out.endTag(null, TAG_NETWORK_POLICY);
2436 }
2437
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002438 // write all known subscription plans
2439 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2440 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002441 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002442 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2443 if (ArrayUtils.isEmpty(plans)) continue;
2444
2445 for (SubscriptionPlan plan : plans) {
2446 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2447 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002448 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002449 final RecurrenceRule cycleRule = plan.getCycleRule();
2450 writeStringAttribute(out, ATTR_CYCLE_START,
2451 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2452 writeStringAttribute(out, ATTR_CYCLE_END,
2453 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2454 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2455 RecurrenceRule.convertPeriod(cycleRule.period));
2456 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2457 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2458 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2459 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2460 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2461 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2462 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2463 }
2464 }
2465
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002466 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002467 for (int i = 0; i < mUidPolicy.size(); i++) {
2468 final int uid = mUidPolicy.keyAt(i);
2469 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002470
Jeff Sharkey497e4432011-06-14 17:27:29 -07002471 // skip writing empty policies
2472 if (policy == POLICY_NONE) continue;
2473
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002474 out.startTag(null, TAG_UID_POLICY);
2475 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002476 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002477 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002478 }
2479
2480 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002481
2482 // write all whitelists
2483 out.startTag(null, TAG_WHITELIST);
2484
Felipe Lemea9505cc2016-02-26 10:28:41 -08002485 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002486 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002487 for (int i = 0; i < size; i++) {
2488 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2489 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2490 writeIntAttribute(out, ATTR_UID, uid);
2491 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2492 }
2493
Felipe Lemeb85a6372016-01-14 16:16:16 -08002494 out.endTag(null, TAG_WHITELIST);
2495
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002496 out.endDocument();
2497
2498 mPolicyFile.finishWrite(fos);
2499 } catch (IOException e) {
2500 if (fos != null) {
2501 mPolicyFile.failWrite(fos);
2502 }
2503 }
2504 }
2505
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002506 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002507 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002508 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002510 if (!UserHandle.isApp(uid)) {
2511 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002512 }
Felipe Lemef0823852016-06-08 13:43:08 -07002513 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002514 final long token = Binder.clearCallingIdentity();
2515 try {
2516 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2517 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002518 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002519 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002520 }
2521 } finally {
2522 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002523 }
2524 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002525 }
2526
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002527 @Override
2528 public void addUidPolicy(int uid, int policy) {
2529 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002530
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002531 if (!UserHandle.isApp(uid)) {
2532 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2533 }
2534
Felipe Lemef0823852016-06-08 13:43:08 -07002535 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002536 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2537 policy |= oldPolicy;
2538 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002539 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002540 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002541 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002542 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002543 }
2544
2545 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002546 public void removeUidPolicy(int uid, int policy) {
2547 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2548
2549 if (!UserHandle.isApp(uid)) {
2550 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2551 }
2552
Felipe Lemef0823852016-06-08 13:43:08 -07002553 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002554 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2555 policy = oldPolicy & ~policy;
2556 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002557 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002558 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002559 }
2560 }
2561 }
2562
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002563 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002564 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002565 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002566
Felipe Leme57e3d312016-08-23 14:42:52 -07002567 final boolean notifyApp;
2568 if (!isUidValidForWhitelistRules(uid)) {
2569 notifyApp = false;
2570 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002571 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2572 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2573 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2574 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002575 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2576 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002577 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2578 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2579 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2580 if (LOGD)
2581 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2582 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2583 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002584 notifyApp = wasBlocked != isBlocked;
2585 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002586 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2587 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002588 if (persist) {
2589 synchronized (mNetworkPoliciesSecondLock) {
2590 writePolicyAL();
2591 }
2592 }
Felipe Leme923845f2016-03-02 13:42:48 -08002593 }
2594
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002595 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002596 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002597 if (policy == POLICY_NONE) {
2598 mUidPolicy.delete(uid);
2599 } else {
2600 mUidPolicy.put(uid, policy);
2601 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002602
2603 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002604 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002605 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002606 synchronized (mNetworkPoliciesSecondLock) {
2607 writePolicyAL();
2608 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002609 }
2610 }
2611
2612 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002613 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002614 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2615
Felipe Lemef0823852016-06-08 13:43:08 -07002616 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002617 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002618 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002619 }
2620
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002621 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002622 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002623 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2624
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002625 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002626 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002627 for (int i = 0; i < mUidPolicy.size(); i++) {
2628 final int uid = mUidPolicy.keyAt(i);
2629 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002630 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2631 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002632 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002633 }
2634 }
2635 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002636 return uids;
2637 }
2638
2639 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002640 * Removes any persistable state associated with given {@link UserHandle}, persisting
2641 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002642 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002643 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002644 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002645
Sudheer Shanka352dc572017-09-22 17:09:38 -07002646 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002647 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002648
Felipe Lemea110eec2016-04-29 09:58:06 -07002649 // Remove entries from revoked default restricted background UID whitelist
2650 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2651 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2652 if (UserHandle.getUserId(uid) == userId) {
2653 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002654 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002655 }
2656 }
2657
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002658 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002659 int[] uids = new int[0];
2660 for (int i = 0; i < mUidPolicy.size(); i++) {
2661 final int uid = mUidPolicy.keyAt(i);
2662 if (UserHandle.getUserId(uid) == userId) {
2663 uids = appendInt(uids, uid);
2664 }
2665 }
2666
2667 if (uids.length > 0) {
2668 for (int uid : uids) {
2669 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002670 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002671 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002672 }
Felipe Lemef0823852016-06-08 13:43:08 -07002673 synchronized (mNetworkPoliciesSecondLock) {
2674 updateRulesForGlobalChangeAL(true);
2675 if (writePolicy && changed) {
2676 writePolicyAL();
2677 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002678 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002679 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002680 }
2681
2682 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002683 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002684 // TODO: create permission for observing network policy
2685 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002686 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002687 }
2688
2689 @Override
2690 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002691 // TODO: create permission for observing network policy
2692 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002693 mListeners.unregister(listener);
2694 }
2695
Jeff Sharkey1b861272011-05-22 00:34:52 -07002696 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002697 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2699
Felipe Leme6a05eee2016-02-19 14:43:51 -08002700 final long token = Binder.clearCallingIdentity();
2701 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002702 synchronized (mUidRulesFirstLock) {
2703 synchronized (mNetworkPoliciesSecondLock) {
2704 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002705 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002706 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002707 }
2708 } finally {
2709 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002710 }
2711 }
2712
Hugo Benichi446c9c92017-04-10 09:41:10 +09002713 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002714 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002715 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2716 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002717 }
2718
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002719 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002720 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002722 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002723 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2724 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2725 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002726 } catch (SecurityException e) {
2727 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002728
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002729 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2730 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2731 return new NetworkPolicy[0];
2732 }
Svet Ganov16a16892015-04-16 10:32:04 -07002733 }
2734
Felipe Lemef0823852016-06-08 13:43:08 -07002735 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002736 final int size = mNetworkPolicy.size();
2737 final NetworkPolicy[] policies = new NetworkPolicy[size];
2738 for (int i = 0; i < size; i++) {
2739 policies[i] = mNetworkPolicy.valueAt(i);
2740 }
2741 return policies;
2742 }
2743 }
2744
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002745 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002746 private void normalizePoliciesNL() {
2747 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002748 }
2749
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002750 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002751 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002752 mNetworkPolicy.clear();
2753 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002754 if (policy == null) {
2755 continue;
2756 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002757 // When two normalized templates conflict, prefer the most
2758 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002759 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002760 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2761 if (existing == null || existing.compareTo(policy) > 0) {
2762 if (existing != null) {
2763 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2764 }
2765 mNetworkPolicy.put(policy.template, policy);
2766 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002767 }
2768 }
2769
2770 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002771 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002772 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002773
2774 final long token = Binder.clearCallingIdentity();
2775 try {
2776 performSnooze(template, TYPE_LIMIT);
2777 } finally {
2778 Binder.restoreCallingIdentity(token);
2779 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002780 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002781
Dianne Hackborn497175b2014-07-01 12:56:08 -07002782 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002783 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002784 synchronized (mUidRulesFirstLock) {
2785 synchronized (mNetworkPoliciesSecondLock) {
2786 // find and snooze local policy that matches
2787 final NetworkPolicy policy = mNetworkPolicy.get(template);
2788 if (policy == null) {
2789 throw new IllegalArgumentException("unable to find policy for " + template);
2790 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002791
Felipe Lemef0823852016-06-08 13:43:08 -07002792 switch (type) {
2793 case TYPE_WARNING:
2794 policy.lastWarningSnooze = currentTime;
2795 break;
2796 case TYPE_LIMIT:
2797 policy.lastLimitSnooze = currentTime;
2798 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002799 case TYPE_RAPID:
2800 policy.lastRapidSnooze = currentTime;
2801 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002802 default:
2803 throw new IllegalArgumentException("unexpected type");
2804 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002805
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002806 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002807 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002808 }
2809 }
2810
2811 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002812 public void onTetheringChanged(String iface, boolean tethering) {
2813 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002814 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002815 if (mRestrictBackground && tethering) {
2816 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2817 setRestrictBackground(false);
2818 }
2819 }
2820 }
2821
2822 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002823 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002824 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002825 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002826 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2827 final long token = Binder.clearCallingIdentity();
2828 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002829 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002830 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002831 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002832 } finally {
2833 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002834 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002835 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002836 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002837 }
2838 }
2839
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002840 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002841 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002842 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002843 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002844 if (restrictBackground == mRestrictBackground) {
2845 // Ideally, UI should never allow this scenario...
2846 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002847 return;
2848 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002849 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2850 final boolean oldRestrictBackground = mRestrictBackground;
2851 mRestrictBackground = restrictBackground;
2852 // Must whitelist foreground apps before turning data saver mode on.
2853 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2854 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2855 updateRulesForRestrictBackgroundUL();
2856 try {
2857 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2858 Slog.e(TAG,
2859 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2860 mRestrictBackground = oldRestrictBackground;
2861 // TODO: if it knew the foreground apps (see TODO above), it could call
2862 // updateRulesForRestrictBackgroundUL() again to restore state.
2863 return;
2864 }
2865 } catch (RemoteException e) {
2866 // ignored; service lives in system_server
2867 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002868
Sudheer Shanka543339f2017-07-28 15:18:07 -07002869 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002870 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002871
2872 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2873 mRestrictBackgroundChangedInBsm = true;
2874 }
2875 synchronized (mNetworkPoliciesSecondLock) {
2876 updateNotificationsNL();
2877 writePolicyAL();
2878 }
2879 } finally {
2880 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002881 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002882 }
2883
2884 private void sendRestrictBackgroundChangedMsg() {
2885 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2886 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2887 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002888 }
2889
Felipe Lemeb85a6372016-01-14 16:16:16 -08002890 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002891 public int getRestrictBackgroundByCaller() {
2892 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2893 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002894
Felipe Lemef0823852016-06-08 13:43:08 -07002895 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002896 // Must clear identity because getUidPolicy() is restricted to system.
2897 final long token = Binder.clearCallingIdentity();
2898 final int policy;
2899 try {
2900 policy = getUidPolicy(uid);
2901 } finally {
2902 Binder.restoreCallingIdentity(token);
2903 }
2904 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2905 // App is blacklisted.
2906 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2907 }
Felipe Leme1b103232016-01-22 09:44:57 -08002908 if (!mRestrictBackground) {
2909 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2910 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002911 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002912 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2913 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2914 }
2915 }
2916
2917 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002918 public boolean getRestrictBackground() {
2919 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2920
Felipe Lemef0823852016-06-08 13:43:08 -07002921 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002922 return mRestrictBackground;
2923 }
2924 }
2925
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002926 @Override
2927 public void setDeviceIdleMode(boolean enabled) {
2928 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002929 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2930 try {
2931 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002932 if (mDeviceIdleMode == enabled) {
2933 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002934 }
Felipe Lemeea014392016-09-06 13:59:54 -07002935 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002936 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002937 if (mSystemReady) {
2938 // Device idle change means we need to rebuild rules for all
2939 // known apps, so do a global refresh.
2940 updateRulesForRestrictPowerUL();
2941 }
2942 }
2943 if (enabled) {
2944 EventLogTags.writeDeviceIdleOnPhase("net");
2945 } else {
2946 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002947 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002948 } finally {
2949 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002950 }
2951 }
2952
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002953 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002954 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2955 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002956 final long token = Binder.clearCallingIdentity();
2957 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002958 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2959 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2960 for (WifiConfiguration config : configs) {
2961 if (Objects.equals(resolveNetworkId(config), networkId)) {
2962 config.meteredOverride = meteredOverride;
2963 wm.updateNetwork(config);
2964 }
2965 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002966 } finally {
2967 Binder.restoreCallingIdentity(token);
2968 }
2969 }
2970
Jeff Sharkey46645002011-07-27 21:11:21 -07002971 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002972 @Deprecated
2973 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2974 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2975 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2976 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002977 }
2978
Jeff Sharkey53313d72017-07-13 16:47:32 -06002979 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2980 // Verify they're not lying about package name
2981 mAppOps.checkPackage(callingUid, callingPackage);
2982
Jeff Sharkey53313d72017-07-13 16:47:32 -06002983 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002984 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002985 final long token = Binder.clearCallingIdentity();
2986 try {
2987 si = mContext.getSystemService(SubscriptionManager.class)
2988 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002989 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002990 } finally {
2991 Binder.restoreCallingIdentity(token);
2992 }
2993
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002994 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002995 if (si != null) {
2996 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2997 return;
2998 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002999 }
3000
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003001 // Second check: has the CarrierService delegated access?
3002 if (config != null) {
3003 final String overridePackage = config
3004 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
3005 if (!TextUtils.isEmpty(overridePackage)
3006 && Objects.equals(overridePackage, callingPackage)) {
3007 return;
3008 }
3009 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003010
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003011 // Third check: is caller the fallback/default CarrierService?
3012 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3013 if (!TextUtils.isEmpty(defaultPackage)
3014 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003015 return;
3016 }
3017
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003018 // Fourth check: is caller a testing app?
3019 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3020 if (!TextUtils.isEmpty(testPackage)
3021 && Objects.equals(testPackage, callingPackage)) {
3022 return;
3023 }
3024
3025 // Fifth check: is caller a legacy testing app?
3026 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3027 if (!TextUtils.isEmpty(legacyTestPackage)
3028 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003029 return;
3030 }
3031
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003032 // Final check: does the caller hold a permission?
3033 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003034 }
3035
3036 @Override
3037 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3038 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3039
Jeff Sharkey53313d72017-07-13 16:47:32 -06003040 final String fake = SystemProperties.get("fw.fake_plan");
3041 if (!TextUtils.isEmpty(fake)) {
3042 final List<SubscriptionPlan> plans = new ArrayList<>();
3043 if ("month_hard".equals(fake)) {
3044 plans.add(SubscriptionPlan.Builder
3045 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3046 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003047 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3048 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3049 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3050 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3051 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003052 plans.add(SubscriptionPlan.Builder
3053 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3054 .setTitle("G-Mobile Happy")
3055 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3056 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3057 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3058 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3059 .build());
3060 plans.add(SubscriptionPlan.Builder
3061 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3062 .setTitle("G-Mobile, Charged after limit")
3063 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3064 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3065 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3066 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3067 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003068 } else if ("month_soft".equals(fake)) {
3069 plans.add(SubscriptionPlan.Builder
3070 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3071 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3072 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3073 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003074 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3075 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3076 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3077 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3078 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003079 plans.add(SubscriptionPlan.Builder
3080 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3081 .setTitle("G-Mobile, Throttled after limit")
3082 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3083 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3084 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3085 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3086 .build());
3087 plans.add(SubscriptionPlan.Builder
3088 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3089 .setTitle("G-Mobile, No data connection after limit")
3090 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3091 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3092 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3093 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3094 .build());
3095
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003096 } else if ("month_over".equals(fake)) {
3097 plans.add(SubscriptionPlan.Builder
3098 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3099 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3100 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3101 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3102 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3103 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3104 .build());
3105 plans.add(SubscriptionPlan.Builder
3106 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3107 .setTitle("G-Mobile, Throttled after limit")
3108 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3109 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3110 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3111 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3112 .build());
3113 plans.add(SubscriptionPlan.Builder
3114 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3115 .setTitle("G-Mobile, No data connection after limit")
3116 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3117 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3118 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3119 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3120 .build());
3121
Jeff Sharkey53313d72017-07-13 16:47:32 -06003122 } else if ("month_none".equals(fake)) {
3123 plans.add(SubscriptionPlan.Builder
3124 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3125 .setTitle("G-Mobile")
3126 .build());
3127 } else if ("prepaid".equals(fake)) {
3128 plans.add(SubscriptionPlan.Builder
3129 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3130 ZonedDateTime.now().plusDays(10))
3131 .setTitle("G-Mobile")
3132 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3133 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3134 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3135 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3136 .build());
3137 } else if ("prepaid_crazy".equals(fake)) {
3138 plans.add(SubscriptionPlan.Builder
3139 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3140 ZonedDateTime.now().plusDays(10))
3141 .setTitle("G-Mobile Anytime")
3142 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3143 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3144 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3145 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3146 .build());
3147 plans.add(SubscriptionPlan.Builder
3148 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3149 ZonedDateTime.now().plusDays(20))
3150 .setTitle("G-Mobile Nickel Nights")
3151 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003152 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3153 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003154 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3155 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3156 .build());
3157 plans.add(SubscriptionPlan.Builder
3158 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3159 ZonedDateTime.now().plusDays(20))
3160 .setTitle("G-Mobile Bonus 3G")
3161 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003162 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003163 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3164 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3165 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3166 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003167 } else if ("unlimited".equals(fake)) {
3168 plans.add(SubscriptionPlan.Builder
3169 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3170 ZonedDateTime.now().plusDays(10))
3171 .setTitle("G-Mobile Awesome")
3172 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3173 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3174 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3175 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3176 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003177 }
3178 return plans.toArray(new SubscriptionPlan[plans.size()]);
3179 }
3180
Jeff Sharkey4635f102017-09-01 11:27:13 -06003181 synchronized (mNetworkPoliciesSecondLock) {
3182 // Only give out plan details to the package that defined them,
3183 // so that we don't risk leaking plans between apps. We always
3184 // let in core system components (like the Settings app).
3185 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3186 if (Objects.equals(ownerPackage, callingPackage)
3187 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3188 return mSubscriptionPlans.get(subId);
3189 } else {
3190 Log.w(TAG, "Not returning plans because caller " + callingPackage
3191 + " doesn't match owner " + ownerPackage);
3192 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003193 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003194 }
3195 }
3196
3197 @Override
3198 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3199 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3200
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003201 for (SubscriptionPlan plan : plans) {
3202 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003203 }
3204
3205 final long token = Binder.clearCallingIdentity();
3206 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003207 synchronized (mUidRulesFirstLock) {
3208 synchronized (mNetworkPoliciesSecondLock) {
3209 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003210 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003211
Jeff Sharkey146bb332018-04-18 15:42:57 -06003212 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3213 if (subscriberId != null) {
3214 ensureActiveMobilePolicyAL(subId, subscriberId);
3215 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3216 } else {
3217 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3218 }
3219
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003220 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003221 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003222 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003223
3224 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3225 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3226 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3227 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003228 } finally {
3229 Binder.restoreCallingIdentity(token);
3230 }
3231 }
3232
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003233 /**
3234 * Only visible for testing purposes. This doesn't give any access to
3235 * existing plans; it simply lets the debug package define new plans.
3236 */
3237 void setSubscriptionPlansOwner(int subId, String packageName) {
3238 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3239 }
3240
Jeff Sharkey53313d72017-07-13 16:47:32 -06003241 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003242 public String getSubscriptionPlansOwner(int subId) {
3243 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3244 throw new SecurityException();
3245 }
3246
3247 synchronized (mNetworkPoliciesSecondLock) {
3248 return mSubscriptionPlansOwner.get(subId);
3249 }
3250 }
3251
3252 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003253 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3254 long timeoutMillis, String callingPackage) {
3255 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3256
3257 // We can only override when carrier told us about plans
3258 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003259 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3260 if (plan == null
3261 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003262 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003263 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003264 }
3265 }
3266
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003267 // Only allow overrides when feature is enabled. However, we always
3268 // allow disabling of overrides for safety reasons.
3269 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3270 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3271 if (overrideEnabled || overrideValue == 0) {
3272 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3273 overrideMask, overrideValue, subId));
3274 if (timeoutMillis > 0) {
3275 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3276 overrideMask, 0, subId), timeoutMillis);
3277 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003278 }
3279 }
3280
3281 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003282 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003283 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003284
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003285 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3286
Dianne Hackborn497175b2014-07-01 12:56:08 -07003287 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003288 for (String arg : args) {
3289 argSet.add(arg);
3290 }
3291
Felipe Lemef0823852016-06-08 13:43:08 -07003292 synchronized (mUidRulesFirstLock) {
3293 synchronized (mNetworkPoliciesSecondLock) {
3294 if (argSet.contains("--unsnooze")) {
3295 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3296 mNetworkPolicy.valueAt(i).clearSnooze();
3297 }
3298
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003299 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003300
3301 fout.println("Cleared snooze timestamps");
3302 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003303 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003304
Felipe Lemef0823852016-06-08 13:43:08 -07003305 fout.print("System ready: "); fout.println(mSystemReady);
3306 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3307 fout.print("Restrict power: "); fout.println(mRestrictPower);
3308 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003309 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3310
3311 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003312 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003313 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003314 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3315 fout.println(mNetworkPolicy.valueAt(i).toString());
3316 }
3317 fout.decreaseIndent();
3318
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003319 fout.println();
3320 fout.println("Subscription plans:");
3321 fout.increaseIndent();
3322 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3323 final int subId = mSubscriptionPlans.keyAt(i);
3324 fout.println("Subscriber ID " + subId + ":");
3325 fout.increaseIndent();
3326 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3327 if (!ArrayUtils.isEmpty(plans)) {
3328 for (SubscriptionPlan plan : plans) {
3329 fout.println(plan);
3330 }
3331 }
3332 fout.decreaseIndent();
3333 }
3334 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003335
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003336 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003337 fout.println("Active subscriptions:");
3338 fout.increaseIndent();
3339 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3340 final int subId = mSubIdToSubscriberId.keyAt(i);
3341 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3342
3343 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3344 }
3345 fout.decreaseIndent();
3346
3347 fout.println();
3348 fout.println("Merged subscriptions: "
3349 + Arrays.toString(NetworkIdentity.scrubSubscriberId(mMergedSubscriberIds)));
3350
3351 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003352 fout.println("Policy for UIDs:");
3353 fout.increaseIndent();
3354 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003355 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003356 final int uid = mUidPolicy.keyAt(i);
3357 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003358 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003359 fout.print(uid);
3360 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003361 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003362 fout.println();
3363 }
3364 fout.decreaseIndent();
3365
3366 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3367 if (size > 0) {
3368 fout.println("Power save whitelist (except idle) app ids:");
3369 fout.increaseIndent();
3370 for (int i = 0; i < size; i++) {
3371 fout.print("UID=");
3372 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3373 fout.print(": ");
3374 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3375 fout.println();
3376 }
3377 fout.decreaseIndent();
3378 }
3379
3380 size = mPowerSaveWhitelistAppIds.size();
3381 if (size > 0) {
3382 fout.println("Power save whitelist app ids:");
3383 fout.increaseIndent();
3384 for (int i = 0; i < size; i++) {
3385 fout.print("UID=");
3386 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3387 fout.print(": ");
3388 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3389 fout.println();
3390 }
3391 fout.decreaseIndent();
3392 }
3393
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003394 size = mAppIdleTempWhitelistAppIds.size();
3395 if (size > 0) {
3396 fout.println("App idle whitelist app ids:");
3397 fout.increaseIndent();
3398 for (int i = 0; i < size; i++) {
3399 fout.print("UID=");
3400 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3401 fout.print(": ");
3402 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3403 fout.println();
3404 }
3405 fout.decreaseIndent();
3406 }
3407
Felipe Lemef0823852016-06-08 13:43:08 -07003408 size = mDefaultRestrictBackgroundWhitelistUids.size();
3409 if (size > 0) {
3410 fout.println("Default restrict background whitelist uids:");
3411 fout.increaseIndent();
3412 for (int i = 0; i < size; i++) {
3413 fout.print("UID=");
3414 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3415 fout.println();
3416 }
3417 fout.decreaseIndent();
3418 }
3419
3420 size = mRestrictBackgroundWhitelistRevokedUids.size();
3421 if (size > 0) {
3422 fout.println("Default restrict background whitelist uids revoked by users:");
3423 fout.increaseIndent();
3424 for (int i = 0; i < size; i++) {
3425 fout.print("UID=");
3426 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3427 fout.println();
3428 }
3429 fout.decreaseIndent();
3430 }
3431
3432 final SparseBooleanArray knownUids = new SparseBooleanArray();
3433 collectKeys(mUidState, knownUids);
3434 collectKeys(mUidRules, knownUids);
3435
3436 fout.println("Status for all known UIDs:");
3437 fout.increaseIndent();
3438 size = knownUids.size();
3439 for (int i = 0; i < size; i++) {
3440 final int uid = knownUids.keyAt(i);
3441 fout.print("UID=");
3442 fout.print(uid);
3443
3444 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3445 fout.print(" state=");
3446 fout.print(state);
3447 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3448 fout.print(" (fg)");
3449 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003450 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003451 ? " (fg svc)" : " (bg)");
3452 }
3453
3454 final int uidRules = mUidRules.get(uid, RULE_NONE);
3455 fout.print(" rules=");
3456 fout.print(uidRulesToString(uidRules));
3457 fout.println();
3458 }
3459 fout.decreaseIndent();
3460
3461 fout.println("Status for just UIDs with rules:");
3462 fout.increaseIndent();
3463 size = mUidRules.size();
3464 for (int i = 0; i < size; i++) {
3465 final int uid = mUidRules.keyAt(i);
3466 fout.print("UID=");
3467 fout.print(uid);
3468 final int uidRules = mUidRules.get(uid, RULE_NONE);
3469 fout.print(" rules=");
3470 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003471 fout.println();
3472 }
3473 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003474
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003475 fout.println("Admin restricted uids for metered data:");
3476 fout.increaseIndent();
3477 size = mMeteredRestrictedUids.size();
3478 for (int i = 0; i < size; ++i) {
3479 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3480 fout.println(mMeteredRestrictedUids.valueAt(i));
3481 }
3482 fout.decreaseIndent();
3483
Makoto Onuki49392d32018-04-11 13:51:02 -07003484 fout.println();
3485 mStatLogger.dump(fout);
3486
Sudheer Shanka352dc572017-09-22 17:09:38 -07003487 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003488 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003489 }
3490 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003491
3492 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003493 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003494 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003495 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003496 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003497 }
3498
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003499 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003500 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003501 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003502 return isUidStateForeground(
3503 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003504 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003505 }
3506
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003507 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003508 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003509 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003510 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003511 }
3512
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003513 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003514 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003515 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3516 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3517 }
3518
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003519 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003520 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003521 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003522 }
3523
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003524 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003525 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003526 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
Amith Yamasanid78542b2019-02-19 09:57:32 -08003527 * {@link #updateRulesForPowerRestrictionsUL(int)}. Returns true if the state was updated.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003528 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003529 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003530 private boolean updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003531 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3532 try {
3533 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3534 if (oldUidState != uidState) {
3535 // state changed, push updated rules
3536 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003537 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3538 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3539 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003540 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003541 if (mDeviceIdleMode) {
3542 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003543 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003544 if (mRestrictPower) {
3545 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003546 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003547 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003548 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003549 return true;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003550 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003551 } finally {
3552 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003553 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003554 return false;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003555 }
3556
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003557 @GuardedBy("mUidRulesFirstLock")
Amith Yamasanid78542b2019-02-19 09:57:32 -08003558 private boolean removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003559 final int index = mUidState.indexOfKey(uid);
3560 if (index >= 0) {
3561 final int oldUidState = mUidState.valueAt(index);
3562 mUidState.removeAt(index);
3563 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003564 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003565 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003566 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003567 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003568 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003569 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003570 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003571 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003572 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasanid78542b2019-02-19 09:57:32 -08003573 return true;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003574 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003575 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08003576 return false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003577 }
3578
Felipe Lemef28983d2016-03-25 12:18:23 -07003579 // adjust stats accounting based on foreground status
3580 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003581 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3582 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3583 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3584 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003585 try {
3586 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003587 } finally {
3588 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003589 }
3590 }
3591
Sudheer Shankac9d94072017-02-22 22:13:55 +00003592 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3593 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003594 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003595 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003596 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003597 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003598 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003599 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003600 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003601 }
3602
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003603 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003604 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003605 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3606 try {
3607 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3608 mUidFirewallPowerSaveRules);
3609 } finally {
3610 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3611 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003612 }
3613
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003614 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003615 void updateRuleForRestrictPowerUL(int uid) {
3616 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003617 }
3618
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003619 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003620 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003621 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3622 try {
3623 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3624 mUidFirewallDozableRules);
3625 } finally {
3626 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3627 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003628 }
3629
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003630 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003631 void updateRuleForDeviceIdleUL(int uid) {
3632 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003633 }
3634
Felipe Lemef28983d2016-03-25 12:18:23 -07003635 // NOTE: since both fw_dozable and fw_powersave uses the same map
3636 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003637 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003638 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003639 SparseIntArray rules) {
3640 if (enabled) {
3641 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003642 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003643 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003644 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003645 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003646 for (int ui = users.size() - 1; ui >= 0; ui--) {
3647 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003648 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3649 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3650 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3651 updateRulesForWhitelistedAppIds(uidRules,
3652 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003653 }
3654 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003655 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003656 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003657 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3658 }
3659 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003660 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003661 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003662 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003663 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003664 }
3665
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003666 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3667 final SparseBooleanArray whitelistedAppIds, int userId) {
3668 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3669 if (whitelistedAppIds.valueAt(i)) {
3670 final int appId = whitelistedAppIds.keyAt(i);
3671 final int uid = UserHandle.getUid(userId, appId);
3672 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3673 }
3674 }
3675 }
3676
3677 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003678 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3679 * mode, and app idle).
3680 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003681 * @param deviceIdleMode if true then we don't consider
3682 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3683 * whitelisted.
3684 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003685 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003686 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003687 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003688 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3689 || mPowerSaveWhitelistAppIds.get(appId);
3690 if (!deviceIdleMode) {
3691 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3692 }
3693 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003694 }
3695
Felipe Lemef28983d2016-03-25 12:18:23 -07003696 // NOTE: since both fw_dozable and fw_powersave uses the same map
3697 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003698 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003699 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003700 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003701 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003702 chain == FIREWALL_CHAIN_DOZABLE);
3703 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003704 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003705 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003706 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003707 }
3708 }
3709 }
3710
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003711 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003712 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003713 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3714 try {
3715 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3716 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003717
Felipe Leme873a83a2016-09-07 11:34:10 -07003718 // Fully update the app idle firewall chain.
3719 final List<UserInfo> users = mUserManager.getUsers();
3720 for (int ui = users.size() - 1; ui >= 0; ui--) {
3721 UserInfo user = users.get(ui);
3722 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3723 for (int uid : idleUids) {
3724 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3725 // quick check: if this uid doesn't have INTERNET permission, it
3726 // doesn't have network access anyway, so it is a waste to mess
3727 // with it here.
3728 if (hasInternetPermissions(uid)) {
3729 uidRules.put(uid, FIREWALL_RULE_DENY);
3730 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003731 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003732 }
3733 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003734
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003735 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003736 } finally {
3737 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3738 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003739 }
3740
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003741 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003742 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003743 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003744
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003745 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3746 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3747 }
3748 try {
3749 int appId = UserHandle.getAppId(uid);
3750 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3751 && !isUidForegroundOnRestrictPowerUL(uid)) {
3752 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003753 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003754 } else {
3755 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003756 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003757 }
3758 } finally {
3759 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003760 }
3761 }
3762
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003763 /**
3764 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3765 * changed.
3766 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003767 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003768 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003769 boolean paroled = mUsageStats.isAppIdleParoleOn();
3770 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003771 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003772
3773 int ruleCount = mUidFirewallStandbyRules.size();
3774 for (int i = 0; i < ruleCount; i++) {
3775 int uid = mUidFirewallStandbyRules.keyAt(i);
3776 int oldRules = mUidRules.get(uid);
3777 if (enableChain) {
3778 // Chain wasn't enabled before and the other power-related
3779 // chains are whitelists, so we can clear the
3780 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3781 // the effective rules result in blocking network access.
3782 oldRules &= MASK_METERED_NETWORKS;
3783 } else {
3784 // Skip if it had no restrictions to begin with
3785 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3786 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003787 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3788 if (newUidRules == RULE_NONE) {
3789 mUidRules.delete(uid);
3790 } else {
3791 mUidRules.put(uid, newUidRules);
3792 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003793 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003794 }
3795
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003796 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003797 * Update rules that might be changed by {@link #mRestrictBackground},
3798 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003799 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003800 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003801 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003802 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3803 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3804 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3805 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003806 try {
Felipe Leme09700462016-09-08 09:33:48 -07003807 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003808 updateRulesForRestrictPowerUL();
3809 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003810
Felipe Leme873a83a2016-09-07 11:34:10 -07003811 // If the set of restricted networks may have changed, re-evaluate those.
3812 if (restrictedNetworksChanged) {
3813 normalizePoliciesNL();
3814 updateNetworkRulesNL();
3815 }
3816 } finally {
3817 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003818 }
3819 }
3820
Felipe Leme09700462016-09-08 09:33:48 -07003821 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003822 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003823 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003824 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3825 try {
3826 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003827 updateRulesForPowerSaveUL();
3828 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3829 } finally {
3830 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3831 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003832 }
3833
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003834 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003835 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003836 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3837 try {
3838 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3839 } finally {
3840 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3841 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003842 }
3843
3844 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3845 private static final int TYPE_RESTRICT_POWER = 2;
3846 @Retention(RetentionPolicy.SOURCE)
3847 @IntDef(flag = false, value = {
3848 TYPE_RESTRICT_BACKGROUND,
3849 TYPE_RESTRICT_POWER,
3850 })
3851 public @interface RestrictType {
3852 }
3853
3854 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003855 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003856 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003857 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3858 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3859 }
3860 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003861 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003862
3863 final PackageManager pm = mContext.getPackageManager();
3864 final List<UserInfo> users;
3865 final List<ApplicationInfo> apps;
3866
3867 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3868 try {
3869 users = mUserManager.getUsers();
3870 } finally {
3871 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3872 }
3873 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3874 try {
3875 apps = pm.getInstalledApplications(
3876 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3877 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3878 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3879 } finally {
3880 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3881 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003882
Felipe Leme873a83a2016-09-07 11:34:10 -07003883 final int usersSize = users.size();
3884 final int appsSize = apps.size();
3885 for (int i = 0; i < usersSize; i++) {
3886 final UserInfo user = users.get(i);
3887 for (int j = 0; j < appsSize; j++) {
3888 final ApplicationInfo app = apps.get(j);
3889 final int uid = UserHandle.getUid(user.id, app.uid);
3890 switch (type) {
3891 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003892 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003893 break;
3894 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003895 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003896 break;
3897 default:
3898 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3899 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003900 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003901 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003902 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003903 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003904 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003905 }
3906
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003907 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003908 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003909 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003910 final int numUsers = users.size();
3911 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003912 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003913 int uid = UserHandle.getUid(user.id, appId);
3914 // Update external firewall rules.
3915 updateRuleForAppIdleUL(uid);
3916 updateRuleForDeviceIdleUL(uid);
3917 updateRuleForRestrictPowerUL(uid);
3918 // Update internal rules.
3919 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003920 }
3921 }
3922
Felipe Leme70c57c22016-03-29 10:45:13 -07003923 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3924 // methods below could be merged into a isUidValidForRules() method.
3925 private boolean isUidValidForBlacklistRules(int uid) {
3926 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003927 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003928 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003929 return true;
3930 }
3931
3932 return false;
3933 }
3934
Felipe Leme70c57c22016-03-29 10:45:13 -07003935 private boolean isUidValidForWhitelistRules(int uid) {
3936 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3937 }
3938
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003939 /**
3940 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3941 * power saving restrictions may still apply.
3942 */
3943 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003944 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003945 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3946
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003947 synchronized (mUidRulesFirstLock) {
3948 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3949 // No change.
3950 return;
3951 }
3952
3953 final long token = Binder.clearCallingIdentity();
3954 try {
3955 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3956 if (shouldWhitelist) {
3957 mAppIdleTempWhitelistAppIds.put(uid, true);
3958 } else {
3959 mAppIdleTempWhitelistAppIds.delete(uid);
3960 }
3961 updateRuleForAppIdleUL(uid);
3962 updateRulesForPowerRestrictionsUL(uid);
3963 } finally {
3964 Binder.restoreCallingIdentity(token);
3965 }
3966 }
3967 }
3968
3969 /** Return the list of UIDs currently in the app idle whitelist. */
3970 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003971 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003972 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3973
3974 synchronized (mUidRulesFirstLock) {
3975 final int len = mAppIdleTempWhitelistAppIds.size();
3976 int[] uids = new int[len];
3977 for (int i = 0; i < len; ++i) {
3978 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
3979 }
3980 return uids;
3981 }
3982 }
3983
3984 /** Returns if the UID is currently considered idle. */
3985 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003986 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003987 synchronized (mUidRulesFirstLock) {
3988 if (mAppIdleTempWhitelistAppIds.get(uid)) {
3989 // UID is temporarily whitelisted.
3990 return false;
3991 }
3992 }
3993
Amith Yamasani15e472352015-04-24 19:06:07 -07003994 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3995 final int userId = UserHandle.getUserId(uid);
3996
songjinshi0655edd2016-05-18 19:55:32 +08003997 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003998 for (String packageName : packages) {
3999 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
4000 return false;
4001 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004002 }
4003 }
4004 return true;
4005 }
4006
4007 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08004008 * Checks if an uid has INTERNET permissions.
4009 * <p>
4010 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004011 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004012 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004013 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004014 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004015 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004016 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004017 }
4018 } catch (RemoteException e) {
4019 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004020 return true;
4021 }
4022
4023 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004024 * Clears all state - internal and external - associated with an UID.
4025 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004026 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004027 private void onUidDeletedUL(int uid) {
4028 // First cleanup in-memory state synchronously...
4029 mUidRules.delete(uid);
4030 mUidPolicy.delete(uid);
4031 mUidFirewallStandbyRules.delete(uid);
4032 mUidFirewallDozableRules.delete(uid);
4033 mUidFirewallPowerSaveRules.delete(uid);
4034 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4035 mPowerSaveWhitelistAppIds.delete(uid);
4036 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004037 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004038
4039 // ...then update iptables asynchronously.
4040 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4041 }
4042
4043 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004044 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004045 *
Felipe Leme781ba142016-05-09 16:24:48 -07004046 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004047 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004048 * <li>Doze mode
4049 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004050 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004051 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004052 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004053 *
4054 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004055 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004056 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004057 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004058 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004059 updateRuleForDeviceIdleUL(uid);
4060 updateRuleForAppIdleUL(uid);
4061 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004062
4063 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004064 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004065
4066 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004067 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004068 }
4069
Felipe Leme70c57c22016-03-29 10:45:13 -07004070 /**
4071 * Applies network rules to bandwidth controllers based on process state and user-defined
4072 * restrictions (blacklist / whitelist).
4073 *
4074 * <p>
4075 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4076 * networks:
4077 * <ul>
4078 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4079 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4080 * also blacklisted.
4081 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004082 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004083 * <ul>
4084 *
4085 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4086 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4087 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4088 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004089 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004090 * {@link INetworkManagementService}, but this method should also be called in events (like
4091 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4092 * following rules should also be applied:
4093 *
4094 * <ul>
4095 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4096 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4097 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4098 * {@code bw_penalty_box}.
4099 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4100 * </ul>
4101 *
4102 * <p>For optimization, the rules are only applied on user apps that have internet access
4103 * permission, since there is no need to change the {@code iptables} rule if the app does not
4104 * have permission to use the internet.
4105 *
4106 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004107 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004108 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004109 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004110 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4111 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4112 "updateRulesForDataUsageRestrictionsUL: " + uid);
4113 }
4114 try {
4115 updateRulesForDataUsageRestrictionsULInner(uid);
4116 } finally {
4117 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4118 }
4119 }
4120
4121 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004122 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004123 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004124 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004125 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004126
Dianne Hackborn497175b2014-07-01 12:56:08 -07004127 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004128 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004129 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004130 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004131
Felipe Leme781ba142016-05-09 16:24:48 -07004132 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004133 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004134 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4135 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004136
Felipe Leme70c57c22016-03-29 10:45:13 -07004137 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004138 if (isRestrictedByAdmin) {
4139 newRule = RULE_REJECT_METERED;
4140 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004141 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4142 newRule = RULE_TEMPORARY_ALLOW_METERED;
4143 } else if (isWhitelisted) {
4144 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004145 }
4146 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004147 if (isBlacklisted) {
4148 newRule = RULE_REJECT_METERED;
4149 } else if (mRestrictBackground && isWhitelisted) {
4150 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004151 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004152 }
Felipe Leme781ba142016-05-09 16:24:48 -07004153 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004154
Felipe Lemef28983d2016-03-25 12:18:23 -07004155 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004156 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004157 + ": isForeground=" +isForeground
4158 + ", isBlacklisted=" + isBlacklisted
4159 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004160 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004161 + ", oldRule=" + uidRulesToString(oldRule)
4162 + ", newRule=" + uidRulesToString(newRule)
4163 + ", newUidRules=" + uidRulesToString(newUidRules)
4164 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004165 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004166
Felipe Leme46c4fc32016-05-04 09:21:43 -07004167 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004168 mUidRules.delete(uid);
4169 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004170 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004171 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004172
Felipe Leme70c57c22016-03-29 10:45:13 -07004173 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004174 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004175 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004176 // Temporarily whitelist foreground app, removing from blacklist if necessary
4177 // (since bw_penalty_box prevails over bw_happy_box).
4178
4179 setMeteredNetworkWhitelist(uid, true);
4180 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4181 // but ideally it should be just:
4182 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004183 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004184 setMeteredNetworkBlacklist(uid, false);
4185 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004186 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004187 // Remove temporary whitelist from app that is not on foreground anymore.
4188
4189 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4190 // but ideally they should be just:
4191 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4192 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004193 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004194 setMeteredNetworkWhitelist(uid, false);
4195 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004196 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004197 setMeteredNetworkBlacklist(uid, true);
4198 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004199 } else if (hasRule(newRule, RULE_REJECT_METERED)
4200 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004201 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004202 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004203 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004204 // Since blacklist prevails over whitelist, we need to handle the special case
4205 // where app is whitelisted and blacklisted at the same time (although such
4206 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004207 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004208 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004209 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4210 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004211 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004212 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004213 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004214 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004215 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4216 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004217 + ", whitelisted=" + isWhitelisted
4218 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004219 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004220 + ", newRule=" + uidRulesToString(newUidRules)
4221 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004222 }
Felipe Leme781ba142016-05-09 16:24:48 -07004223
Sudheer Shankac9d94072017-02-22 22:13:55 +00004224 // Dispatch changed rule to existing listeners.
4225 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004226 }
4227 }
4228
4229 /**
4230 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4231 * listeners in case of change.
4232 * <p>
4233 * There are 3 power-related rules that affects whether an app has background access on
4234 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4235 * restriction, it's added to the equivalent firewall chain:
4236 * <ul>
4237 * <li>App is idle: {@code fw_standby} firewall chain.
4238 * <li>Device is idle: {@code fw_dozable} firewall chain.
4239 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4240 * </ul>
4241 * <p>
4242 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4243 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4244 * <p>
4245 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4246 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004247 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004248 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004249 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4250
Sudheer Shankac9d94072017-02-22 22:13:55 +00004251 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004252
Sudheer Shankac9d94072017-02-22 22:13:55 +00004253 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004254 mUidRules.delete(uid);
4255 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004256 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004257 }
4258 }
4259
4260 /**
4261 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4262 *
4263 * @param uid the uid of the app to update rules for
4264 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4265 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4266 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004267 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004268 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004269 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004270 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4271 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4272 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4273 + (paroled ? "P" : "-"));
4274 }
4275 try {
4276 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4277 } finally {
4278 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4279 }
4280 }
4281
4282 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004283 if (!isUidValidForBlacklistRules(uid)) {
4284 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004285 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004286 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004287
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004288 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004289 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004290 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004291
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004292 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004293 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4294 int newRule = RULE_NONE;
4295
4296 // First step: define the new rule based on user restrictions and foreground state.
4297
4298 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4299 // by considering the foreground and non-foreground states.
4300 if (isForeground) {
4301 if (restrictMode) {
4302 newRule = RULE_ALLOW_ALL;
4303 }
4304 } else if (restrictMode) {
4305 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4306 }
4307
4308 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4309
4310 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004311 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004312 + ", isIdle: " + isIdle
4313 + ", mRestrictPower: " + mRestrictPower
4314 + ", mDeviceIdleMode: " + mDeviceIdleMode
4315 + ", isForeground=" + isForeground
4316 + ", isWhitelisted=" + isWhitelisted
4317 + ", oldRule=" + uidRulesToString(oldRule)
4318 + ", newRule=" + uidRulesToString(newRule)
4319 + ", newUidRules=" + uidRulesToString(newUidRules)
4320 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4321 }
4322
Felipe Leme781ba142016-05-09 16:24:48 -07004323 // Second step: notify listeners if state changed.
4324 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004325 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004326 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004327 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004328 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4329 } else {
4330 // All scenarios should have been covered above
4331 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4332 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004333 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004334 + ", newRule=" + uidRulesToString(newUidRules)
4335 + ", oldRule=" + uidRulesToString(oldUidRules));
4336 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004337 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004338 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004339
Sudheer Shankac9d94072017-02-22 22:13:55 +00004340 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004341 }
4342
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004343 private class AppIdleStateChangeListener
4344 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4345
4346 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004347 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4348 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004349 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004350 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4351 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004352 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004353 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004354 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004355 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004356 }
4357 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004358 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004359 }
4360
4361 @Override
4362 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004363 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004364 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004365 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004366 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004367 }
4368 }
4369
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004370 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4371 if (listener != null) {
4372 try {
4373 listener.onUidRulesChanged(uid, uidRules);
4374 } catch (RemoteException ignored) {
4375 }
4376 }
4377 }
4378
4379 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4380 String[] meteredIfaces) {
4381 if (listener != null) {
4382 try {
4383 listener.onMeteredIfacesChanged(meteredIfaces);
4384 } catch (RemoteException ignored) {
4385 }
4386 }
4387 }
4388
4389 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4390 boolean restrictBackground) {
4391 if (listener != null) {
4392 try {
4393 listener.onRestrictBackgroundChanged(restrictBackground);
4394 } catch (RemoteException ignored) {
4395 }
4396 }
4397 }
4398
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004399 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4400 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004401 if (listener != null) {
4402 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004403 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004404 } catch (RemoteException ignored) {
4405 }
4406 }
4407 }
4408
Jeff Sharkey9252b342018-01-19 07:58:35 +09004409 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4410 int overrideMask, int overrideValue) {
4411 if (listener != null) {
4412 try {
4413 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4414 } catch (RemoteException ignored) {
4415 }
4416 }
4417 }
4418
Makoto Onuki8e777332017-03-28 11:25:47 -07004419 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004420 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004421 public boolean handleMessage(Message msg) {
4422 switch (msg.what) {
4423 case MSG_RULES_CHANGED: {
4424 final int uid = msg.arg1;
4425 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004426 final int length = mListeners.beginBroadcast();
4427 for (int i = 0; i < length; i++) {
4428 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4429 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004430 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004431 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004432 return true;
4433 }
4434 case MSG_METERED_IFACES_CHANGED: {
4435 final String[] meteredIfaces = (String[]) msg.obj;
4436 final int length = mListeners.beginBroadcast();
4437 for (int i = 0; i < length; i++) {
4438 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004439 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004440 }
4441 mListeners.finishBroadcast();
4442 return true;
4443 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004444 case MSG_LIMIT_REACHED: {
4445 final String iface = (String) msg.obj;
4446
Felipe Lemef0823852016-06-08 13:43:08 -07004447 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004448 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004449 // force stats update to make sure we have
4450 // numbers that caused alert to trigger.
4451 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004452
Felipe Lemef0823852016-06-08 13:43:08 -07004453 updateNetworkEnabledNL();
4454 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004455 }
4456 }
4457 return true;
4458 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004459 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4460 final boolean restrictBackground = msg.arg1 != 0;
4461 final int length = mListeners.beginBroadcast();
4462 for (int i = 0; i < length; i++) {
4463 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004464 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004465 }
4466 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004467 final Intent intent =
4468 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4469 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4470 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4471 return true;
4472 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004473 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004474 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004475 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004476 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004477 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004478 final int length = mListeners.beginBroadcast();
4479 for (int i = 0; i < length; i++) {
4480 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004481 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004482 }
4483 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004484 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4485 if (notifyApp.booleanValue()) {
4486 broadcastRestrictBackgroundChanged(uid, notifyApp);
4487 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004488 return true;
4489 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004490 case MSG_ADVISE_PERSIST_THRESHOLD: {
4491 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004492 // make sure stats are recorded frequently enough; we aim
4493 // for 2MB threshold for 2GB/month rules.
4494 final long persistThreshold = lowestRule / 1000;
4495 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004496 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004497 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004498 case MSG_UPDATE_INTERFACE_QUOTA: {
4499 removeInterfaceQuota((String) msg.obj);
4500 // int params need to be stitched back into a long
4501 setInterfaceQuota((String) msg.obj,
4502 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4503 return true;
4504 }
4505 case MSG_REMOVE_INTERFACE_QUOTA: {
4506 removeInterfaceQuota((String) msg.obj);
4507 return true;
4508 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004509 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4510 resetUidFirewallRules(msg.arg1);
4511 return true;
4512 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004513 case MSG_SUBSCRIPTION_OVERRIDE: {
4514 final int overrideMask = msg.arg1;
4515 final int overrideValue = msg.arg2;
4516 final int subId = (int) msg.obj;
4517 final int length = mListeners.beginBroadcast();
4518 for (int i = 0; i < length; i++) {
4519 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4520 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4521 }
4522 mListeners.finishBroadcast();
4523 return true;
4524 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004525 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4526 final int userId = msg.arg1;
4527 final Set<String> packageNames = (Set<String>) msg.obj;
4528 setMeteredRestrictedPackagesInternal(packageNames, userId);
4529 return true;
4530 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004531 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4532 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4533 final boolean enabled = msg.arg1 != 0;
4534 setNetworkTemplateEnabledInner(template, enabled);
4535 return true;
4536 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004537 default: {
4538 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004539 }
4540 }
4541 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004542 };
4543
4544 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4545 @Override
4546 public boolean handleMessage(Message msg) {
4547 switch (msg.what) {
4548 case UID_MSG_STATE_CHANGED: {
4549 final int uid = msg.arg1;
4550 final int procState = msg.arg2;
4551 final long procStateSeq = (Long) msg.obj;
4552
4553 handleUidChanged(uid, procState, procStateSeq);
4554 return true;
4555 }
4556 case UID_MSG_GONE: {
4557 final int uid = msg.arg1;
4558 handleUidGone(uid);
4559 return true;
4560 }
4561 default: {
4562 return false;
4563 }
4564 }
4565 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004566 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004567
Makoto Onuki8e777332017-03-28 11:25:47 -07004568 void handleUidChanged(int uid, int procState, long procStateSeq) {
4569 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4570 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004571 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004572 synchronized (mUidRulesFirstLock) {
4573 // We received a uid state change callback, add it to the history so that it
4574 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004575 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004576 // Now update the network policy rules as per the updated uid state.
Amith Yamasanid78542b2019-02-19 09:57:32 -08004577 updated = updateUidStateUL(uid, procState);
Makoto Onuki8e777332017-03-28 11:25:47 -07004578 // Updating the network rules is done, so notify AMS about this.
4579 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4580 }
Amith Yamasanid78542b2019-02-19 09:57:32 -08004581 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4582 // called from the handler, so there's no multi-threading issue.
4583 if (updated) {
4584 updateNetworkStats(uid, isUidStateForeground(procState));
4585 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004586 } finally {
4587 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4588 }
4589 }
4590
4591 void handleUidGone(int uid) {
4592 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4593 try {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004594 boolean updated;
Makoto Onuki8e777332017-03-28 11:25:47 -07004595 synchronized (mUidRulesFirstLock) {
Amith Yamasanid78542b2019-02-19 09:57:32 -08004596 updated = removeUidStateUL(uid);
4597 }
4598 // Do this without the lock held. handleUidChanged() and handleUidGone() are
4599 // called from the handler, so there's no multi-threading issue.
4600 if (updated) {
4601 updateNetworkStats(uid, false);
Makoto Onuki8e777332017-03-28 11:25:47 -07004602 }
4603 } finally {
4604 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4605 }
4606 }
4607
Felipe Leme57e3d312016-08-23 14:42:52 -07004608 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4609 final PackageManager pm = mContext.getPackageManager();
4610 final String[] packages = pm.getPackagesForUid(uid);
4611 if (packages != null) {
4612 final int userId = UserHandle.getUserId(uid);
4613 for (String packageName : packages) {
4614 final Intent intent =
4615 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4616 intent.setPackage(packageName);
4617 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4618 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4619 }
4620 }
4621 }
4622
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004623 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4624 // long quotaBytes split up into two ints to fit in message
4625 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4626 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4627 }
4628
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004629 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004630 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004631 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004632 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004633 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004634 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004635 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004636 }
4637 }
4638
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004639 private void removeInterfaceQuotaAsync(String iface) {
4640 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4641 }
4642
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004643 private void removeInterfaceQuota(String iface) {
4644 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004645 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004646 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004647 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004648 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004649 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004650 }
4651 }
4652
Felipe Leme70c57c22016-03-29 10:45:13 -07004653 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4654 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004655 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004656 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004657 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004658 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4659 } catch (RemoteException e) {
4660 // ignored; service lives in system_server
4661 }
4662 }
4663
4664 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4665 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4666 try {
4667 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4668 } catch (IllegalStateException e) {
4669 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004670 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004671 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004672 }
4673 }
4674
Felipe Lemebc853dd2016-09-08 13:26:55 -07004675 private static final int CHAIN_TOGGLE_NONE = 0;
4676 private static final int CHAIN_TOGGLE_ENABLE = 1;
4677 private static final int CHAIN_TOGGLE_DISABLE = 2;
4678 @Retention(RetentionPolicy.SOURCE)
4679 @IntDef(flag = false, value = {
4680 CHAIN_TOGGLE_NONE,
4681 CHAIN_TOGGLE_ENABLE,
4682 CHAIN_TOGGLE_DISABLE
4683 })
4684 public @interface ChainToggleType {
4685 }
4686
4687 /**
4688 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004689 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004690 *
4691 * @param chain firewall chain.
4692 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4693 * @param toggle whether the chain should be enabled, disabled, or not changed.
4694 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004695 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004696 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004697 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004698 if (uidRules != null) {
4699 setUidFirewallRulesUL(chain, uidRules);
4700 }
4701 if (toggle != CHAIN_TOGGLE_NONE) {
4702 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4703 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004704 }
4705
Amith Yamasani15e472352015-04-24 19:06:07 -07004706 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004707 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4708 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4709 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004710 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004711 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004712 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004713 int size = uidRules.size();
4714 int[] uids = new int[size];
4715 int[] rules = new int[size];
4716 for(int index = size - 1; index >= 0; --index) {
4717 uids[index] = uidRules.keyAt(index);
4718 rules[index] = uidRules.valueAt(index);
4719 }
4720 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004721 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004722 } catch (IllegalStateException e) {
4723 Log.wtf(TAG, "problem setting firewall uid rules", e);
4724 } catch (RemoteException e) {
4725 // ignored; service lives in system_server
4726 }
4727 }
4728
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004729 /**
4730 * Add or remove a uid to the firewall blacklist for all network ifaces.
4731 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004732 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004733 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4734 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4735 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004736 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004737 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004738 if (chain == FIREWALL_CHAIN_DOZABLE) {
4739 mUidFirewallDozableRules.put(uid, rule);
4740 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4741 mUidFirewallStandbyRules.put(uid, rule);
4742 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4743 mUidFirewallPowerSaveRules.put(uid, rule);
4744 }
4745
4746 try {
4747 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004748 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004749 } catch (IllegalStateException e) {
4750 Log.wtf(TAG, "problem setting firewall uid rules", e);
4751 } catch (RemoteException e) {
4752 // ignored; service lives in system_server
4753 }
4754 } finally {
4755 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004756 }
4757 }
4758
4759 /**
4760 * Add or remove a uid to the firewall blacklist for all network ifaces.
4761 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004762 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004763 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004764 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4765 mFirewallChainStates.get(chain) == enable) {
4766 // All is the same, nothing to do.
4767 return;
4768 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004769 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004770 try {
4771 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004772 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004773 } catch (IllegalStateException e) {
4774 Log.wtf(TAG, "problem enable firewall chain", e);
4775 } catch (RemoteException e) {
4776 // ignored; service lives in system_server
4777 }
4778 }
4779
Felipe Leme03e95e22016-09-09 09:25:31 -07004780 /**
4781 * Resets all firewall rules associated with an UID.
4782 */
4783 private void resetUidFirewallRules(int uid) {
4784 try {
4785 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4786 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4787 mNetworkManager
4788 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4789 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4790 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4791 } catch (IllegalStateException e) {
4792 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4793 } catch (RemoteException e) {
4794 // ignored; service lives in system_server
4795 }
4796 }
4797
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004798 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004799 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004800 return getNetworkTotalBytes(template, start, end);
4801 }
4802
4803 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004804 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004805 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004806 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004807 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004808 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004809 }
4810 }
4811
4812 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4813 try {
4814 return mNetworkStats.getNetworkUidBytes(template, start, end);
4815 } catch (RuntimeException e) {
4816 Slog.w(TAG, "Failed to read network stats: " + e);
4817 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004818 }
4819 }
4820
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004821 private boolean isBandwidthControlEnabled() {
4822 final long token = Binder.clearCallingIdentity();
4823 try {
4824 return mNetworkManager.isBandwidthControlEnabled();
4825 } catch (RemoteException e) {
4826 // ignored; service lives in system_server
4827 return false;
4828 } finally {
4829 Binder.restoreCallingIdentity(token);
4830 }
4831 }
4832
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004833 private static Intent buildAllowBackgroundDataIntent() {
4834 return new Intent(ACTION_ALLOW_BACKGROUND);
4835 }
4836
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004837 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4838 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004839 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4840 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4841 return intent;
4842 }
4843
4844 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4845 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4846 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004847 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4848 return intent;
4849 }
4850
Wei Liu546cb772016-07-21 16:19:01 -07004851 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004852 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004853 intent.setComponent(ComponentName.unflattenFromString(
4854 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004855 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4856 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4857 return intent;
4858 }
4859
Wei Liu546cb772016-07-21 16:19:01 -07004860 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004861 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004862 intent.setComponent(ComponentName.unflattenFromString(
4863 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004864 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4865 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4866 return intent;
4867 }
4868
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004869 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004870 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004871 mHandler.getLooper().getQueue().addIdleHandler(handler);
4872 }
4873
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004874 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004875 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004876 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004877 mRestrictBackgroundPowerState = result;
4878
4879 boolean restrictBackground = result.batterySaverEnabled;
4880 boolean shouldInvokeRestrictBackground;
4881 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4882 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4883
4884 if (result.globalBatterySaverEnabled) {
4885 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4886 // turn it on.
4887 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4888 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4889 localRestrictBgChangedInBsm = false;
4890 } else {
4891 // Try to restore the restrictBackground if it doesn't change in bsm
4892 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4893 restrictBackground = mRestrictBackgroundBeforeBsm;
4894 }
4895
4896 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004897 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004898 }
4899
4900 // Change it at last so setRestrictBackground() won't affect this variable
4901 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4902 }
4903
Jeff Sharkey1b861272011-05-22 00:34:52 -07004904 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4905 final int size = source.size();
4906 for (int i = 0; i < size; i++) {
4907 target.put(source.keyAt(i), true);
4908 }
4909 }
4910
Stuart Scottf1fb3972015-04-02 18:00:02 -07004911 @Override
4912 public void factoryReset(String subscriber) {
4913 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4914
Stuart Scotte3e314d2015-04-20 14:07:45 -07004915 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4916 return;
4917 }
4918
Stuart Scottf1fb3972015-04-02 18:00:02 -07004919 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004920 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004921 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4922 for (NetworkPolicy policy : policies) {
4923 if (policy.template.equals(template)) {
4924 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4925 policy.inferred = false;
4926 policy.clearSnooze();
4927 }
4928 }
4929 setNetworkPolicies(policies);
4930
4931 // Turn restrict background data off
4932 setRestrictBackground(false);
4933
Stuart Scotte3e314d2015-04-20 14:07:45 -07004934 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4935 // Remove app's "restrict background data" flag
4936 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4937 setUidPolicy(uid, POLICY_NONE);
4938 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004939 }
4940 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004941
Sudheer Shankab8f23162017-08-04 13:30:10 -07004942 @Override
4943 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004944 final long startTime = mStatLogger.getTime();
4945
Sudheer Shankab8f23162017-08-04 13:30:10 -07004946 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004947 final int uidRules;
4948 final boolean isBackgroundRestricted;
4949 synchronized (mUidRulesFirstLock) {
4950 uidRules = mUidRules.get(uid, RULE_NONE);
4951 isBackgroundRestricted = mRestrictBackground;
4952 }
junyulai05986c62018-08-07 19:50:45 +08004953 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
4954 isBackgroundRestricted, mLogger);
4955
4956 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4957
4958 return ret;
4959 }
4960
4961 private static boolean isSystem(int uid) {
4962 return uid < Process.FIRST_APPLICATION_UID;
4963 }
4964
4965 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
4966 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
4967 final int reason;
4968 // Networks are never blocked for system components
4969 if (isSystem(uid)) {
4970 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004971 }
junyulai05986c62018-08-07 19:50:45 +08004972 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
4973 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004974 }
junyulai05986c62018-08-07 19:50:45 +08004975 else if (!isNetworkMetered) {
4976 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004977 }
junyulai05986c62018-08-07 19:50:45 +08004978 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
4979 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004980 }
junyulai05986c62018-08-07 19:50:45 +08004981 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4982 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004983 }
junyulai05986c62018-08-07 19:50:45 +08004984 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4985 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004986 }
junyulai05986c62018-08-07 19:50:45 +08004987 else if (isBackgroundRestricted) {
4988 reason = NTWK_BLOCKED_BG_RESTRICT;
4989 }
4990 else {
4991 reason = NTWK_ALLOWED_DEFAULT;
4992 }
4993
4994 final boolean blocked;
4995 switch(reason) {
4996 case NTWK_ALLOWED_DEFAULT:
4997 case NTWK_ALLOWED_NON_METERED:
4998 case NTWK_ALLOWED_TMP_WHITELIST:
4999 case NTWK_ALLOWED_WHITELIST:
5000 case NTWK_ALLOWED_SYSTEM:
5001 blocked = false;
5002 break;
5003 case NTWK_BLOCKED_POWER:
5004 case NTWK_BLOCKED_BLACKLIST:
5005 case NTWK_BLOCKED_BG_RESTRICT:
5006 blocked = true;
5007 break;
5008 default:
5009 throw new IllegalArgumentException();
5010 }
5011 if (logger != null) {
5012 logger.networkBlocked(uid, reason);
5013 }
5014
5015 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005016 }
5017
Felipe Lemed17fda42016-04-29 11:12:45 -07005018 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
5019
5020 @Override
5021 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005022 synchronized (mUidRulesFirstLock) {
5023 boolean changed = removeUserStateUL(userId, false);
5024 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005025 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005026 synchronized (mNetworkPoliciesSecondLock) {
5027 writePolicyAL();
5028 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005029 }
5030 }
5031 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005032
5033 /**
5034 * @return true if the given uid is restricted from doing networking on metered networks.
5035 */
5036 @Override
5037 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5038 final int uidRules;
5039 final boolean isBackgroundRestricted;
5040 synchronized (mUidRulesFirstLock) {
5041 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5042 isBackgroundRestricted = mRestrictBackground;
5043 }
5044 return isBackgroundRestricted
5045 && !hasRule(uidRules, RULE_ALLOW_METERED)
5046 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5047 }
5048
5049 /**
5050 * @return true if networking is blocked on the given interface for the given uid according
5051 * to current networking policies.
5052 */
5053 @Override
5054 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005055 final long startTime = mStatLogger.getTime();
5056
junyulai05986c62018-08-07 19:50:45 +08005057 final int uidRules;
5058 final boolean isBackgroundRestricted;
5059 synchronized (mUidRulesFirstLock) {
5060 uidRules = mUidRules.get(uid, RULE_NONE);
5061 isBackgroundRestricted = mRestrictBackground;
5062 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005063 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005064 synchronized (mNetworkPoliciesSecondLock) {
5065 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005066 }
junyulai05986c62018-08-07 19:50:45 +08005067 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5068 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005069
5070 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5071
5072 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005073 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005074
5075 @Override
5076 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5077 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005078 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005079 if (added) {
5080 mPowerSaveTempWhitelistAppIds.put(appId, true);
5081 } else {
5082 mPowerSaveTempWhitelistAppIds.delete(appId);
5083 }
5084 updateRulesForTempWhitelistChangeUL(appId);
5085 }
5086 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005087
5088 @Override
5089 public SubscriptionPlan getSubscriptionPlan(Network network) {
5090 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005091 final int subId = getSubIdLocked(network);
5092 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005093 }
5094 }
5095
5096 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005097 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5098 synchronized (mNetworkPoliciesSecondLock) {
5099 final int subId = findRelevantSubIdNL(template);
5100 return getPrimarySubscriptionPlanLocked(subId);
5101 }
5102 }
5103
5104 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005105 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005106 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005107 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005108 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005109 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005110 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005111 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5112 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5113 }
5114
5115 if (quotaType == QUOTA_TYPE_JOBS) {
5116 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5117 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5118 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5119 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5120 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5121 } else {
5122 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5123 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005124 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005125
5126 @Override
5127 public void onAdminDataAvailable() {
5128 mAdminDataAvailableLatch.countDown();
5129 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005130
5131 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005132 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5133 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5134 }
5135
5136 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005137 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5138 setMeteredRestrictedPackagesInternal(packageNames, userId);
5139 }
5140
5141 @Override
5142 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5143 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5144 userId, 0, packageNames).sendToTarget();
5145 }
5146 }
5147
5148 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5149 synchronized (mUidRulesFirstLock) {
5150 final Set<Integer> newRestrictedUids = new ArraySet<>();
5151 for (String packageName : packageNames) {
5152 final int uid = getUidForPackage(packageName, userId);
5153 if (uid >= 0) {
5154 newRestrictedUids.add(uid);
5155 }
5156 }
5157 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5158 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5159 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5160 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5161 }
5162 }
5163
5164 private int getUidForPackage(String packageName, int userId) {
5165 try {
5166 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5167 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5168 } catch (NameNotFoundException e) {
5169 return -1;
5170 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005171 }
5172
5173 private int parseSubId(NetworkState state) {
5174 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5175 int subId = INVALID_SUBSCRIPTION_ID;
5176 if (state != null && state.networkCapabilities != null
5177 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5178 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5179 if (spec instanceof StringNetworkSpecifier) {
5180 try {
5181 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5182 } catch (NumberFormatException e) {
5183 }
5184 }
5185 }
5186 return subId;
5187 }
5188
Andreas Gampea36dc622018-02-05 17:19:22 -08005189 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005190 private int getSubIdLocked(Network network) {
5191 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005192 }
5193
Andreas Gampea36dc622018-02-05 17:19:22 -08005194 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005195 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5196 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005197 if (!ArrayUtils.isEmpty(plans)) {
5198 for (SubscriptionPlan plan : plans) {
5199 if (plan.getCycleRule().isRecurring()) {
5200 // Recurring plans will always have an active cycle
5201 return plan;
5202 } else {
5203 // Non-recurring plans need manual test for active cycle
5204 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5205 if (cycle.contains(ZonedDateTime.now(mClock))) {
5206 return plan;
5207 }
5208 }
5209 }
5210 }
5211 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005212 }
5213
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005214 /**
5215 * This will only ever be called once - during device boot.
5216 */
5217 private void waitForAdminData() {
5218 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5219 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5220 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5221 }
5222 }
5223
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005224 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5225 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005226 if (!mNetworkManagerReady) {
5227 return;
5228 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005229 if (oldRestrictedUids == null) {
5230 for (int uid : newRestrictedUids) {
5231 updateRulesForDataUsageRestrictionsUL(uid);
5232 }
5233 return;
5234 }
5235 for (int uid : oldRestrictedUids) {
5236 if (!newRestrictedUids.contains(uid)) {
5237 updateRulesForDataUsageRestrictionsUL(uid);
5238 }
5239 }
5240 for (int uid : newRestrictedUids) {
5241 if (!oldRestrictedUids.contains(uid)) {
5242 updateRulesForDataUsageRestrictionsUL(uid);
5243 }
5244 }
5245 }
5246
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005247 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005248 private boolean isRestrictedByAdminUL(int uid) {
5249 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5250 UserHandle.getUserId(uid));
5251 return restrictedUids != null && restrictedUids.contains(uid);
5252 }
5253
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005254 private static boolean hasRule(int uidRules, int rule) {
5255 return (uidRules & rule) != 0;
5256 }
5257
Jeff Sharkey2e471452018-01-19 18:02:47 +09005258 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5259 return (val != null) ? val : new NetworkState[0];
5260 }
5261
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005262 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5263 String key, boolean defaultValue) {
5264 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5265 }
5266
Chris Wren193ae6b2017-03-31 15:17:11 -04005267 private class NotificationId {
5268 private final String mTag;
5269 private final int mId;
5270
5271 NotificationId(NetworkPolicy policy, int type) {
5272 mTag = buildNotificationTag(policy, type);
5273 mId = type;
5274 }
5275
5276 @Override
5277 public boolean equals(Object o) {
5278 if (this == o) return true;
5279 if (!(o instanceof NotificationId)) return false;
5280 NotificationId that = (NotificationId) o;
5281 return Objects.equals(mTag, that.mTag);
5282 }
5283
5284 @Override
5285 public int hashCode() {
5286 return Objects.hash(mTag);
5287 }
5288
5289 /**
5290 * Build unique tag that identifies an active {@link NetworkPolicy}
5291 * notification of a specific type, like {@link #TYPE_LIMIT}.
5292 */
5293 private String buildNotificationTag(NetworkPolicy policy, int type) {
5294 return TAG + ":" + policy.template.hashCode() + ":" + type;
5295 }
5296
5297 public String getTag() {
5298 return mTag;
5299 }
5300
5301 public int getId() {
5302 return mId;
5303 }
5304 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005305}