blob: ebb32090f493f2dfeb3f2baaaeefcd37ee20f763 [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;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060041import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090042import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey9252b342018-01-19 07:58:35 +090043import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070044import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070045import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070046import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070047import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070048import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080049import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070050import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
51import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070052import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070053import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
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;
102import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
103import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
104import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
106import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700107import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600108
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700109import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800110import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700111import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700112
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700113import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700114import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900115import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700116import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700117import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800118import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700119import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700120import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700121import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700122import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700123import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700124import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700125import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700126import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700127import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700128import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600129import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700130import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700131import android.content.Intent;
132import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700133import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700134import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700135import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700136import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700137import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700138import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700139import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600140import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700141import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700142import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700144import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700145import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700146import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600147import android.net.Network;
148import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700149import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600151import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700152import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600153import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900154import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700155import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700156import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700157import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900158import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600159import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700160import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700161import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700162import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700163import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import android.os.Environment;
165import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700166import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700167import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700168import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700169import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700170import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700171import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700172import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700173import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700174import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600175import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800176import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700177import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700178import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600179import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700180import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700181import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700182import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600183import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700184import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700185import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700186import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700187import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100188import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700189import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600190import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800191import android.telephony.SubscriptionManager;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600192import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600193import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700194import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400195import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700196import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700197import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700198import android.util.ArrayMap;
199import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700200import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900201import android.util.DataUnit;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600202import android.util.IntArray;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700203import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700204import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600205import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600206import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700207import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600208import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700209import android.util.SparseBooleanArray;
210import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900211import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700213
Jeff Sharkey497e4432011-06-14 17:27:29 -0700214import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700215import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800216import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400217import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500218import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700219import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800220import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800221import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600222import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700224import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600225import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700226import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700227import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700228import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700229import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800230import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600231
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600232import libcore.io.IoUtils;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600233import libcore.util.EmptyArray;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600234
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlSerializer;
237
238import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700239import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240import java.io.FileInputStream;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700244import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700245import java.lang.annotation.Retention;
246import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100247import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700248import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900249import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600250import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700251import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600252import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900253import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600255import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700256import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600257import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400258import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800259import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800260import java.util.concurrent.CountDownLatch;
261import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700262
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700263/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700264 * Service that maintains low-level network policy rules, using
265 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700266 * <p>
267 * Derives active rules by combining a given policy with other system status,
268 * and delivers to listeners, such as {@link ConnectivityManager}, for
269 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700270 *
271 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000272 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700273 * <ul>
274 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
275 * rules).
276 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
277 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000278 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
279 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700280 * </ul>
281 *
282 * <p>
283 * As such, methods that require synchronization have the following prefixes:
284 * <ul>
285 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
286 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000287 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
288 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700289 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700290 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700292 static final String TAG = NetworkPolicyLogger.TAG;
293 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
294 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700295
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900296 /**
297 * No opportunistic quota could be calculated from user data plan or data settings.
298 */
299 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
300
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 private static final int VERSION_INIT = 1;
302 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700303 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800304 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800305 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800306 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700307 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700308 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700309 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700310 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600311 private static final int VERSION_ADDED_CYCLE = 11;
312 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400315 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400317 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400319 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900320 @VisibleForTesting
321 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700322
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 private static final String TAG_POLICY_LIST = "policy-list";
324 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600325 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700326 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700327 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800328 private static final String TAG_WHITELIST = "whitelist";
329 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800330 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331
332 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700333 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
335 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700336 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600337 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
338 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
339 private static final String ATTR_CYCLE_START = "cycleStart";
340 private static final String ATTR_CYCLE_END = "cycleEnd";
341 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private static final String ATTR_WARNING_BYTES = "warningBytes";
343 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700344 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800345 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
346 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800347 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700348 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700349 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700350 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700351 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600352 private static final String ATTR_SUB_ID = "subId";
353 private static final String ATTR_TITLE = "title";
354 private static final String ATTR_SUMMARY = "summary";
355 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
356 private static final String ATTR_USAGE_BYTES = "usageBytes";
357 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600358 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800360 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800361 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800362 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800363 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700364 private static final String ACTION_SNOOZE_RAPID =
365 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700366
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800367 /**
368 * Indicates the maximum wait time for admin data to be available;
369 */
370 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
371
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600372 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
373 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
374 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
375 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
376
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700377 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700378 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800379 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800380 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700381 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700382 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
383 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700384 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700385 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900386 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800387 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700388 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700389
Makoto Onuki8e777332017-03-28 11:25:47 -0700390 private static final int UID_MSG_STATE_CHANGED = 100;
391 private static final int UID_MSG_GONE = 101;
392
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600393 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
394
Jeff Sharkey75279902011-05-24 18:39:45 -0700395 private final Context mContext;
396 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700397 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700398 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700399 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700400 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700401 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700402 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403
404 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700405 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700406 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800407 @GuardedBy("mUidRulesFirstLock")
408 private PowerSaveState mRestrictBackgroundPowerState;
409
410 // Store the status of restrict background before turning on battery saver.
411 // Used to restore mRestrictBackground when battery saver is turned off.
412 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700413
Sudheer Shanka543339f2017-07-28 15:18:07 -0700414 // Denotes the status of restrict background read from disk.
415 private boolean mLoadedRestrictBackground;
416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 // See main javadoc for instructions on how to use these locks.
418 final Object mUidRulesFirstLock = new Object();
419 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420
Felipe Lemef0823852016-06-08 13:43:08 -0700421 @GuardedBy("allLocks") volatile boolean mSystemReady;
422
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
Jeff Sharkey32566012014-12-02 18:30:14 -0800466 /**
467 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700468 * in power save mode, except device idle (doze) still applies.
469 * TODO: An int array might be sufficient
470 */
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700472 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
473
474 /**
475 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800476 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700477 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800478 */
Felipe Lemef0823852016-06-08 13:43:08 -0700479 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700480 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700481
Felipe Lemef0823852016-06-08 13:43:08 -0700482 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700483 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
484
Felipe Lemeb85a6372016-01-14 16:16:16 -0800485 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800486 * UIDs that have been initially white-listed by system to avoid restricted background.
487 */
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800489 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
490 new SparseBooleanArray();
491
492 /**
493 * UIDs that have been initially white-listed by system to avoid restricted background,
494 * but later revoked by user.
495 */
Felipe Lemef0823852016-06-08 13:43:08 -0700496 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800497 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
498 new SparseBooleanArray();
499
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700500 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700501 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800502 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700503 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700504 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800505 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700506
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700507 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700508 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400509 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700510
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700511 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800513 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700514
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600515 /** Map from network ID to last observed meteredness state */
516 @GuardedBy("mNetworkPoliciesSecondLock")
517 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900518 /** Map from network ID to last observed roaming state */
519 @GuardedBy("mNetworkPoliciesSecondLock")
520 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
521
Jeff Sharkey9252b342018-01-19 07:58:35 +0900522 /** Map from netId to subId as of last update */
523 @GuardedBy("mNetworkPoliciesSecondLock")
524 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
525
Jeff Sharkey146bb332018-04-18 15:42:57 -0600526 /** Map from subId to subscriberId as of last update */
527 @GuardedBy("mNetworkPoliciesSecondLock")
528 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
529 /** Set of all merged subscriberId as of last update */
530 @GuardedBy("mNetworkPoliciesSecondLock")
531 private String[] mMergedSubscriberIds = EmptyArray.STRING;
532
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800533 /**
534 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
535 * userId to restricted uids which belong to that user.
536 */
537 @GuardedBy("mUidRulesFirstLock")
538 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
539
Jeff Sharkey32566012014-12-02 18:30:14 -0800540 private final RemoteCallbackList<INetworkPolicyListener>
541 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700542
Dianne Hackborn497175b2014-07-01 12:56:08 -0700543 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700544 @VisibleForTesting
545 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700546
547 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700548
Felipe Lemef0823852016-06-08 13:43:08 -0700549 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700550 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700551
Svet Ganov16a16892015-04-16 10:32:04 -0700552 private final AppOpsManager mAppOps;
553
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800554 private final IPackageManager mIPm;
555
Sudheer Shankae7361852017-03-07 11:51:46 -0800556 private ActivityManagerInternal mActivityManagerInternal;
557
Sudheer Shanka352dc572017-09-22 17:09:38 -0700558 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800559
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700560 // TODO: keep whitelist of system-critical services that should never have
561 // rules enforced, such as system, phone, and radio UIDs.
562
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700563 // TODO: migrate notifications to SystemUI
564
Makoto Onuki49392d32018-04-11 13:51:02 -0700565
566 interface Stats {
567 int UPDATE_NETWORK_ENABLED = 0;
568 int IS_UID_NETWORKING_BLOCKED = 1;
569
570 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
571 }
572
573 public final StatLogger mStatLogger = new StatLogger(new String[] {
574 "updateNetworkEnabledNL()",
575 "isUidNetworkingBlocked()",
576 });
577
Jeff Sharkey75279902011-05-24 18:39:45 -0700578 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700579 INetworkManagementService networkManagement) {
580 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
581 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700582 }
583
Jeff Sharkey9911a282018-02-14 22:29:11 -0700584 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700585 return new File(Environment.getDataDirectory(), "system");
586 }
587
Jeff Sharkey9911a282018-02-14 22:29:11 -0700588 private static @NonNull Clock getDefaultClock() {
589 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
590 Clock.systemUTC());
591 }
592
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700593 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700594 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
595 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700596 mContext = checkNotNull(context, "missing context");
597 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700598 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700599 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700600 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700601 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700602 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700603 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700604 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700605
Amith Yamasani450a16b2013-09-18 16:28:50 -0700606 HandlerThread thread = new HandlerThread(TAG);
607 thread.start();
608 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700609
Makoto Onuki8e777332017-03-28 11:25:47 -0700610 // We create another thread for the UID events, which are more time-critical.
611 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
612 /*allowIo=*/ false);
613 mUidEventThread.start();
614 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
615
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700616 mSuppressDefaultPolicy = suppressDefaultPolicy;
617
Dianne Hackborne17b4452018-01-10 13:15:40 -0800618 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700619
620 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800621
Felipe Lemed17fda42016-04-29 11:12:45 -0700622 // Expose private service for system components to use.
623 LocalServices.addService(NetworkPolicyManagerInternal.class,
624 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700625 }
626
627 public void bindConnectivityManager(IConnectivityManager connManager) {
628 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700629 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700630
Felipe Lemef0823852016-06-08 13:43:08 -0700631 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700632 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700633 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
634 mPowerSaveWhitelistExceptIdleAppIds.clear();
635 if (whitelist != null) {
636 for (int uid : whitelist) {
637 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
638 }
639 }
640 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700641 mPowerSaveWhitelistAppIds.clear();
642 if (whitelist != null) {
643 for (int uid : whitelist) {
644 mPowerSaveWhitelistAppIds.put(uid, true);
645 }
646 }
647 } catch (RemoteException e) {
648 }
649 }
650
Felipe Lemea9505cc2016-02-26 10:28:41 -0800651 /**
652 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
653 * revoke the whitelist.
654 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700655 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800656 */
Felipe Lemef0823852016-06-08 13:43:08 -0700657 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800658 final List<UserInfo> users = mUserManager.getUsers();
659 final int numberUsers = users.size();
660
Felipe Lemea110eec2016-04-29 09:58:06 -0700661 boolean changed = false;
662 for (int i = 0; i < numberUsers; i++) {
663 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700664 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700665 }
666 return changed;
667 }
668
Felipe Lemef0823852016-06-08 13:43:08 -0700669 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700670 final SystemConfig sysConfig = SystemConfig.getInstance();
671 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800672 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
673 boolean changed = false;
674 for (int i = 0; i < allowDataUsage.size(); i++) {
675 final String pkg = allowDataUsage.valueAt(i);
676 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700677 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
678 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800679 final ApplicationInfo app;
680 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700681 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800682 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700683 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
684 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800685 continue;
686 }
687 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700688 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
689 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800690 continue;
691 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700692 final int uid = UserHandle.getUid(userId, app.uid);
693 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
694 if (LOGD)
695 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
696 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800697 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700698 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700699 if (LOGD)
700 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
701 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700702 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700703 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 }
705 }
706 return changed;
707 }
708
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800709 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700710 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800711 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700712 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800713 // Boost thread's priority during system server init
714 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700715 if (!isBandwidthControlEnabled()) {
716 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
717 return;
718 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700719
Felipe Leme873a83a2016-09-07 11:34:10 -0700720 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700721 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700722
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 synchronized (mUidRulesFirstLock) {
724 synchronized (mNetworkPoliciesSecondLock) {
725 updatePowerSaveWhitelistUL();
726 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
727 mPowerManagerInternal.registerLowPowerModeObserver(
728 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800729 @Override
730 public int getServiceType() {
731 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700732 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800733
734 @Override
735 public void onLowPowerModeChanged(PowerSaveState result) {
736 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800737 if (LOGD) {
738 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
739 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800740 synchronized (mUidRulesFirstLock) {
741 if (mRestrictPower != enabled) {
742 mRestrictPower = enabled;
743 updateRulesForRestrictPowerUL();
744 }
745 }
746 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800747 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800748 mRestrictPower = mPowerManagerInternal.getLowPowerState(
749 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700750
751 mSystemReady = true;
752
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800753 waitForAdminData();
754
Felipe Leme873a83a2016-09-07 11:34:10 -0700755 // read policy from disk
756 readPolicyAL();
757
jackqdyulei29c82ab2017-03-10 14:09:16 -0800758 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700759 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800760 mRestrictBackgroundPowerState = mPowerManagerInternal
761 .getLowPowerState(ServiceType.DATA_SAVER);
762 final boolean localRestrictBackground =
763 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700764 if (localRestrictBackground && !mLoadedRestrictBackground) {
765 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800766 }
767 mPowerManagerInternal.registerLowPowerModeObserver(
768 new PowerManagerInternal.LowPowerModeListener() {
769 @Override
770 public int getServiceType() {
771 return ServiceType.DATA_SAVER;
772 }
773
774 @Override
775 public void onLowPowerModeChanged(PowerSaveState result) {
776 synchronized (mUidRulesFirstLock) {
777 updateRestrictBackgroundByLowPowerModeUL(result);
778 }
779 }
780 });
781
Felipe Leme873a83a2016-09-07 11:34:10 -0700782 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
783 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700784 }
Felipe Lemef0823852016-06-08 13:43:08 -0700785
Sudheer Shanka543339f2017-07-28 15:18:07 -0700786 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700787 updateRulesForGlobalChangeAL(false);
788 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700789 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800790 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700791
Sudheer Shankae7361852017-03-07 11:51:46 -0800792 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700793 try {
794 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000795 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800796 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 mNetworkManager.registerObserver(mAlertObserver);
798 } catch (RemoteException e) {
799 // ignored; both services live in system_server
800 }
801
802 // listen for changes to power save whitelist
803 final IntentFilter whitelistFilter = new IntentFilter(
804 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
805 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
806
Felipe Leme873a83a2016-09-07 11:34:10 -0700807 // watch for network interfaces to be claimed
808 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
809 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
810
811 // listen for package changes to update policy
812 final IntentFilter packageFilter = new IntentFilter();
813 packageFilter.addAction(ACTION_PACKAGE_ADDED);
814 packageFilter.addDataScheme("package");
815 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
816
817 // listen for UID changes to update policy
818 mContext.registerReceiver(
819 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
820
821 // listen for user changes to update policy
822 final IntentFilter userFilter = new IntentFilter();
823 userFilter.addAction(ACTION_USER_ADDED);
824 userFilter.addAction(ACTION_USER_REMOVED);
825 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
826
827 // listen for stats update events
828 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
829 mContext.registerReceiver(
830 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
831
832 // listen for restrict background changes from notifications
833 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
834 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
835
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700836 // Listen for snooze from notifications
837 mContext.registerReceiver(mSnoozeReceiver,
838 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
839 mContext.registerReceiver(mSnoozeReceiver,
840 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700841
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600842 // listen for configured wifi networks to be loaded
843 final IntentFilter wifiFilter =
844 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
845 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700846
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700847 // listen for carrier config changes to update data cycle information
848 final IntentFilter carrierConfigFilter = new IntentFilter(
849 ACTION_CARRIER_CONFIG_CHANGED);
850 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
851
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600852 // listen for meteredness changes
853 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
854 new NetworkRequest.Builder().build(), mNetworkCallback);
855
Felipe Leme873a83a2016-09-07 11:34:10 -0700856 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600857
858 // Listen for subscriber changes
859 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
860 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
861 @Override
862 public void onSubscriptionsChanged() {
863 updateNetworksInternal();
864 }
865 });
866
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800867 // tell systemReady() that the service has been initialized
868 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700869 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800870 // Restore the default priority after init is done
871 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700872 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700873 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700874 }
875
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800876 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700877 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800878 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
879 mHandler.post(() -> initService(initCompleteSignal));
880 return initCompleteSignal;
881 }
882
883 public void systemReady(CountDownLatch initCompleteSignal) {
884 // wait for initService to complete
885 try {
886 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
887 throw new IllegalStateException("Service " + TAG +" init timeout");
888 }
889 } catch (InterruptedException e) {
890 Thread.currentThread().interrupt();
891 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
892 }
893 }
894
Sudheer Shankac9d94072017-02-22 22:13:55 +0000895 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700896 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700897 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
898 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700899 }
900
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700901 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700902 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700903 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700904
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700905 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700906 }
907
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700908 @Override public void onUidIdle(int uid, boolean disabled) {
909 }
910
911 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700912 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700913 };
914
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700915 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700916 @Override
917 public void onReceive(Context context, Intent intent) {
918 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700919 synchronized (mUidRulesFirstLock) {
920 updatePowerSaveWhitelistUL();
921 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700922 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700923 }
924 }
925 };
926
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700927 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700928 @Override
929 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700930 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700931
932 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700933 final int uid = intent.getIntExtra(EXTRA_UID, -1);
934 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700935
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700936 if (ACTION_PACKAGE_ADDED.equals(action)) {
937 // update rules for UID, since it might be subject to
938 // global background data policy
939 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700940 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700941 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700942 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700943 }
944 }
945 };
946
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700947 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700948 @Override
949 public void onReceive(Context context, Intent intent) {
950 // on background handler thread, and UID_REMOVED is protected
951
952 final int uid = intent.getIntExtra(EXTRA_UID, -1);
953 if (uid == -1) return;
954
955 // remove any policy and update rules to clean up
956 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700957 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700958 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700959 synchronized (mNetworkPoliciesSecondLock) {
960 writePolicyAL();
961 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700962 }
963 }
964 };
965
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700966 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700967 @Override
968 public void onReceive(Context context, Intent intent) {
969 // on background handler thread, and USER_ADDED and USER_REMOVED
970 // broadcasts are protected
971
972 final String action = intent.getAction();
973 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
974 if (userId == -1) return;
975
Amith Yamasani15e472352015-04-24 19:06:07 -0700976 switch (action) {
977 case ACTION_USER_REMOVED:
978 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700979 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800980 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700981 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700982 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800983 // Removing outside removeUserStateUL since that can also be called when
984 // user resets app preferences.
985 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700986 if (action == ACTION_USER_ADDED) {
987 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700988 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700989 }
990 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700991 synchronized (mNetworkPoliciesSecondLock) {
992 updateRulesForGlobalChangeAL(true);
993 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700994 }
995 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700996 }
997 }
998 };
999
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001000 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001 * Receiver that watches for {@link INetworkStatsService} updates, which we
1002 * use to check against {@link NetworkPolicy#warningBytes}.
1003 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001004 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005 @Override
1006 public void onReceive(Context context, Intent intent) {
1007 // on background handler thread, and verified
1008 // READ_NETWORK_USAGE_HISTORY permission above.
1009
Felipe Lemef0823852016-06-08 13:43:08 -07001010 synchronized (mNetworkPoliciesSecondLock) {
1011 updateNetworkEnabledNL();
1012 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013 }
1014 }
1015 };
1016
1017 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001018 * Receiver that watches for {@link Notification} control of
1019 * {@link #mRestrictBackground}.
1020 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001021 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001022 @Override
1023 public void onReceive(Context context, Intent intent) {
1024 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1025 // permission above.
1026
1027 setRestrictBackground(false);
1028 }
1029 };
1030
1031 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001032 * Receiver that watches for {@link Notification} control of
1033 * {@link NetworkPolicy#lastWarningSnooze}.
1034 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001035 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001036 @Override
1037 public void onReceive(Context context, Intent intent) {
1038 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1039 // permission above.
1040
1041 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001042 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1043 performSnooze(template, TYPE_WARNING);
1044 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1045 performSnooze(template, TYPE_RAPID);
1046 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001047 }
1048 };
1049
1050 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001051 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001052 * we can perform upgrade logic. After initial upgrade logic, it updates
1053 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001054 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001055 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001056 @Override
1057 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001058 synchronized (mUidRulesFirstLock) {
1059 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001060 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001061 }
1062 }
1063 // Only need to perform upgrade logic once
1064 mContext.unregisterReceiver(this);
1065 }
1066 };
1067
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001068 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1069 Network network) {
1070 final boolean lastValue = lastValues.get(network.netId, false);
1071 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1072 if (changed) {
1073 lastValues.put(network.netId, newValue);
1074 }
1075 return changed;
1076 }
1077
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001078 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1079 @Override
1080 public void onCapabilitiesChanged(Network network,
1081 NetworkCapabilities networkCapabilities) {
1082 if (network == null || networkCapabilities == null) return;
1083
1084 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001085 final boolean newMetered = !networkCapabilities
1086 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001087 final boolean meteredChanged = updateCapabilityChange(
1088 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001089
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001090 final boolean newRoaming = !networkCapabilities
1091 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1092 final boolean roamingChanged = updateCapabilityChange(
1093 mNetworkRoaming, newRoaming, network);
1094
1095 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001096 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001097 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001098 }
1099 }
1100 }
1101 };
1102
1103 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001104 * Observer that watches for {@link INetworkManagementService} alerts.
1105 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001106 final private INetworkManagementEventObserver mAlertObserver
1107 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001108 @Override
1109 public void limitReached(String limitName, String iface) {
1110 // only someone like NMS should be calling us
1111 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1112
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001113 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1114 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001115 }
1116 }
1117 };
1118
1119 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001120 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1121 * to show visible notifications as needed.
1122 */
Felipe Lemef0823852016-06-08 13:43:08 -07001123 void updateNotificationsNL() {
1124 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001125 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001126
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001128 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130
1131 // TODO: when switching to kernel notifications, compute next future
1132 // cycle boundary to recompute notifications.
1133
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001134 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001135 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001136 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1137 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001138 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001139
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001140 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001141 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001142 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001143
Jeff Sharkey53313d72017-07-13 16:47:32 -06001144 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1145 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001146 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1147 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1148 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001149
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001150 // Carrier might want to manage notifications themselves
1151 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1152 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1153 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1154 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1155 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1156 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1157 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1158
1159 // Notify when data usage is over warning
1160 if (notifyWarning) {
1161 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1162 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1163 if (!snoozedThisCycle) {
1164 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1165 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001166 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001167 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001168
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001169 // Notify when data usage is over limit
1170 if (notifyLimit) {
1171 if (policy.isOverLimit(totalBytes)) {
1172 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1173 if (snoozedThisCycle) {
1174 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1175 } else {
1176 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1177 notifyOverLimitNL(policy.template);
1178 }
1179 } else {
1180 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001181 }
1182 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001183
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001184 // Warn if average usage over last 4 days is on track to blow pretty
1185 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001186 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001187 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001188 final long recentStart = now - recentDuration;
1189 final long recentEnd = now;
1190 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001191
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001192 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001193 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001194 final long alertBytes = (policy.limitBytes * 3) / 2;
1195
1196 if (LOGD) {
1197 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1198 + projectedBytes + " alert " + alertBytes);
1199 }
1200
1201 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1202 - DateUtils.DAY_IN_MILLIS;
1203 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001204 enqueueNotification(policy, TYPE_RAPID, 0,
1205 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001206 }
1207 }
1208 }
1209
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001210 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001211 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001212 final NotificationId notificationId = beforeNotifs.valueAt(i);
1213 if (!mActiveNotifs.contains(notificationId)) {
1214 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001215 }
1216 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001217
1218 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001219 }
1220
1221 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001222 * Attempt to find a specific app to blame for rapid data usage during the
1223 * given time period.
1224 */
1225 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1226 long start, long end) {
1227 long totalBytes = 0;
1228 long maxBytes = 0;
1229 int maxUid = 0;
1230
1231 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1232 NetworkStats.Entry entry = null;
1233 for (int i = 0; i < stats.size(); i++) {
1234 entry = stats.getValues(i, entry);
1235 final long bytes = entry.rxBytes + entry.txBytes;
1236 totalBytes += bytes;
1237 if (bytes > maxBytes) {
1238 maxBytes = bytes;
1239 maxUid = entry.uid;
1240 }
1241 }
1242
1243 // Only point blame if the majority of usage was done by a single app.
1244 // TODO: support shared UIDs
1245 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1246 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001247 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001248 try {
1249 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1250 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1251 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1252 } catch (NameNotFoundException ignored) {
1253 }
1254 }
1255 }
1256
1257 return null;
1258 }
1259
1260 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001261 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001262 * current device state, such as when
1263 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1264 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001265 *
1266 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1267 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001268 */
Jeff Sharkey146bb332018-04-18 15:42:57 -06001269 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001270 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001271 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1272 final int subId = mSubIdToSubscriberId.keyAt(i);
1273 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001274 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1275 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1276 true);
1277 if (template.matches(probeIdent)) {
1278 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001279 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001280 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001281 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001282 }
1283
1284 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001285 * Notify that given {@link NetworkTemplate} is over
1286 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1287 */
Felipe Lemef0823852016-06-08 13:43:08 -07001288 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001289 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001290 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001291 mOverLimitNotified.add(template);
1292 }
1293 }
1294
Felipe Lemef0823852016-06-08 13:43:08 -07001295 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001296 mOverLimitNotified.remove(template);
1297 }
1298
1299 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001300 * Show notification for combined {@link NetworkPolicy} and specific type,
1301 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1302 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001303 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1304 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001305 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001306 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001307 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001308 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001309 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001310 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001311 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001312
1313 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001314 final CharSequence title;
1315 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001316 switch (type) {
1317 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001318 title = res.getText(R.string.data_usage_warning_title);
1319 body = res.getString(R.string.data_usage_warning_body,
1320 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001321
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001322 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001323
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001324 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1325 builder.setDeleteIntent(PendingIntent.getBroadcast(
1326 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1327
Wei Liu546cb772016-07-21 16:19:01 -07001328 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001329 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001330 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1331
Jeff Sharkey497e4432011-06-14 17:27:29 -07001332 break;
1333 }
1334 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001335 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001336 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001337 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001338 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001339 case MATCH_WIFI:
1340 title = res.getText(R.string.data_usage_wifi_limit_title);
1341 break;
1342 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001343 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001344 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001345 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001346
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001347 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001348 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001349
Wei Liu546cb772016-07-21 16:19:01 -07001350 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001351 builder.setContentIntent(PendingIntent.getActivity(
1352 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1353 break;
1354 }
1355 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001357 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001358 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1359 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001360 case MATCH_WIFI:
1361 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1362 break;
1363 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001364 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001365 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001366 final long overBytes = totalBytes - policy.limitBytes;
1367 body = res.getString(R.string.data_usage_limit_snoozed_body,
1368 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001369
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001370 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001371 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001372 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001373
Wei Liu546cb772016-07-21 16:19:01 -07001374 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001375 builder.setContentIntent(PendingIntent.getActivity(
1376 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001377 break;
1378 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001379 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001380 title = res.getText(R.string.data_usage_rapid_title);
1381 if (rapidBlame != null) {
1382 body = res.getString(R.string.data_usage_rapid_app_body,
1383 rapidBlame.loadLabel(mContext.getPackageManager()));
1384 } else {
1385 body = res.getString(R.string.data_usage_rapid_body);
1386 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001387
Jeff Sharkey2e471452018-01-19 18:02:47 +09001388 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001389
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001390 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1391 builder.setDeleteIntent(PendingIntent.getBroadcast(
1392 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1393
1394 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001395 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001396 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001397 break;
1398 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001399 default: {
1400 return;
1401 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001402 }
1403
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001404 builder.setTicker(title);
1405 builder.setContentTitle(title);
1406 builder.setContentText(body);
1407 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001408
1409 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1410 notificationId.getId(), builder.build(), UserHandle.ALL);
1411 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001412 }
1413
Chris Wren193ae6b2017-03-31 15:17:11 -04001414 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001415 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1416 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001417 }
1418
1419 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001420 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001421 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001422 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001423 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424 @Override
1425 public void onReceive(Context context, Intent intent) {
1426 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1427 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001428 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001429 }
1430 };
1431
Jeff Sharkey146bb332018-04-18 15:42:57 -06001432 private void updateNetworksInternal() {
1433 // Get all of our cross-process communication with telephony out of
1434 // the way before we acquire internal locks.
1435 updateSubscriptions();
1436
1437 synchronized (mUidRulesFirstLock) {
1438 synchronized (mNetworkPoliciesSecondLock) {
1439 ensureActiveMobilePolicyAL();
1440 normalizePoliciesNL();
1441 updateNetworkEnabledNL();
1442 updateNetworkRulesNL();
1443 updateNotificationsNL();
1444 }
1445 }
1446 }
1447
Jeff Sharkey2e471452018-01-19 18:02:47 +09001448 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001449 public void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001450 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001451 final CountDownLatch latch = new CountDownLatch(1);
1452 mHandler.post(() -> {
1453 latch.countDown();
1454 });
1455 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001456 }
1457
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001458 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001459 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1460 * if necessary.
1461 *
1462 * @param subId that has its associated NetworkPolicy updated if necessary
1463 * @return if any policies were updated
1464 */
Jeff Sharkey146bb332018-04-18 15:42:57 -06001465 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001466 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001467
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001468 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001469 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001470 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001471 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001472 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1473 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1474 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001475 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1476 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001477 }
1478 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001479 return policyUpdated;
1480 }
1481
1482 /**
1483 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1484 *
1485 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1486 * to do so, it returns the fallback value.
1487 *
1488 * @param config The CarrierConfig to read the value from.
1489 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1490 * @return cycleDay to use in the mobile NetworkPolicy.
1491 */
1492 @VisibleForTesting
1493 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1494 int fallbackCycleDay) {
1495 if (config == null) {
1496 return fallbackCycleDay;
1497 }
1498 int cycleDay =
1499 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1500 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1501 return fallbackCycleDay;
1502 }
1503 // validate cycleDay value
1504 final Calendar cal = Calendar.getInstance();
1505 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1506 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1507 Slog.e(TAG, "Invalid date in "
1508 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1509 return fallbackCycleDay;
1510 }
1511 return cycleDay;
1512 }
1513
1514 /**
1515 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1516 *
1517 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1518 * to do so, it returns the fallback value.
1519 *
1520 * @param config The CarrierConfig to read the value from.
1521 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1522 * @return warningBytes to use in the mobile NetworkPolicy.
1523 */
1524 @VisibleForTesting
1525 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1526 long fallbackWarningBytes) {
1527 if (config == null) {
1528 return fallbackWarningBytes;
1529 }
1530 long warningBytes =
1531 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1532
1533 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1534 return WARNING_DISABLED;
1535 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1536 return getPlatformDefaultWarningBytes();
1537 } else if (warningBytes < 0) {
1538 Slog.e(TAG, "Invalid value in "
1539 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1540 + "non-negative value but got: " + warningBytes);
1541 return fallbackWarningBytes;
1542 }
1543
1544 return warningBytes;
1545 }
1546
1547 /**
1548 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1549 *
1550 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1551 * to do so, it returns the fallback value.
1552 *
1553 * @param config The CarrierConfig to read the value from.
1554 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1555 * @return limitBytes to use in the mobile NetworkPolicy.
1556 */
1557 @VisibleForTesting
1558 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1559 long fallbackLimitBytes) {
1560 if (config == null) {
1561 return fallbackLimitBytes;
1562 }
1563 long limitBytes =
1564 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1565
1566 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1567 return LIMIT_DISABLED;
1568 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1569 return getPlatformDefaultLimitBytes();
1570 } else if (limitBytes < 0) {
1571 Slog.e(TAG, "Invalid value in "
1572 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1573 + "non-negative value but got: " + limitBytes);
1574 return fallbackLimitBytes;
1575 }
1576 return limitBytes;
1577 }
1578
1579 /**
1580 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1581 */
1582 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1583 @Override
1584 public void onReceive(Context context, Intent intent) {
1585 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1586 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1587
1588 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1589 return;
1590 }
1591 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001592
1593 // Get all of our cross-process communication with telephony out of
1594 // the way before we acquire internal locks.
1595 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001596
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001597 synchronized (mUidRulesFirstLock) {
1598 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001599 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1600 if (subscriberId != null) {
1601 ensureActiveMobilePolicyAL(subId, subscriberId);
1602 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1603 } else {
1604 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1605 }
1606
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001607 // update network and notification rules, as the data cycle changed and it's
1608 // possible that we should be triggering warnings/limits now
1609 handleNetworkPoliciesUpdateAL(true);
1610 }
1611 }
1612 }
1613 };
1614
1615 /**
1616 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1617 * one has been updated.
1618 *
1619 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1620 * update.
1621 */
1622 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1623 if (shouldNormalizePolicies) {
1624 normalizePoliciesNL();
1625 }
1626 updateNetworkEnabledNL();
1627 updateNetworkRulesNL();
1628 updateNotificationsNL();
1629 writePolicyAL();
1630 }
1631
1632 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001633 * Proactively control network data connections when they exceed
1634 * {@link NetworkPolicy#limitBytes}.
1635 */
Felipe Lemef0823852016-06-08 13:43:08 -07001636 void updateNetworkEnabledNL() {
1637 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001638 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001639
1640 // TODO: reset any policy-disabled networks when any policy is removed
1641 // completely, which is currently rare case.
1642
Makoto Onuki49392d32018-04-11 13:51:02 -07001643 final long startTime = mStatLogger.getTime();
1644
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001645 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1646 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001647 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001648 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001649 setNetworkTemplateEnabled(policy.template, true);
1650 continue;
1651 }
1652
Jeff Sharkey53313d72017-07-13 16:47:32 -06001653 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1654 .cycleIterator(policy).next();
1655 final long start = cycle.first.toInstant().toEpochMilli();
1656 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001657 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001658
1659 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001660 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1661 && policy.lastLimitSnooze < start;
1662 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001663
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001664 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001665 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001666
1667 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001668 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001669 }
1670
1671 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001672 * Proactively disable networks that match the given
1673 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001674 */
1675 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001676 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1677 // held. Call it via the handler.
1678 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1679 .sendToTarget();
1680 }
1681
1682 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001683 // TODO: reach into ConnectivityManager to proactively disable bringing
1684 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001685
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001686 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001687 // If mobile data usage hits the limit or if the user resumes the data, we need to
1688 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001689
Jeff Sharkey146bb332018-04-18 15:42:57 -06001690 final IntArray matchingSubIds = new IntArray();
1691 synchronized (mNetworkPoliciesSecondLock) {
1692 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1693 final int subId = mSubIdToSubscriberId.keyAt(i);
1694 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1695
1696 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1697 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1698 true);
1699 // Template is matched when subscriber id matches.
1700 if (template.matches(probeIdent)) {
1701 matchingSubIds.add(subId);
1702 }
Jack Yu8781b682016-07-08 14:28:51 -07001703 }
1704 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001705
1706 // Only talk with telephony outside of locks
1707 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1708 for (int i = 0; i < matchingSubIds.size(); i++) {
1709 final int subId = matchingSubIds.get(i);
1710 tm.setPolicyDataEnabled(enabled, subId);
1711 }
Jack Yu8781b682016-07-08 14:28:51 -07001712 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001713 }
1714
1715 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001716 * Collect all ifaces from a {@link NetworkState} into the given set.
1717 */
1718 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1719 final String baseIface = state.linkProperties.getInterfaceName();
1720 if (baseIface != null) {
1721 ifaces.add(baseIface);
1722 }
1723 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1724 final String stackedIface = stackedLink.getInterfaceName();
1725 if (stackedIface != null) {
1726 ifaces.add(stackedIface);
1727 }
1728 }
1729 }
1730
1731 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001732 * Examine all currently active subscriptions from
1733 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1734 * internal data structures.
1735 * <p>
1736 * Callers <em>must not</em> hold any locks when this method called.
1737 */
1738 void updateSubscriptions() {
1739 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1740 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1741
1742 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1743 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1744
1745 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
1746 final String[] mergedSubscriberIds = ArrayUtils.defeatNullable(tm.getMergedSubscriberIds());
1747
1748 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1749 for (int subId : subIds) {
1750 final String subscriberId = tm.getSubscriberId(subId);
1751 if (!TextUtils.isEmpty(subscriberId)) {
1752 subIdToSubscriberId.put(subId, subscriberId);
1753 } else {
1754 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1755 }
1756 }
1757
1758 synchronized (mNetworkPoliciesSecondLock) {
1759 mSubIdToSubscriberId.clear();
1760 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1761 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1762 subIdToSubscriberId.valueAt(i));
1763 }
1764
1765 mMergedSubscriberIds = mergedSubscriberIds;
1766 }
1767
1768 Trace.traceEnd(TRACE_TAG_NETWORK);
1769 }
1770
1771 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001772 * Examine all connected {@link NetworkState}, looking for
1773 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1774 * remaining quota based on usage cycle and historical stats.
1775 */
Felipe Lemef0823852016-06-08 13:43:08 -07001776 void updateNetworkRulesNL() {
1777 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001778 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001779
1780 final NetworkState[] states;
1781 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001782 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001783 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001784 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001785 return;
1786 }
1787
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001788 // First, generate identities of all connected networks so we can
1789 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001790 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001791 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001792 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001793 if (state.network != null) {
1794 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1795 }
Wei Liub8eaf452016-01-25 10:32:27 -08001796 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001797 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1798 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001799 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001800 }
1801 }
1802
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001803 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001804 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001805
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001806 // For every well-defined policy, compute remaining data based on
1807 // current cycle and historical stats, and push to kernel.
1808 final ArraySet<String> matchingIfaces = new ArraySet<>();
1809 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1810 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1811
1812 // Collect all ifaces that match this policy
1813 matchingIfaces.clear();
1814 for (int j = identified.size() - 1; j >= 0; j--) {
1815 if (policy.template.matches(identified.valueAt(j))) {
1816 collectIfaces(matchingIfaces, identified.keyAt(j));
1817 }
1818 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001819
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001820 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001821 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001822 }
1823
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001824 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001825 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001826 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001827 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001828 if (hasLimit && policy.hasCycle()) {
1829 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1830 .cycleIterator(policy).next();
1831 final long start = cycle.first.toInstant().toEpochMilli();
1832 final long end = cycle.second.toInstant().toEpochMilli();
1833 final long totalBytes = getTotalBytes(policy.template, start, end);
1834
1835 if (policy.lastLimitSnooze >= start) {
1836 // snoozing past quota, but we still need to restrict apps,
1837 // so push really high quota.
1838 quotaBytes = Long.MAX_VALUE;
1839 } else {
1840 // remaining "quota" bytes are based on total usage in
1841 // current cycle. kernel doesn't like 0-byte rules, so we
1842 // set 1-byte quota and disable the radio later.
1843 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1844 }
1845 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001846 // metered network, but no policy limit; we still need to
1847 // restrict apps, so push really high quota.
1848 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001849 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001850
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001851 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001852 // TODO: switch to shared quota once NMS supports
1853 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001854 }
1855
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001856 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1857 final String iface = matchingIfaces.valueAt(j);
1858 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001859 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001860 }
1861 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001862
1863 // keep track of lowest warning or limit of active policies
1864 if (hasWarning && policy.warningBytes < lowestRule) {
1865 lowestRule = policy.warningBytes;
1866 }
1867 if (hasLimit && policy.limitBytes < lowestRule) {
1868 lowestRule = policy.limitBytes;
1869 }
1870 }
1871
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001872 // One final pass to catch any metered ifaces that don't have explicitly
1873 // defined policies; typically Wi-Fi networks.
1874 for (NetworkState state : states) {
1875 if (state.networkInfo != null && state.networkInfo.isConnected()
1876 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1877 matchingIfaces.clear();
1878 collectIfaces(matchingIfaces, state);
1879 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1880 final String iface = matchingIfaces.valueAt(j);
1881 if (!newMeteredIfaces.contains(iface)) {
1882 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1883 newMeteredIfaces.add(iface);
1884 }
1885 }
1886 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001887 }
1888
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001889 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001890 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1891 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001892 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001893 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001894 }
1895 }
1896 mMeteredIfaces = newMeteredIfaces;
1897
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001898 final ContentResolver cr = mContext.getContentResolver();
1899 final boolean quotaEnabled = Settings.Global.getInt(cr,
1900 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1901 final long quotaUnlimited = Settings.Global.getLong(cr,
1902 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1903 final float quotaLimited = Settings.Global.getFloat(cr,
1904 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1905
Jeff Sharkey9252b342018-01-19 07:58:35 +09001906 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001907 mSubscriptionOpportunisticQuota.clear();
1908 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001909 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001910 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001911 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001912 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001913 if (plan == null) continue;
1914
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001915 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001916 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001917 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1918 // Clamp to 0 when roaming
1919 quotaBytes = 0;
1920 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001921 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001922 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001923 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001924 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001925 } else {
1926 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001927 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1928 final long start = cycle.getLower().toInstant().toEpochMilli();
1929 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001930 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001931 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001932 .truncatedTo(ChronoUnit.DAYS)
1933 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001934 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001935 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1936 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001937 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001938 // Number of remaining days including current day
1939 final long remainingDays =
1940 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001941
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001942 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001943 }
1944
1945 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1946 }
1947
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001948 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001949 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001950
1951 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06001952
1953 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001954 }
1955
1956 /**
1957 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1958 * have at least a default mobile policy defined.
1959 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001960 private void ensureActiveMobilePolicyAL() {
1961 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001962 if (mSuppressDefaultPolicy) return;
1963
Jeff Sharkey146bb332018-04-18 15:42:57 -06001964 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1965 final int subId = mSubIdToSubscriberId.keyAt(i);
1966 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001967
Hugo Benichi446c9c92017-04-10 09:41:10 +09001968 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001969 }
1970 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001971
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001972 /**
1973 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1974 * have at least a default mobile policy defined.
1975 *
1976 * @param subId to build a default policy for
1977 * @param subscriberId that we check for an existing policy
1978 * @return true if a mobile network policy was added, or false one already existed.
1979 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001980 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001981 // Poke around to see if we already have a policy
1982 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001983 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001984 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1985 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1986 if (template.matches(probeIdent)) {
1987 if (LOGD) {
1988 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1989 + NetworkIdentity.scrubSubscriberId(subscriberId));
1990 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001991 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001992 }
1993 }
1994
Jeff Sharkey32566012014-12-02 18:30:14 -08001995 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1996 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001997 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001998 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001999 return true;
2000 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002001
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002002 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002003 final int dataWarningConfig = mContext.getResources().getInteger(
2004 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002005 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002006 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002007 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002008 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002009 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002010 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002011
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002012 private long getPlatformDefaultLimitBytes() {
2013 return LIMIT_DISABLED;
2014 }
2015
2016 @VisibleForTesting
2017 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002018 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002019 final RecurrenceRule cycleRule = NetworkPolicy
2020 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002021 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002022 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2023 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2024 synchronized (mUidRulesFirstLock) {
2025 synchronized (mNetworkPoliciesSecondLock) {
2026 updateDefaultMobilePolicyAL(subId, policy);
2027 }
2028 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002029 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002030 }
2031
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002032 /**
2033 * Update the given {@link NetworkPolicy} based on any carrier-provided
2034 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2035 * Leaves policy untouched if the user has modified it.
2036 *
2037 * @return if the policy was modified
2038 */
2039 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2040 if (!policy.inferred) {
2041 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2042 return false;
2043 }
2044
2045 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2046 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2047 policy.lastLimitSnooze, policy.metered, policy.inferred);
2048
2049 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2050 if (!ArrayUtils.isEmpty(plans)) {
2051 final SubscriptionPlan plan = plans[0];
2052 policy.cycleRule = plan.getCycleRule();
2053 final long planLimitBytes = plan.getDataLimitBytes();
2054 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2055 policy.warningBytes = getPlatformDefaultWarningBytes();
2056 policy.limitBytes = getPlatformDefaultLimitBytes();
2057 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2058 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2059 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2060 } else {
2061 policy.warningBytes = (planLimitBytes * 9) / 10;
2062 switch (plan.getDataLimitBehavior()) {
2063 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2064 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2065 policy.limitBytes = planLimitBytes;
2066 break;
2067 default:
2068 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2069 break;
2070 }
2071 }
2072 } else {
2073 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2074 final int currentCycleDay;
2075 if (policy.cycleRule.isMonthly()) {
2076 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2077 } else {
2078 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2079 }
2080 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2081 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2082 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2083 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2084 }
2085
2086 if (policy.equals(original)) {
2087 return false;
2088 } else {
2089 Slog.d(TAG, "Updated " + original + " to " + policy);
2090 return true;
2091 }
2092 }
2093
Felipe Lemef0823852016-06-08 13:43:08 -07002094 private void readPolicyAL() {
2095 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002096
2097 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002098 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002099 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002100 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002101 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002102
2103 FileInputStream fis = null;
2104 try {
2105 fis = mPolicyFile.openRead();
2106 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002107 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002108
Felipe Leme46b451f2016-08-19 08:46:17 -07002109 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2110 // to skip UIDs that were explicitly blacklisted.
2111 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2112
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002113 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002114 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002115 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002116 while ((type = in.next()) != END_DOCUMENT) {
2117 final String tag = in.getName();
2118 if (type == START_TAG) {
2119 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002120 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002121 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002122 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2123 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002124 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2125 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2126 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002127 final String networkId;
2128 if (version >= VERSION_ADDED_NETWORK_ID) {
2129 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2130 } else {
2131 networkId = null;
2132 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002133 final RecurrenceRule cycleRule;
2134 if (version >= VERSION_ADDED_CYCLE) {
2135 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2136 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2137 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2138 cycleRule = new RecurrenceRule(
2139 RecurrenceRule.convertZonedDateTime(start),
2140 RecurrenceRule.convertZonedDateTime(end),
2141 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002142 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002143 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2144 final String cycleTimezone;
2145 if (version >= VERSION_ADDED_TIMEZONE) {
2146 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2147 } else {
2148 cycleTimezone = "UTC";
2149 }
2150 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002151 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002152 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2153 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002154 final long lastLimitSnooze;
2155 if (version >= VERSION_SPLIT_SNOOZE) {
2156 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2157 } else if (version >= VERSION_ADDED_SNOOZE) {
2158 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002159 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002160 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002161 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002162 final boolean metered;
2163 if (version >= VERSION_ADDED_METERED) {
2164 metered = readBooleanAttribute(in, ATTR_METERED);
2165 } else {
2166 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002167 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002168 metered = true;
2169 break;
2170 default:
2171 metered = false;
2172 }
2173 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002174 final long lastWarningSnooze;
2175 if (version >= VERSION_SPLIT_SNOOZE) {
2176 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2177 } else {
2178 lastWarningSnooze = SNOOZE_NEVER;
2179 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002180 final boolean inferred;
2181 if (version >= VERSION_ADDED_INFERRED) {
2182 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2183 } else {
2184 inferred = false;
2185 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002186
Jeff Sharkey32566012014-12-02 18:30:14 -08002187 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2188 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002189 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002190 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2191 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002192 lastLimitSnooze, metered, inferred));
2193 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002194
2195 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2196 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2197 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2198 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2199 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2200 RecurrenceRule.convertZonedDateTime(start),
2201 RecurrenceRule.convertZonedDateTime(end),
2202 RecurrenceRule.convertPeriod(period));
2203 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2204 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2205
2206 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2207 SubscriptionPlan.BYTES_UNKNOWN);
2208 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2209 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2210 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2211 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2212 builder.setDataLimit(limitBytes, limitBehavior);
2213 }
2214
2215 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2216 SubscriptionPlan.BYTES_UNKNOWN);
2217 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2218 SubscriptionPlan.TIME_UNKNOWN);
2219 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2220 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2221 builder.setDataUsage(usageBytes, usageTime);
2222 }
2223
2224 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2225 final SubscriptionPlan plan = builder.build();
2226 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2227 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2228
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002229 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2230 mSubscriptionPlansOwner.put(subId, ownerPackage);
2231
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002232 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002233 final int uid = readIntAttribute(in, ATTR_UID);
2234 final int policy = readIntAttribute(in, ATTR_POLICY);
2235
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002236 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002237 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002238 } else {
2239 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2240 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002241 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002242 final int appId = readIntAttribute(in, ATTR_APP_ID);
2243 final int policy = readIntAttribute(in, ATTR_POLICY);
2244
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002245 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002246 // app policy is deprecated so this is only used in pre system user split.
2247 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002248 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002249 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002250 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002251 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002252 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002253 } else if (TAG_WHITELIST.equals(tag)) {
2254 insideWhitelist = true;
2255 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2256 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002257 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002258 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2259 final int uid = readIntAttribute(in, ATTR_UID);
2260 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002261 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002262 } else if (type == END_TAG) {
2263 if (TAG_WHITELIST.equals(tag)) {
2264 insideWhitelist = false;
2265 }
2266
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002267 }
2268 }
2269
Felipe Leme46b451f2016-08-19 08:46:17 -07002270 final int size = whitelistedRestrictBackground.size();
2271 for (int i = 0; i < size; i++) {
2272 final int uid = whitelistedRestrictBackground.keyAt(i);
2273 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2274 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2275 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2276 + " because its policy is " + uidPoliciesToString(policy));
2277 continue;
2278 }
2279 if (UserHandle.isApp(uid)) {
2280 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2281 if (LOGV)
2282 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2283 setUidPolicyUncheckedUL(uid, newPolicy, false);
2284 } else {
2285 Slog.w(TAG, "unable to update policy on UID " + uid);
2286 }
2287 }
2288
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002289 } catch (FileNotFoundException e) {
2290 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002291 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002292 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002293 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002294 } finally {
2295 IoUtils.closeQuietly(fis);
2296 }
2297 }
2298
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002299 /**
2300 * Upgrade legacy background data flags, notifying listeners of one last
2301 * change to always-true.
2302 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002303 private void upgradeDefaultBackgroundDataUL() {
2304 // This method is only called when we're unable to find the network policy flag, which
2305 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002306
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002307 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002308 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002309 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2310
2311 // NOTE: We used to read the legacy setting here :
2312 //
2313 // final int legacyFlagValue = Settings.Secure.getInt(
2314 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2315 //
2316 // This is no longer necessary because we will never upgrade directly from Gingerbread
2317 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2318 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002319 }
2320
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002321 /**
2322 * Perform upgrade step of moving any user-defined meterness overrides over
2323 * into {@link WifiConfiguration}.
2324 */
2325 private void upgradeWifiMeteredOverrideAL() {
2326 boolean modified = false;
2327 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2328 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2329 for (int i = 0; i < mNetworkPolicy.size(); ) {
2330 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2331 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2332 && !policy.inferred) {
2333 mNetworkPolicy.removeAt(i);
2334 modified = true;
2335
2336 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2337 for (WifiConfiguration config : configs) {
2338 if (Objects.equals(resolveNetworkId(config), networkId)) {
2339 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2340 config.meteredOverride = policy.metered
2341 ? WifiConfiguration.METERED_OVERRIDE_METERED
2342 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2343 wm.updateNetwork(config);
2344 }
2345 }
2346 } else {
2347 i++;
2348 }
2349 }
2350 if (modified) {
2351 writePolicyAL();
2352 }
2353 }
2354
Felipe Lemef0823852016-06-08 13:43:08 -07002355 void writePolicyAL() {
2356 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002357
2358 FileOutputStream fos = null;
2359 try {
2360 fos = mPolicyFile.startWrite();
2361
2362 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002363 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002364 out.startDocument(null, true);
2365
2366 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002367 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002368 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002369
2370 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002371 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2372 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002373 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002374 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002375
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002376 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002377 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2378 final String subscriberId = template.getSubscriberId();
2379 if (subscriberId != null) {
2380 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002381 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002382 final String networkId = template.getNetworkId();
2383 if (networkId != null) {
2384 out.attribute(null, ATTR_NETWORK_ID, networkId);
2385 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002386 writeStringAttribute(out, ATTR_CYCLE_START,
2387 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2388 writeStringAttribute(out, ATTR_CYCLE_END,
2389 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2390 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2391 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002392 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2393 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002394 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2395 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002396 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002397 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002398 out.endTag(null, TAG_NETWORK_POLICY);
2399 }
2400
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002401 // write all known subscription plans
2402 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2403 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002404 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002405 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2406 if (ArrayUtils.isEmpty(plans)) continue;
2407
2408 for (SubscriptionPlan plan : plans) {
2409 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2410 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002411 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002412 final RecurrenceRule cycleRule = plan.getCycleRule();
2413 writeStringAttribute(out, ATTR_CYCLE_START,
2414 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2415 writeStringAttribute(out, ATTR_CYCLE_END,
2416 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2417 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2418 RecurrenceRule.convertPeriod(cycleRule.period));
2419 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2420 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2421 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2422 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2423 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2424 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2425 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2426 }
2427 }
2428
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002429 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002430 for (int i = 0; i < mUidPolicy.size(); i++) {
2431 final int uid = mUidPolicy.keyAt(i);
2432 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002433
Jeff Sharkey497e4432011-06-14 17:27:29 -07002434 // skip writing empty policies
2435 if (policy == POLICY_NONE) continue;
2436
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002437 out.startTag(null, TAG_UID_POLICY);
2438 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002439 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002440 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002441 }
2442
2443 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002444
2445 // write all whitelists
2446 out.startTag(null, TAG_WHITELIST);
2447
Felipe Lemea9505cc2016-02-26 10:28:41 -08002448 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002449 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002450 for (int i = 0; i < size; i++) {
2451 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2452 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2453 writeIntAttribute(out, ATTR_UID, uid);
2454 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2455 }
2456
Felipe Lemeb85a6372016-01-14 16:16:16 -08002457 out.endTag(null, TAG_WHITELIST);
2458
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002459 out.endDocument();
2460
2461 mPolicyFile.finishWrite(fos);
2462 } catch (IOException e) {
2463 if (fos != null) {
2464 mPolicyFile.failWrite(fos);
2465 }
2466 }
2467 }
2468
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002469 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002470 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002471 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002472
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002473 if (!UserHandle.isApp(uid)) {
2474 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002475 }
Felipe Lemef0823852016-06-08 13:43:08 -07002476 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002477 final long token = Binder.clearCallingIdentity();
2478 try {
2479 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2480 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002481 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002482 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002483 }
2484 } finally {
2485 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002486 }
2487 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002488 }
2489
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002490 @Override
2491 public void addUidPolicy(int uid, int policy) {
2492 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002493
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002494 if (!UserHandle.isApp(uid)) {
2495 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2496 }
2497
Felipe Lemef0823852016-06-08 13:43:08 -07002498 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002499 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2500 policy |= oldPolicy;
2501 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002502 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002503 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002504 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002505 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002506 }
2507
2508 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002509 public void removeUidPolicy(int uid, int policy) {
2510 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2511
2512 if (!UserHandle.isApp(uid)) {
2513 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2514 }
2515
Felipe Lemef0823852016-06-08 13:43:08 -07002516 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002517 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2518 policy = oldPolicy & ~policy;
2519 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002520 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002521 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002522 }
2523 }
2524 }
2525
Felipe Lemef0823852016-06-08 13:43:08 -07002526 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002527 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002528
Felipe Leme57e3d312016-08-23 14:42:52 -07002529 final boolean notifyApp;
2530 if (!isUidValidForWhitelistRules(uid)) {
2531 notifyApp = false;
2532 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002533 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2534 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2535 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2536 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002537 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2538 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002539 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2540 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2541 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2542 if (LOGD)
2543 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2544 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2545 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002546 notifyApp = wasBlocked != isBlocked;
2547 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002548 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2549 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002550 if (persist) {
2551 synchronized (mNetworkPoliciesSecondLock) {
2552 writePolicyAL();
2553 }
2554 }
Felipe Leme923845f2016-03-02 13:42:48 -08002555 }
2556
Felipe Lemef0823852016-06-08 13:43:08 -07002557 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002558 if (policy == POLICY_NONE) {
2559 mUidPolicy.delete(uid);
2560 } else {
2561 mUidPolicy.put(uid, policy);
2562 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002563
2564 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002565 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002566 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002567 synchronized (mNetworkPoliciesSecondLock) {
2568 writePolicyAL();
2569 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002570 }
2571 }
2572
2573 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002574 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002575 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2576
Felipe Lemef0823852016-06-08 13:43:08 -07002577 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002578 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002580 }
2581
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002582 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002583 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2585
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002586 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002587 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002588 for (int i = 0; i < mUidPolicy.size(); i++) {
2589 final int uid = mUidPolicy.keyAt(i);
2590 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002591 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2592 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002593 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002594 }
2595 }
2596 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002597 return uids;
2598 }
2599
2600 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002601 * Removes any persistable state associated with given {@link UserHandle}, persisting
2602 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002603 */
Felipe Lemef0823852016-06-08 13:43:08 -07002604 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002605
Sudheer Shanka352dc572017-09-22 17:09:38 -07002606 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002607 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002608
Felipe Lemea110eec2016-04-29 09:58:06 -07002609 // Remove entries from revoked default restricted background UID whitelist
2610 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2611 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2612 if (UserHandle.getUserId(uid) == userId) {
2613 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002614 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002615 }
2616 }
2617
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002618 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002619 int[] uids = new int[0];
2620 for (int i = 0; i < mUidPolicy.size(); i++) {
2621 final int uid = mUidPolicy.keyAt(i);
2622 if (UserHandle.getUserId(uid) == userId) {
2623 uids = appendInt(uids, uid);
2624 }
2625 }
2626
2627 if (uids.length > 0) {
2628 for (int uid : uids) {
2629 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002630 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002631 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002632 }
Felipe Lemef0823852016-06-08 13:43:08 -07002633 synchronized (mNetworkPoliciesSecondLock) {
2634 updateRulesForGlobalChangeAL(true);
2635 if (writePolicy && changed) {
2636 writePolicyAL();
2637 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002638 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002639 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002640 }
2641
2642 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002643 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002644 // TODO: create permission for observing network policy
2645 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002646 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002647 }
2648
2649 @Override
2650 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002651 // TODO: create permission for observing network policy
2652 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002653 mListeners.unregister(listener);
2654 }
2655
Jeff Sharkey1b861272011-05-22 00:34:52 -07002656 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002657 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002658 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2659
Felipe Leme6a05eee2016-02-19 14:43:51 -08002660 final long token = Binder.clearCallingIdentity();
2661 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002662 synchronized (mUidRulesFirstLock) {
2663 synchronized (mNetworkPoliciesSecondLock) {
2664 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002665 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002666 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002667 }
2668 } finally {
2669 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002670 }
2671 }
2672
Hugo Benichi446c9c92017-04-10 09:41:10 +09002673 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002674 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002675 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2676 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002677 }
2678
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002679 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002680 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002681 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002682 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002683 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2684 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2685 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002686 } catch (SecurityException e) {
2687 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002688
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002689 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2690 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2691 return new NetworkPolicy[0];
2692 }
Svet Ganov16a16892015-04-16 10:32:04 -07002693 }
2694
Felipe Lemef0823852016-06-08 13:43:08 -07002695 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002696 final int size = mNetworkPolicy.size();
2697 final NetworkPolicy[] policies = new NetworkPolicy[size];
2698 for (int i = 0; i < size; i++) {
2699 policies[i] = mNetworkPolicy.valueAt(i);
2700 }
2701 return policies;
2702 }
2703 }
2704
Felipe Lemef0823852016-06-08 13:43:08 -07002705 private void normalizePoliciesNL() {
2706 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002707 }
2708
Felipe Lemef0823852016-06-08 13:43:08 -07002709 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002710 mNetworkPolicy.clear();
2711 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002712 if (policy == null) {
2713 continue;
2714 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002715 // When two normalized templates conflict, prefer the most
2716 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002717 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002718 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2719 if (existing == null || existing.compareTo(policy) > 0) {
2720 if (existing != null) {
2721 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2722 }
2723 mNetworkPolicy.put(policy.template, policy);
2724 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002725 }
2726 }
2727
2728 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002729 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002730 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002731
2732 final long token = Binder.clearCallingIdentity();
2733 try {
2734 performSnooze(template, TYPE_LIMIT);
2735 } finally {
2736 Binder.restoreCallingIdentity(token);
2737 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002738 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002739
Dianne Hackborn497175b2014-07-01 12:56:08 -07002740 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002741 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002742 synchronized (mUidRulesFirstLock) {
2743 synchronized (mNetworkPoliciesSecondLock) {
2744 // find and snooze local policy that matches
2745 final NetworkPolicy policy = mNetworkPolicy.get(template);
2746 if (policy == null) {
2747 throw new IllegalArgumentException("unable to find policy for " + template);
2748 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002749
Felipe Lemef0823852016-06-08 13:43:08 -07002750 switch (type) {
2751 case TYPE_WARNING:
2752 policy.lastWarningSnooze = currentTime;
2753 break;
2754 case TYPE_LIMIT:
2755 policy.lastLimitSnooze = currentTime;
2756 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002757 case TYPE_RAPID:
2758 policy.lastRapidSnooze = currentTime;
2759 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002760 default:
2761 throw new IllegalArgumentException("unexpected type");
2762 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002763
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002764 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002765 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002766 }
2767 }
2768
2769 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002770 public void onTetheringChanged(String iface, boolean tethering) {
2771 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002772 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002773 if (mRestrictBackground && tethering) {
2774 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2775 setRestrictBackground(false);
2776 }
2777 }
2778 }
2779
2780 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002781 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002782 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002783 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002784 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2785 final long token = Binder.clearCallingIdentity();
2786 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002787 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002788 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002789 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002790 } finally {
2791 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002792 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002793 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002794 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002795 }
2796 }
2797
Felipe Lemef0823852016-06-08 13:43:08 -07002798 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002799 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002800 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002801 if (restrictBackground == mRestrictBackground) {
2802 // Ideally, UI should never allow this scenario...
2803 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002804 return;
2805 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002806 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2807 final boolean oldRestrictBackground = mRestrictBackground;
2808 mRestrictBackground = restrictBackground;
2809 // Must whitelist foreground apps before turning data saver mode on.
2810 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2811 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2812 updateRulesForRestrictBackgroundUL();
2813 try {
2814 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2815 Slog.e(TAG,
2816 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2817 mRestrictBackground = oldRestrictBackground;
2818 // TODO: if it knew the foreground apps (see TODO above), it could call
2819 // updateRulesForRestrictBackgroundUL() again to restore state.
2820 return;
2821 }
2822 } catch (RemoteException e) {
2823 // ignored; service lives in system_server
2824 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002825
Sudheer Shanka543339f2017-07-28 15:18:07 -07002826 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002827 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002828
2829 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2830 mRestrictBackgroundChangedInBsm = true;
2831 }
2832 synchronized (mNetworkPoliciesSecondLock) {
2833 updateNotificationsNL();
2834 writePolicyAL();
2835 }
2836 } finally {
2837 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002838 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002839 }
2840
2841 private void sendRestrictBackgroundChangedMsg() {
2842 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2843 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2844 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002845 }
2846
Felipe Lemeb85a6372016-01-14 16:16:16 -08002847 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002848 public int getRestrictBackgroundByCaller() {
2849 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2850 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002851
Felipe Lemef0823852016-06-08 13:43:08 -07002852 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002853 // Must clear identity because getUidPolicy() is restricted to system.
2854 final long token = Binder.clearCallingIdentity();
2855 final int policy;
2856 try {
2857 policy = getUidPolicy(uid);
2858 } finally {
2859 Binder.restoreCallingIdentity(token);
2860 }
2861 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2862 // App is blacklisted.
2863 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2864 }
Felipe Leme1b103232016-01-22 09:44:57 -08002865 if (!mRestrictBackground) {
2866 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2867 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002868 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002869 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2870 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2871 }
2872 }
2873
2874 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002875 public boolean getRestrictBackground() {
2876 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2877
Felipe Lemef0823852016-06-08 13:43:08 -07002878 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002879 return mRestrictBackground;
2880 }
2881 }
2882
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002883 @Override
2884 public void setDeviceIdleMode(boolean enabled) {
2885 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002886 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2887 try {
2888 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002889 if (mDeviceIdleMode == enabled) {
2890 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002891 }
Felipe Lemeea014392016-09-06 13:59:54 -07002892 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002893 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002894 if (mSystemReady) {
2895 // Device idle change means we need to rebuild rules for all
2896 // known apps, so do a global refresh.
2897 updateRulesForRestrictPowerUL();
2898 }
2899 }
2900 if (enabled) {
2901 EventLogTags.writeDeviceIdleOnPhase("net");
2902 } else {
2903 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002904 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002905 } finally {
2906 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002907 }
2908 }
2909
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002910 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002911 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2912 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002913 final long token = Binder.clearCallingIdentity();
2914 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002915 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2916 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2917 for (WifiConfiguration config : configs) {
2918 if (Objects.equals(resolveNetworkId(config), networkId)) {
2919 config.meteredOverride = meteredOverride;
2920 wm.updateNetwork(config);
2921 }
2922 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002923 } finally {
2924 Binder.restoreCallingIdentity(token);
2925 }
2926 }
2927
Jeff Sharkey46645002011-07-27 21:11:21 -07002928 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002929 @Deprecated
2930 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2931 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2932 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2933 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002934 }
2935
Jeff Sharkey53313d72017-07-13 16:47:32 -06002936 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2937 // Verify they're not lying about package name
2938 mAppOps.checkPackage(callingUid, callingPackage);
2939
Jeff Sharkey53313d72017-07-13 16:47:32 -06002940 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002941 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002942 final long token = Binder.clearCallingIdentity();
2943 try {
2944 si = mContext.getSystemService(SubscriptionManager.class)
2945 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002946 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002947 } finally {
2948 Binder.restoreCallingIdentity(token);
2949 }
2950
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002951 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002952 if (si != null) {
2953 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2954 return;
2955 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002956 }
2957
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002958 // Second check: has the CarrierService delegated access?
2959 if (config != null) {
2960 final String overridePackage = config
2961 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2962 if (!TextUtils.isEmpty(overridePackage)
2963 && Objects.equals(overridePackage, callingPackage)) {
2964 return;
2965 }
2966 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002967
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002968 // Third check: is caller the fallback/default CarrierService?
2969 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2970 if (!TextUtils.isEmpty(defaultPackage)
2971 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002972 return;
2973 }
2974
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002975 // Fourth check: is caller a testing app?
2976 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2977 if (!TextUtils.isEmpty(testPackage)
2978 && Objects.equals(testPackage, callingPackage)) {
2979 return;
2980 }
2981
2982 // Fifth check: is caller a legacy testing app?
2983 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2984 if (!TextUtils.isEmpty(legacyTestPackage)
2985 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002986 return;
2987 }
2988
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002989 // Final check: does the caller hold a permission?
2990 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002991 }
2992
2993 @Override
2994 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2995 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2996
Jeff Sharkey53313d72017-07-13 16:47:32 -06002997 final String fake = SystemProperties.get("fw.fake_plan");
2998 if (!TextUtils.isEmpty(fake)) {
2999 final List<SubscriptionPlan> plans = new ArrayList<>();
3000 if ("month_hard".equals(fake)) {
3001 plans.add(SubscriptionPlan.Builder
3002 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3003 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003004 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3005 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3006 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3007 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3008 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003009 plans.add(SubscriptionPlan.Builder
3010 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3011 .setTitle("G-Mobile Happy")
3012 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3013 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3014 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3015 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3016 .build());
3017 plans.add(SubscriptionPlan.Builder
3018 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3019 .setTitle("G-Mobile, Charged after limit")
3020 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3021 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3022 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3023 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3024 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003025 } else if ("month_soft".equals(fake)) {
3026 plans.add(SubscriptionPlan.Builder
3027 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3028 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3029 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3030 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003031 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3032 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3033 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3034 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3035 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003036 plans.add(SubscriptionPlan.Builder
3037 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3038 .setTitle("G-Mobile, Throttled after limit")
3039 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3040 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3041 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3042 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3043 .build());
3044 plans.add(SubscriptionPlan.Builder
3045 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3046 .setTitle("G-Mobile, No data connection after limit")
3047 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3048 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3049 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3050 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3051 .build());
3052
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003053 } else if ("month_over".equals(fake)) {
3054 plans.add(SubscriptionPlan.Builder
3055 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3056 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3057 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3058 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3059 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3060 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3061 .build());
3062 plans.add(SubscriptionPlan.Builder
3063 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3064 .setTitle("G-Mobile, Throttled after limit")
3065 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3066 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3067 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3068 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3069 .build());
3070 plans.add(SubscriptionPlan.Builder
3071 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3072 .setTitle("G-Mobile, No data connection after limit")
3073 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3074 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3075 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3076 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3077 .build());
3078
Jeff Sharkey53313d72017-07-13 16:47:32 -06003079 } else if ("month_none".equals(fake)) {
3080 plans.add(SubscriptionPlan.Builder
3081 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3082 .setTitle("G-Mobile")
3083 .build());
3084 } else if ("prepaid".equals(fake)) {
3085 plans.add(SubscriptionPlan.Builder
3086 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3087 ZonedDateTime.now().plusDays(10))
3088 .setTitle("G-Mobile")
3089 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3090 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3091 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3092 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3093 .build());
3094 } else if ("prepaid_crazy".equals(fake)) {
3095 plans.add(SubscriptionPlan.Builder
3096 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3097 ZonedDateTime.now().plusDays(10))
3098 .setTitle("G-Mobile Anytime")
3099 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3100 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3101 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3102 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3103 .build());
3104 plans.add(SubscriptionPlan.Builder
3105 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3106 ZonedDateTime.now().plusDays(20))
3107 .setTitle("G-Mobile Nickel Nights")
3108 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003109 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3110 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003111 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3112 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3113 .build());
3114 plans.add(SubscriptionPlan.Builder
3115 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3116 ZonedDateTime.now().plusDays(20))
3117 .setTitle("G-Mobile Bonus 3G")
3118 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003119 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003120 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3121 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3122 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3123 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003124 } else if ("unlimited".equals(fake)) {
3125 plans.add(SubscriptionPlan.Builder
3126 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3127 ZonedDateTime.now().plusDays(10))
3128 .setTitle("G-Mobile Awesome")
3129 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3130 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3131 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3132 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3133 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003134 }
3135 return plans.toArray(new SubscriptionPlan[plans.size()]);
3136 }
3137
Jeff Sharkey4635f102017-09-01 11:27:13 -06003138 synchronized (mNetworkPoliciesSecondLock) {
3139 // Only give out plan details to the package that defined them,
3140 // so that we don't risk leaking plans between apps. We always
3141 // let in core system components (like the Settings app).
3142 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3143 if (Objects.equals(ownerPackage, callingPackage)
3144 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3145 return mSubscriptionPlans.get(subId);
3146 } else {
3147 Log.w(TAG, "Not returning plans because caller " + callingPackage
3148 + " doesn't match owner " + ownerPackage);
3149 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003150 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003151 }
3152 }
3153
3154 @Override
3155 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3156 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3157
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003158 for (SubscriptionPlan plan : plans) {
3159 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003160 }
3161
3162 final long token = Binder.clearCallingIdentity();
3163 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003164 synchronized (mUidRulesFirstLock) {
3165 synchronized (mNetworkPoliciesSecondLock) {
3166 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003167 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003168
Jeff Sharkey146bb332018-04-18 15:42:57 -06003169 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3170 if (subscriberId != null) {
3171 ensureActiveMobilePolicyAL(subId, subscriberId);
3172 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3173 } else {
3174 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3175 }
3176
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003177 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003178 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003179 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003180
3181 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3182 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3183 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3184 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003185 } finally {
3186 Binder.restoreCallingIdentity(token);
3187 }
3188 }
3189
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003190 /**
3191 * Only visible for testing purposes. This doesn't give any access to
3192 * existing plans; it simply lets the debug package define new plans.
3193 */
3194 void setSubscriptionPlansOwner(int subId, String packageName) {
3195 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3196 }
3197
Jeff Sharkey53313d72017-07-13 16:47:32 -06003198 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003199 public String getSubscriptionPlansOwner(int subId) {
3200 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3201 throw new SecurityException();
3202 }
3203
3204 synchronized (mNetworkPoliciesSecondLock) {
3205 return mSubscriptionPlansOwner.get(subId);
3206 }
3207 }
3208
3209 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003210 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3211 long timeoutMillis, String callingPackage) {
3212 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3213
3214 // We can only override when carrier told us about plans
3215 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003216 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3217 if (plan == null
3218 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003219 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003220 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003221 }
3222 }
3223
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003224 // Only allow overrides when feature is enabled. However, we always
3225 // allow disabling of overrides for safety reasons.
3226 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3227 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3228 if (overrideEnabled || overrideValue == 0) {
3229 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3230 overrideMask, overrideValue, subId));
3231 if (timeoutMillis > 0) {
3232 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3233 overrideMask, 0, subId), timeoutMillis);
3234 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003235 }
3236 }
3237
3238 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003239 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003240 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003241
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003242 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3243
Dianne Hackborn497175b2014-07-01 12:56:08 -07003244 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003245 for (String arg : args) {
3246 argSet.add(arg);
3247 }
3248
Felipe Lemef0823852016-06-08 13:43:08 -07003249 synchronized (mUidRulesFirstLock) {
3250 synchronized (mNetworkPoliciesSecondLock) {
3251 if (argSet.contains("--unsnooze")) {
3252 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3253 mNetworkPolicy.valueAt(i).clearSnooze();
3254 }
3255
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003256 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003257
3258 fout.println("Cleared snooze timestamps");
3259 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003260 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003261
Felipe Lemef0823852016-06-08 13:43:08 -07003262 fout.print("System ready: "); fout.println(mSystemReady);
3263 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3264 fout.print("Restrict power: "); fout.println(mRestrictPower);
3265 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003266 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3267
3268 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003269 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003270 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003271 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3272 fout.println(mNetworkPolicy.valueAt(i).toString());
3273 }
3274 fout.decreaseIndent();
3275
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003276 fout.println();
3277 fout.println("Subscription plans:");
3278 fout.increaseIndent();
3279 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3280 final int subId = mSubscriptionPlans.keyAt(i);
3281 fout.println("Subscriber ID " + subId + ":");
3282 fout.increaseIndent();
3283 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3284 if (!ArrayUtils.isEmpty(plans)) {
3285 for (SubscriptionPlan plan : plans) {
3286 fout.println(plan);
3287 }
3288 }
3289 fout.decreaseIndent();
3290 }
3291 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003292
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003293 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003294 fout.println("Active subscriptions:");
3295 fout.increaseIndent();
3296 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3297 final int subId = mSubIdToSubscriberId.keyAt(i);
3298 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3299
3300 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3301 }
3302 fout.decreaseIndent();
3303
3304 fout.println();
3305 fout.println("Merged subscriptions: "
3306 + Arrays.toString(NetworkIdentity.scrubSubscriberId(mMergedSubscriberIds)));
3307
3308 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003309 fout.println("Policy for UIDs:");
3310 fout.increaseIndent();
3311 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003312 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003313 final int uid = mUidPolicy.keyAt(i);
3314 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003315 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003316 fout.print(uid);
3317 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003318 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003319 fout.println();
3320 }
3321 fout.decreaseIndent();
3322
3323 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3324 if (size > 0) {
3325 fout.println("Power save whitelist (except idle) app ids:");
3326 fout.increaseIndent();
3327 for (int i = 0; i < size; i++) {
3328 fout.print("UID=");
3329 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3330 fout.print(": ");
3331 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3332 fout.println();
3333 }
3334 fout.decreaseIndent();
3335 }
3336
3337 size = mPowerSaveWhitelistAppIds.size();
3338 if (size > 0) {
3339 fout.println("Power save whitelist app ids:");
3340 fout.increaseIndent();
3341 for (int i = 0; i < size; i++) {
3342 fout.print("UID=");
3343 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3344 fout.print(": ");
3345 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3346 fout.println();
3347 }
3348 fout.decreaseIndent();
3349 }
3350
Felipe Lemef0823852016-06-08 13:43:08 -07003351 size = mDefaultRestrictBackgroundWhitelistUids.size();
3352 if (size > 0) {
3353 fout.println("Default restrict background whitelist uids:");
3354 fout.increaseIndent();
3355 for (int i = 0; i < size; i++) {
3356 fout.print("UID=");
3357 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3358 fout.println();
3359 }
3360 fout.decreaseIndent();
3361 }
3362
3363 size = mRestrictBackgroundWhitelistRevokedUids.size();
3364 if (size > 0) {
3365 fout.println("Default restrict background whitelist uids revoked by users:");
3366 fout.increaseIndent();
3367 for (int i = 0; i < size; i++) {
3368 fout.print("UID=");
3369 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3370 fout.println();
3371 }
3372 fout.decreaseIndent();
3373 }
3374
3375 final SparseBooleanArray knownUids = new SparseBooleanArray();
3376 collectKeys(mUidState, knownUids);
3377 collectKeys(mUidRules, knownUids);
3378
3379 fout.println("Status for all known UIDs:");
3380 fout.increaseIndent();
3381 size = knownUids.size();
3382 for (int i = 0; i < size; i++) {
3383 final int uid = knownUids.keyAt(i);
3384 fout.print("UID=");
3385 fout.print(uid);
3386
3387 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3388 fout.print(" state=");
3389 fout.print(state);
3390 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3391 fout.print(" (fg)");
3392 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003393 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003394 ? " (fg svc)" : " (bg)");
3395 }
3396
3397 final int uidRules = mUidRules.get(uid, RULE_NONE);
3398 fout.print(" rules=");
3399 fout.print(uidRulesToString(uidRules));
3400 fout.println();
3401 }
3402 fout.decreaseIndent();
3403
3404 fout.println("Status for just UIDs with rules:");
3405 fout.increaseIndent();
3406 size = mUidRules.size();
3407 for (int i = 0; i < size; i++) {
3408 final int uid = mUidRules.keyAt(i);
3409 fout.print("UID=");
3410 fout.print(uid);
3411 final int uidRules = mUidRules.get(uid, RULE_NONE);
3412 fout.print(" rules=");
3413 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003414 fout.println();
3415 }
3416 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003417
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003418 fout.println("Admin restricted uids for metered data:");
3419 fout.increaseIndent();
3420 size = mMeteredRestrictedUids.size();
3421 for (int i = 0; i < size; ++i) {
3422 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3423 fout.println(mMeteredRestrictedUids.valueAt(i));
3424 }
3425 fout.decreaseIndent();
3426
Makoto Onuki49392d32018-04-11 13:51:02 -07003427 fout.println();
3428 mStatLogger.dump(fout);
3429
Sudheer Shanka352dc572017-09-22 17:09:38 -07003430 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003431 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003432 }
3433 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003434
3435 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003436 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003437 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003438 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003439 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003440 }
3441
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003442 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003443 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003444 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003445 return isUidStateForeground(
3446 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003447 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003448 }
3449
Felipe Lemef0823852016-06-08 13:43:08 -07003450 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003451 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003452 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003453 }
3454
Felipe Lemef0823852016-06-08 13:43:08 -07003455 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003456 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3457 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3458 }
3459
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003460 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003461 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003462 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003463 }
3464
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003465 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003466 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003467 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3468 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003469 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003470 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003471 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3472 try {
3473 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3474 if (oldUidState != uidState) {
3475 // state changed, push updated rules
3476 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003477 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3478 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3479 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003480 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003481 if (mDeviceIdleMode) {
3482 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003483 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003484 if (mRestrictPower) {
3485 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003486 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003487 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003488 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003489 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003490 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003491 } finally {
3492 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003493 }
3494 }
3495
Felipe Lemef0823852016-06-08 13:43:08 -07003496 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003497 final int index = mUidState.indexOfKey(uid);
3498 if (index >= 0) {
3499 final int oldUidState = mUidState.valueAt(index);
3500 mUidState.removeAt(index);
3501 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003502 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003503 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003504 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003505 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003506 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003507 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003508 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003509 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003510 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003511 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003512 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003513 }
3514 }
3515
Felipe Lemef28983d2016-03-25 12:18:23 -07003516 // adjust stats accounting based on foreground status
3517 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003518 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3519 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3520 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3521 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003522 try {
3523 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003524 } finally {
3525 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003526 }
3527 }
3528
Sudheer Shankac9d94072017-02-22 22:13:55 +00003529 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3530 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003531 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003532 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003533 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003534 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003535 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003536 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003537 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003538 }
3539
Felipe Lemef0823852016-06-08 13:43:08 -07003540 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003541 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3542 try {
3543 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3544 mUidFirewallPowerSaveRules);
3545 } finally {
3546 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3547 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003548 }
3549
Felipe Lemef0823852016-06-08 13:43:08 -07003550 void updateRuleForRestrictPowerUL(int uid) {
3551 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003552 }
3553
Felipe Lemef0823852016-06-08 13:43:08 -07003554 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003555 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3556 try {
3557 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3558 mUidFirewallDozableRules);
3559 } finally {
3560 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3561 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003562 }
3563
Felipe Lemef0823852016-06-08 13:43:08 -07003564 void updateRuleForDeviceIdleUL(int uid) {
3565 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003566 }
3567
Felipe Lemef28983d2016-03-25 12:18:23 -07003568 // NOTE: since both fw_dozable and fw_powersave uses the same map
3569 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003570 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003571 SparseIntArray rules) {
3572 if (enabled) {
3573 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003574 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003575 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003576 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003577 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003578 for (int ui = users.size() - 1; ui >= 0; ui--) {
3579 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003580 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3581 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3582 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3583 updateRulesForWhitelistedAppIds(uidRules,
3584 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003585 }
3586 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003587 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003588 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003589 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3590 }
3591 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003592 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003593 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003594 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003595 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003596 }
3597
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003598 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3599 final SparseBooleanArray whitelistedAppIds, int userId) {
3600 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3601 if (whitelistedAppIds.valueAt(i)) {
3602 final int appId = whitelistedAppIds.keyAt(i);
3603 final int uid = UserHandle.getUid(userId, appId);
3604 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3605 }
3606 }
3607 }
3608
3609 /**
3610 * @param deviceIdleMode if true then we don't consider
3611 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3612 * whitelisted.
3613 */
3614 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003615 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003616 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3617 || mPowerSaveWhitelistAppIds.get(appId);
3618 if (!deviceIdleMode) {
3619 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3620 }
3621 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003622 }
3623
Felipe Lemef28983d2016-03-25 12:18:23 -07003624 // NOTE: since both fw_dozable and fw_powersave uses the same map
3625 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003626 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003627 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003628 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3629 chain == FIREWALL_CHAIN_DOZABLE);
3630 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003631 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003632 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003633 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003634 }
3635 }
3636 }
3637
Felipe Lemef0823852016-06-08 13:43:08 -07003638 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003639 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3640 try {
3641 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3642 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003643
Felipe Leme873a83a2016-09-07 11:34:10 -07003644 // Fully update the app idle firewall chain.
3645 final List<UserInfo> users = mUserManager.getUsers();
3646 for (int ui = users.size() - 1; ui >= 0; ui--) {
3647 UserInfo user = users.get(ui);
3648 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3649 for (int uid : idleUids) {
3650 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3651 // quick check: if this uid doesn't have INTERNET permission, it
3652 // doesn't have network access anyway, so it is a waste to mess
3653 // with it here.
3654 if (hasInternetPermissions(uid)) {
3655 uidRules.put(uid, FIREWALL_RULE_DENY);
3656 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003657 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003658 }
3659 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003660
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003661 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003662 } finally {
3663 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3664 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003665 }
3666
Felipe Lemef0823852016-06-08 13:43:08 -07003667 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003668 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003669
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003670 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3671 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3672 }
3673 try {
3674 int appId = UserHandle.getAppId(uid);
3675 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3676 && !isUidForegroundOnRestrictPowerUL(uid)) {
3677 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3678 } else {
3679 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3680 }
3681 } finally {
3682 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003683 }
3684 }
3685
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003686 /**
3687 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3688 * changed.
3689 */
Felipe Lemef0823852016-06-08 13:43:08 -07003690 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003691 boolean paroled = mUsageStats.isAppIdleParoleOn();
3692 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003693 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003694
3695 int ruleCount = mUidFirewallStandbyRules.size();
3696 for (int i = 0; i < ruleCount; i++) {
3697 int uid = mUidFirewallStandbyRules.keyAt(i);
3698 int oldRules = mUidRules.get(uid);
3699 if (enableChain) {
3700 // Chain wasn't enabled before and the other power-related
3701 // chains are whitelists, so we can clear the
3702 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3703 // the effective rules result in blocking network access.
3704 oldRules &= MASK_METERED_NETWORKS;
3705 } else {
3706 // Skip if it had no restrictions to begin with
3707 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3708 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003709 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3710 if (newUidRules == RULE_NONE) {
3711 mUidRules.delete(uid);
3712 } else {
3713 mUidRules.put(uid, newUidRules);
3714 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003715 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003716 }
3717
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003718 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003719 * Update rules that might be changed by {@link #mRestrictBackground},
3720 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003721 */
Felipe Lemef0823852016-06-08 13:43:08 -07003722 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003723 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3724 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3725 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3726 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003727 try {
Felipe Leme09700462016-09-08 09:33:48 -07003728 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003729 updateRulesForRestrictPowerUL();
3730 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003731
Felipe Leme873a83a2016-09-07 11:34:10 -07003732 // If the set of restricted networks may have changed, re-evaluate those.
3733 if (restrictedNetworksChanged) {
3734 normalizePoliciesNL();
3735 updateNetworkRulesNL();
3736 }
3737 } finally {
3738 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003739 }
3740 }
3741
Felipe Leme09700462016-09-08 09:33:48 -07003742 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003743 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003744 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3745 try {
3746 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003747 updateRulesForPowerSaveUL();
3748 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3749 } finally {
3750 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3751 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003752 }
3753
Felipe Lemef0823852016-06-08 13:43:08 -07003754 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003755 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3756 try {
3757 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3758 } finally {
3759 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3760 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003761 }
3762
3763 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3764 private static final int TYPE_RESTRICT_POWER = 2;
3765 @Retention(RetentionPolicy.SOURCE)
3766 @IntDef(flag = false, value = {
3767 TYPE_RESTRICT_BACKGROUND,
3768 TYPE_RESTRICT_POWER,
3769 })
3770 public @interface RestrictType {
3771 }
3772
3773 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003774 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003775 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3776 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3777 }
3778 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003779 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003780
3781 final PackageManager pm = mContext.getPackageManager();
3782 final List<UserInfo> users;
3783 final List<ApplicationInfo> apps;
3784
3785 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3786 try {
3787 users = mUserManager.getUsers();
3788 } finally {
3789 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3790 }
3791 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3792 try {
3793 apps = pm.getInstalledApplications(
3794 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3795 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3796 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3797 } finally {
3798 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3799 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003800
Felipe Leme873a83a2016-09-07 11:34:10 -07003801 final int usersSize = users.size();
3802 final int appsSize = apps.size();
3803 for (int i = 0; i < usersSize; i++) {
3804 final UserInfo user = users.get(i);
3805 for (int j = 0; j < appsSize; j++) {
3806 final ApplicationInfo app = apps.get(j);
3807 final int uid = UserHandle.getUid(user.id, app.uid);
3808 switch (type) {
3809 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003810 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003811 break;
3812 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003813 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003814 break;
3815 default:
3816 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3817 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003818 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003819 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003820 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003821 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003822 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003823 }
3824
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003825 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003826 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003827 final int numUsers = users.size();
3828 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003829 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003830 int uid = UserHandle.getUid(user.id, appId);
3831 // Update external firewall rules.
3832 updateRuleForAppIdleUL(uid);
3833 updateRuleForDeviceIdleUL(uid);
3834 updateRuleForRestrictPowerUL(uid);
3835 // Update internal rules.
3836 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003837 }
3838 }
3839
Felipe Leme70c57c22016-03-29 10:45:13 -07003840 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3841 // methods below could be merged into a isUidValidForRules() method.
3842 private boolean isUidValidForBlacklistRules(int uid) {
3843 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003844 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003845 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003846 return true;
3847 }
3848
3849 return false;
3850 }
3851
Felipe Leme70c57c22016-03-29 10:45:13 -07003852 private boolean isUidValidForWhitelistRules(int uid) {
3853 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3854 }
3855
Amith Yamasani15e472352015-04-24 19:06:07 -07003856 private boolean isUidIdle(int uid) {
3857 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3858 final int userId = UserHandle.getUserId(uid);
3859
songjinshi0655edd2016-05-18 19:55:32 +08003860 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003861 for (String packageName : packages) {
3862 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3863 return false;
3864 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003865 }
3866 }
3867 return true;
3868 }
3869
3870 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003871 * Checks if an uid has INTERNET permissions.
3872 * <p>
3873 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003874 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003875 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003876 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003877 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003878 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003879 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003880 }
3881 } catch (RemoteException e) {
3882 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003883 return true;
3884 }
3885
3886 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003887 * Clears all state - internal and external - associated with an UID.
3888 */
3889 private void onUidDeletedUL(int uid) {
3890 // First cleanup in-memory state synchronously...
3891 mUidRules.delete(uid);
3892 mUidPolicy.delete(uid);
3893 mUidFirewallStandbyRules.delete(uid);
3894 mUidFirewallDozableRules.delete(uid);
3895 mUidFirewallPowerSaveRules.delete(uid);
3896 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3897 mPowerSaveWhitelistAppIds.delete(uid);
3898 mPowerSaveTempWhitelistAppIds.delete(uid);
3899
3900 // ...then update iptables asynchronously.
3901 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3902 }
3903
3904 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003905 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003906 *
Felipe Leme781ba142016-05-09 16:24:48 -07003907 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003908 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003909 * <li>Doze mode
3910 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003911 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003912 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003913 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003914 *
3915 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003916 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003917 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003918 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003919 updateRuleForDeviceIdleUL(uid);
3920 updateRuleForAppIdleUL(uid);
3921 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003922
3923 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003924 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003925
3926 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003927 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003928 }
3929
Felipe Leme70c57c22016-03-29 10:45:13 -07003930 /**
3931 * Applies network rules to bandwidth controllers based on process state and user-defined
3932 * restrictions (blacklist / whitelist).
3933 *
3934 * <p>
3935 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3936 * networks:
3937 * <ul>
3938 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3939 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3940 * also blacklisted.
3941 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3942 * no UIDs other those whitelisted will have access.
3943 * <ul>
3944 *
3945 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3946 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3947 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3948 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003949 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003950 * {@link INetworkManagementService}, but this method should also be called in events (like
3951 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3952 * following rules should also be applied:
3953 *
3954 * <ul>
3955 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3956 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3957 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3958 * {@code bw_penalty_box}.
3959 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3960 * </ul>
3961 *
3962 * <p>For optimization, the rules are only applied on user apps that have internet access
3963 * permission, since there is no need to change the {@code iptables} rule if the app does not
3964 * have permission to use the internet.
3965 *
3966 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003967 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003968 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003969 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003970 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3971 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3972 "updateRulesForDataUsageRestrictionsUL: " + uid);
3973 }
3974 try {
3975 updateRulesForDataUsageRestrictionsULInner(uid);
3976 } finally {
3977 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3978 }
3979 }
3980
3981 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003982 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003983 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003984 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003985 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003986
Dianne Hackborn497175b2014-07-01 12:56:08 -07003987 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003988 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003989 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003990 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003991
Felipe Leme781ba142016-05-09 16:24:48 -07003992 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003993 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003994 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3995 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003996
Felipe Leme70c57c22016-03-29 10:45:13 -07003997 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003998 if (isRestrictedByAdmin) {
3999 newRule = RULE_REJECT_METERED;
4000 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004001 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4002 newRule = RULE_TEMPORARY_ALLOW_METERED;
4003 } else if (isWhitelisted) {
4004 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004005 }
4006 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004007 if (isBlacklisted) {
4008 newRule = RULE_REJECT_METERED;
4009 } else if (mRestrictBackground && isWhitelisted) {
4010 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004011 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004012 }
Felipe Leme781ba142016-05-09 16:24:48 -07004013 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004014
Felipe Lemef28983d2016-03-25 12:18:23 -07004015 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004016 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004017 + ": isForeground=" +isForeground
4018 + ", isBlacklisted=" + isBlacklisted
4019 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004020 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004021 + ", oldRule=" + uidRulesToString(oldRule)
4022 + ", newRule=" + uidRulesToString(newRule)
4023 + ", newUidRules=" + uidRulesToString(newUidRules)
4024 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004025 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004026
Felipe Leme46c4fc32016-05-04 09:21:43 -07004027 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004028 mUidRules.delete(uid);
4029 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004030 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004031 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004032
Felipe Leme70c57c22016-03-29 10:45:13 -07004033 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004034 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004035 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004036 // Temporarily whitelist foreground app, removing from blacklist if necessary
4037 // (since bw_penalty_box prevails over bw_happy_box).
4038
4039 setMeteredNetworkWhitelist(uid, true);
4040 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4041 // but ideally it should be just:
4042 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004043 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004044 setMeteredNetworkBlacklist(uid, false);
4045 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004046 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004047 // Remove temporary whitelist from app that is not on foreground anymore.
4048
4049 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4050 // but ideally they should be just:
4051 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4052 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004053 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004054 setMeteredNetworkWhitelist(uid, false);
4055 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004056 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004057 setMeteredNetworkBlacklist(uid, true);
4058 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004059 } else if (hasRule(newRule, RULE_REJECT_METERED)
4060 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004061 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004062 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004063 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004064 // Since blacklist prevails over whitelist, we need to handle the special case
4065 // where app is whitelisted and blacklisted at the same time (although such
4066 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004067 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004068 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004069 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4070 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004071 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004072 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004073 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004074 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004075 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4076 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004077 + ", whitelisted=" + isWhitelisted
4078 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004079 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004080 + ", newRule=" + uidRulesToString(newUidRules)
4081 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004082 }
Felipe Leme781ba142016-05-09 16:24:48 -07004083
Sudheer Shankac9d94072017-02-22 22:13:55 +00004084 // Dispatch changed rule to existing listeners.
4085 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004086 }
4087 }
4088
4089 /**
4090 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4091 * listeners in case of change.
4092 * <p>
4093 * There are 3 power-related rules that affects whether an app has background access on
4094 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4095 * restriction, it's added to the equivalent firewall chain:
4096 * <ul>
4097 * <li>App is idle: {@code fw_standby} firewall chain.
4098 * <li>Device is idle: {@code fw_dozable} firewall chain.
4099 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4100 * </ul>
4101 * <p>
4102 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4103 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4104 * <p>
4105 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4106 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004107 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004108 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4109
Sudheer Shankac9d94072017-02-22 22:13:55 +00004110 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004111
Sudheer Shankac9d94072017-02-22 22:13:55 +00004112 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004113 mUidRules.delete(uid);
4114 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004115 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004116 }
4117 }
4118
4119 /**
4120 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4121 *
4122 * @param uid the uid of the app to update rules for
4123 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4124 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4125 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004126 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004127 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004128 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004129 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4130 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4131 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4132 + (paroled ? "P" : "-"));
4133 }
4134 try {
4135 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4136 } finally {
4137 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4138 }
4139 }
4140
4141 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004142 if (!isUidValidForBlacklistRules(uid)) {
4143 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004144 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004145 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004146
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004147 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004148 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004149 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004150
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07004151 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004152 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4153 int newRule = RULE_NONE;
4154
4155 // First step: define the new rule based on user restrictions and foreground state.
4156
4157 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4158 // by considering the foreground and non-foreground states.
4159 if (isForeground) {
4160 if (restrictMode) {
4161 newRule = RULE_ALLOW_ALL;
4162 }
4163 } else if (restrictMode) {
4164 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4165 }
4166
4167 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4168
4169 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004170 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004171 + ", isIdle: " + isIdle
4172 + ", mRestrictPower: " + mRestrictPower
4173 + ", mDeviceIdleMode: " + mDeviceIdleMode
4174 + ", isForeground=" + isForeground
4175 + ", isWhitelisted=" + isWhitelisted
4176 + ", oldRule=" + uidRulesToString(oldRule)
4177 + ", newRule=" + uidRulesToString(newRule)
4178 + ", newUidRules=" + uidRulesToString(newUidRules)
4179 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4180 }
4181
Felipe Leme781ba142016-05-09 16:24:48 -07004182 // Second step: notify listeners if state changed.
4183 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004184 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004185 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004186 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004187 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4188 } else {
4189 // All scenarios should have been covered above
4190 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4191 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004192 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004193 + ", newRule=" + uidRulesToString(newUidRules)
4194 + ", oldRule=" + uidRulesToString(oldUidRules));
4195 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004196 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004197 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004198
Sudheer Shankac9d94072017-02-22 22:13:55 +00004199 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004200 }
4201
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004202 private class AppIdleStateChangeListener
4203 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4204
4205 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004206 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4207 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004208 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004209 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4210 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004211 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004212 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004213 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004214 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004215 }
4216 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004217 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004218 }
4219
4220 @Override
4221 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004222 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004223 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004224 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004225 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004226 }
4227 }
4228
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004229 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4230 if (listener != null) {
4231 try {
4232 listener.onUidRulesChanged(uid, uidRules);
4233 } catch (RemoteException ignored) {
4234 }
4235 }
4236 }
4237
4238 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4239 String[] meteredIfaces) {
4240 if (listener != null) {
4241 try {
4242 listener.onMeteredIfacesChanged(meteredIfaces);
4243 } catch (RemoteException ignored) {
4244 }
4245 }
4246 }
4247
4248 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4249 boolean restrictBackground) {
4250 if (listener != null) {
4251 try {
4252 listener.onRestrictBackgroundChanged(restrictBackground);
4253 } catch (RemoteException ignored) {
4254 }
4255 }
4256 }
4257
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004258 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4259 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004260 if (listener != null) {
4261 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004262 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004263 } catch (RemoteException ignored) {
4264 }
4265 }
4266 }
4267
Jeff Sharkey9252b342018-01-19 07:58:35 +09004268 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4269 int overrideMask, int overrideValue) {
4270 if (listener != null) {
4271 try {
4272 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4273 } catch (RemoteException ignored) {
4274 }
4275 }
4276 }
4277
Makoto Onuki8e777332017-03-28 11:25:47 -07004278 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004279 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004280 public boolean handleMessage(Message msg) {
4281 switch (msg.what) {
4282 case MSG_RULES_CHANGED: {
4283 final int uid = msg.arg1;
4284 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004285 final int length = mListeners.beginBroadcast();
4286 for (int i = 0; i < length; i++) {
4287 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4288 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004289 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004290 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004291 return true;
4292 }
4293 case MSG_METERED_IFACES_CHANGED: {
4294 final String[] meteredIfaces = (String[]) msg.obj;
4295 final int length = mListeners.beginBroadcast();
4296 for (int i = 0; i < length; i++) {
4297 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004298 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004299 }
4300 mListeners.finishBroadcast();
4301 return true;
4302 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004303 case MSG_LIMIT_REACHED: {
4304 final String iface = (String) msg.obj;
4305
Felipe Lemef0823852016-06-08 13:43:08 -07004306 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004307 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004308 // force stats update to make sure we have
4309 // numbers that caused alert to trigger.
4310 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004311
Felipe Lemef0823852016-06-08 13:43:08 -07004312 updateNetworkEnabledNL();
4313 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004314 }
4315 }
4316 return true;
4317 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004318 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4319 final boolean restrictBackground = msg.arg1 != 0;
4320 final int length = mListeners.beginBroadcast();
4321 for (int i = 0; i < length; i++) {
4322 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004323 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004324 }
4325 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004326 final Intent intent =
4327 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4328 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4329 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4330 return true;
4331 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004332 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004333 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004334 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004335 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004336 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004337 final int length = mListeners.beginBroadcast();
4338 for (int i = 0; i < length; i++) {
4339 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004340 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004341 }
4342 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004343 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4344 if (notifyApp.booleanValue()) {
4345 broadcastRestrictBackgroundChanged(uid, notifyApp);
4346 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004347 return true;
4348 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004349 case MSG_ADVISE_PERSIST_THRESHOLD: {
4350 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004351 // make sure stats are recorded frequently enough; we aim
4352 // for 2MB threshold for 2GB/month rules.
4353 final long persistThreshold = lowestRule / 1000;
4354 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004355 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004356 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004357 case MSG_UPDATE_INTERFACE_QUOTA: {
4358 removeInterfaceQuota((String) msg.obj);
4359 // int params need to be stitched back into a long
4360 setInterfaceQuota((String) msg.obj,
4361 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4362 return true;
4363 }
4364 case MSG_REMOVE_INTERFACE_QUOTA: {
4365 removeInterfaceQuota((String) msg.obj);
4366 return true;
4367 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004368 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4369 resetUidFirewallRules(msg.arg1);
4370 return true;
4371 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004372 case MSG_SUBSCRIPTION_OVERRIDE: {
4373 final int overrideMask = msg.arg1;
4374 final int overrideValue = msg.arg2;
4375 final int subId = (int) msg.obj;
4376 final int length = mListeners.beginBroadcast();
4377 for (int i = 0; i < length; i++) {
4378 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4379 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4380 }
4381 mListeners.finishBroadcast();
4382 return true;
4383 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004384 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4385 final int userId = msg.arg1;
4386 final Set<String> packageNames = (Set<String>) msg.obj;
4387 setMeteredRestrictedPackagesInternal(packageNames, userId);
4388 return true;
4389 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004390 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4391 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4392 final boolean enabled = msg.arg1 != 0;
4393 setNetworkTemplateEnabledInner(template, enabled);
4394 return true;
4395 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004396 default: {
4397 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004398 }
4399 }
4400 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004401 };
4402
4403 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4404 @Override
4405 public boolean handleMessage(Message msg) {
4406 switch (msg.what) {
4407 case UID_MSG_STATE_CHANGED: {
4408 final int uid = msg.arg1;
4409 final int procState = msg.arg2;
4410 final long procStateSeq = (Long) msg.obj;
4411
4412 handleUidChanged(uid, procState, procStateSeq);
4413 return true;
4414 }
4415 case UID_MSG_GONE: {
4416 final int uid = msg.arg1;
4417 handleUidGone(uid);
4418 return true;
4419 }
4420 default: {
4421 return false;
4422 }
4423 }
4424 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004425
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004426 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004427
Makoto Onuki8e777332017-03-28 11:25:47 -07004428 void handleUidChanged(int uid, int procState, long procStateSeq) {
4429 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4430 try {
4431 synchronized (mUidRulesFirstLock) {
4432 // We received a uid state change callback, add it to the history so that it
4433 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004434 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004435 // Now update the network policy rules as per the updated uid state.
4436 updateUidStateUL(uid, procState);
4437 // Updating the network rules is done, so notify AMS about this.
4438 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4439 }
4440 } finally {
4441 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4442 }
4443 }
4444
4445 void handleUidGone(int uid) {
4446 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4447 try {
4448 synchronized (mUidRulesFirstLock) {
4449 removeUidStateUL(uid);
4450 }
4451 } finally {
4452 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4453 }
4454 }
4455
Felipe Leme57e3d312016-08-23 14:42:52 -07004456 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4457 final PackageManager pm = mContext.getPackageManager();
4458 final String[] packages = pm.getPackagesForUid(uid);
4459 if (packages != null) {
4460 final int userId = UserHandle.getUserId(uid);
4461 for (String packageName : packages) {
4462 final Intent intent =
4463 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4464 intent.setPackage(packageName);
4465 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4466 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4467 }
4468 }
4469 }
4470
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004471 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4472 // long quotaBytes split up into two ints to fit in message
4473 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4474 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4475 }
4476
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004477 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004478 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004479 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004480 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004481 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004482 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004483 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004484 }
4485 }
4486
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004487 private void removeInterfaceQuotaAsync(String iface) {
4488 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4489 }
4490
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004491 private void removeInterfaceQuota(String iface) {
4492 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004493 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004494 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004495 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004496 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004497 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004498 }
4499 }
4500
Felipe Leme70c57c22016-03-29 10:45:13 -07004501 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4502 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004503 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004504 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004505 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004506 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4507 } catch (RemoteException e) {
4508 // ignored; service lives in system_server
4509 }
4510 }
4511
4512 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4513 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4514 try {
4515 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4516 } catch (IllegalStateException e) {
4517 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004518 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004519 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004520 }
4521 }
4522
Felipe Lemebc853dd2016-09-08 13:26:55 -07004523 private static final int CHAIN_TOGGLE_NONE = 0;
4524 private static final int CHAIN_TOGGLE_ENABLE = 1;
4525 private static final int CHAIN_TOGGLE_DISABLE = 2;
4526 @Retention(RetentionPolicy.SOURCE)
4527 @IntDef(flag = false, value = {
4528 CHAIN_TOGGLE_NONE,
4529 CHAIN_TOGGLE_ENABLE,
4530 CHAIN_TOGGLE_DISABLE
4531 })
4532 public @interface ChainToggleType {
4533 }
4534
4535 /**
4536 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004537 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004538 *
4539 * @param chain firewall chain.
4540 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4541 * @param toggle whether the chain should be enabled, disabled, or not changed.
4542 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004543 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004544 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004545 if (uidRules != null) {
4546 setUidFirewallRulesUL(chain, uidRules);
4547 }
4548 if (toggle != CHAIN_TOGGLE_NONE) {
4549 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4550 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004551 }
4552
Amith Yamasani15e472352015-04-24 19:06:07 -07004553 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004554 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4555 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4556 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004557 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004558 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004559 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004560 int size = uidRules.size();
4561 int[] uids = new int[size];
4562 int[] rules = new int[size];
4563 for(int index = size - 1; index >= 0; --index) {
4564 uids[index] = uidRules.keyAt(index);
4565 rules[index] = uidRules.valueAt(index);
4566 }
4567 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004568 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004569 } catch (IllegalStateException e) {
4570 Log.wtf(TAG, "problem setting firewall uid rules", e);
4571 } catch (RemoteException e) {
4572 // ignored; service lives in system_server
4573 }
4574 }
4575
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004576 /**
4577 * Add or remove a uid to the firewall blacklist for all network ifaces.
4578 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004579 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004580 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4581 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4582 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004583 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004584 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004585 if (chain == FIREWALL_CHAIN_DOZABLE) {
4586 mUidFirewallDozableRules.put(uid, rule);
4587 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4588 mUidFirewallStandbyRules.put(uid, rule);
4589 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4590 mUidFirewallPowerSaveRules.put(uid, rule);
4591 }
4592
4593 try {
4594 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004595 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004596 } catch (IllegalStateException e) {
4597 Log.wtf(TAG, "problem setting firewall uid rules", e);
4598 } catch (RemoteException e) {
4599 // ignored; service lives in system_server
4600 }
4601 } finally {
4602 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004603 }
4604 }
4605
4606 /**
4607 * Add or remove a uid to the firewall blacklist for all network ifaces.
4608 */
Felipe Lemef0823852016-06-08 13:43:08 -07004609 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004610 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4611 mFirewallChainStates.get(chain) == enable) {
4612 // All is the same, nothing to do.
4613 return;
4614 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004615 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004616 try {
4617 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004618 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004619 } catch (IllegalStateException e) {
4620 Log.wtf(TAG, "problem enable firewall chain", e);
4621 } catch (RemoteException e) {
4622 // ignored; service lives in system_server
4623 }
4624 }
4625
Felipe Leme03e95e22016-09-09 09:25:31 -07004626 /**
4627 * Resets all firewall rules associated with an UID.
4628 */
4629 private void resetUidFirewallRules(int uid) {
4630 try {
4631 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4632 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4633 mNetworkManager
4634 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4635 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4636 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4637 } catch (IllegalStateException e) {
4638 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4639 } catch (RemoteException e) {
4640 // ignored; service lives in system_server
4641 }
4642 }
4643
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004644 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004645 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004646 return getNetworkTotalBytes(template, start, end);
4647 }
4648
4649 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004650 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004651 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004652 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004653 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004654 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004655 }
4656 }
4657
4658 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4659 try {
4660 return mNetworkStats.getNetworkUidBytes(template, start, end);
4661 } catch (RuntimeException e) {
4662 Slog.w(TAG, "Failed to read network stats: " + e);
4663 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004664 }
4665 }
4666
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004667 private boolean isBandwidthControlEnabled() {
4668 final long token = Binder.clearCallingIdentity();
4669 try {
4670 return mNetworkManager.isBandwidthControlEnabled();
4671 } catch (RemoteException e) {
4672 // ignored; service lives in system_server
4673 return false;
4674 } finally {
4675 Binder.restoreCallingIdentity(token);
4676 }
4677 }
4678
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004679 private static Intent buildAllowBackgroundDataIntent() {
4680 return new Intent(ACTION_ALLOW_BACKGROUND);
4681 }
4682
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004683 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4684 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004685 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4686 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4687 return intent;
4688 }
4689
4690 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4691 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4692 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004693 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4694 return intent;
4695 }
4696
Wei Liu546cb772016-07-21 16:19:01 -07004697 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004698 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004699 intent.setComponent(ComponentName.unflattenFromString(
4700 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004701 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4702 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4703 return intent;
4704 }
4705
Wei Liu546cb772016-07-21 16:19:01 -07004706 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004707 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004708 intent.setComponent(ComponentName.unflattenFromString(
4709 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004710 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4711 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4712 return intent;
4713 }
4714
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004715 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004716 public void addIdleHandler(IdleHandler handler) {
4717 mHandler.getLooper().getQueue().addIdleHandler(handler);
4718 }
4719
jackqdyulei29c82ab2017-03-10 14:09:16 -08004720 @VisibleForTesting
4721 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4722 mRestrictBackgroundPowerState = result;
4723
4724 boolean restrictBackground = result.batterySaverEnabled;
4725 boolean shouldInvokeRestrictBackground;
4726 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4727 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4728
4729 if (result.globalBatterySaverEnabled) {
4730 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4731 // turn it on.
4732 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4733 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4734 localRestrictBgChangedInBsm = false;
4735 } else {
4736 // Try to restore the restrictBackground if it doesn't change in bsm
4737 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4738 restrictBackground = mRestrictBackgroundBeforeBsm;
4739 }
4740
4741 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004742 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004743 }
4744
4745 // Change it at last so setRestrictBackground() won't affect this variable
4746 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4747 }
4748
Jeff Sharkey1b861272011-05-22 00:34:52 -07004749 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4750 final int size = source.size();
4751 for (int i = 0; i < size; i++) {
4752 target.put(source.keyAt(i), true);
4753 }
4754 }
4755
Stuart Scottf1fb3972015-04-02 18:00:02 -07004756 @Override
4757 public void factoryReset(String subscriber) {
4758 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4759
Stuart Scotte3e314d2015-04-20 14:07:45 -07004760 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4761 return;
4762 }
4763
Stuart Scottf1fb3972015-04-02 18:00:02 -07004764 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004765 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004766 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4767 for (NetworkPolicy policy : policies) {
4768 if (policy.template.equals(template)) {
4769 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4770 policy.inferred = false;
4771 policy.clearSnooze();
4772 }
4773 }
4774 setNetworkPolicies(policies);
4775
4776 // Turn restrict background data off
4777 setRestrictBackground(false);
4778
Stuart Scotte3e314d2015-04-20 14:07:45 -07004779 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4780 // Remove app's "restrict background data" flag
4781 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4782 setUidPolicy(uid, POLICY_NONE);
4783 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004784 }
4785 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004786
Sudheer Shankab8f23162017-08-04 13:30:10 -07004787 @Override
4788 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004789 final long startTime = mStatLogger.getTime();
4790
Sudheer Shankab8f23162017-08-04 13:30:10 -07004791 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Makoto Onuki49392d32018-04-11 13:51:02 -07004792 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4793
4794 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4795
4796 return ret;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004797 }
4798
4799 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4800 final int uidRules;
4801 final boolean isBackgroundRestricted;
4802 synchronized (mUidRulesFirstLock) {
4803 uidRules = mUidRules.get(uid, RULE_NONE);
4804 isBackgroundRestricted = mRestrictBackground;
4805 }
4806 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004807 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004808 return true;
4809 }
4810 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004811 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004812 return false;
4813 }
4814 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004815 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004816 return true;
4817 }
4818 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004819 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004820 return false;
4821 }
4822 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004823 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004824 return false;
4825 }
4826 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004827 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004828 return true;
4829 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004830 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004831 return false;
4832 }
4833
Felipe Lemed17fda42016-04-29 11:12:45 -07004834 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4835
4836 @Override
4837 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004838 synchronized (mUidRulesFirstLock) {
4839 boolean changed = removeUserStateUL(userId, false);
4840 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004841 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004842 synchronized (mNetworkPoliciesSecondLock) {
4843 writePolicyAL();
4844 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004845 }
4846 }
4847 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004848
4849 /**
4850 * @return true if the given uid is restricted from doing networking on metered networks.
4851 */
4852 @Override
4853 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4854 final int uidRules;
4855 final boolean isBackgroundRestricted;
4856 synchronized (mUidRulesFirstLock) {
4857 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4858 isBackgroundRestricted = mRestrictBackground;
4859 }
4860 return isBackgroundRestricted
4861 && !hasRule(uidRules, RULE_ALLOW_METERED)
4862 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4863 }
4864
4865 /**
4866 * @return true if networking is blocked on the given interface for the given uid according
4867 * to current networking policies.
4868 */
4869 @Override
4870 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004871 final long startTime = mStatLogger.getTime();
4872
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004873 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004874 synchronized (mNetworkPoliciesSecondLock) {
4875 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004876 }
Makoto Onuki49392d32018-04-11 13:51:02 -07004877 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4878
4879 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4880
4881 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004882 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004883
4884 @Override
4885 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4886 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004887 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004888 if (added) {
4889 mPowerSaveTempWhitelistAppIds.put(appId, true);
4890 } else {
4891 mPowerSaveTempWhitelistAppIds.delete(appId);
4892 }
4893 updateRulesForTempWhitelistChangeUL(appId);
4894 }
4895 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004896
4897 @Override
4898 public SubscriptionPlan getSubscriptionPlan(Network network) {
4899 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004900 final int subId = getSubIdLocked(network);
4901 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004902 }
4903 }
4904
4905 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06004906 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
4907 synchronized (mNetworkPoliciesSecondLock) {
4908 final int subId = findRelevantSubIdNL(template);
4909 return getPrimarySubscriptionPlanLocked(subId);
4910 }
4911 }
4912
4913 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09004914 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004915 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004916 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004917 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004918 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004919 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004920 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4921 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4922 }
4923
4924 if (quotaType == QUOTA_TYPE_JOBS) {
4925 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4926 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4927 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4928 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4929 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4930 } else {
4931 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4932 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004933 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004934
4935 @Override
4936 public void onAdminDataAvailable() {
4937 mAdminDataAvailableLatch.countDown();
4938 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004939
4940 @Override
4941 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4942 setMeteredRestrictedPackagesInternal(packageNames, userId);
4943 }
4944
4945 @Override
4946 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4947 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4948 userId, 0, packageNames).sendToTarget();
4949 }
4950 }
4951
4952 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4953 synchronized (mUidRulesFirstLock) {
4954 final Set<Integer> newRestrictedUids = new ArraySet<>();
4955 for (String packageName : packageNames) {
4956 final int uid = getUidForPackage(packageName, userId);
4957 if (uid >= 0) {
4958 newRestrictedUids.add(uid);
4959 }
4960 }
4961 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4962 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4963 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4964 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4965 }
4966 }
4967
4968 private int getUidForPackage(String packageName, int userId) {
4969 try {
4970 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4971 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4972 } catch (NameNotFoundException e) {
4973 return -1;
4974 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004975 }
4976
4977 private int parseSubId(NetworkState state) {
4978 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4979 int subId = INVALID_SUBSCRIPTION_ID;
4980 if (state != null && state.networkCapabilities != null
4981 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4982 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4983 if (spec instanceof StringNetworkSpecifier) {
4984 try {
4985 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4986 } catch (NumberFormatException e) {
4987 }
4988 }
4989 }
4990 return subId;
4991 }
4992
Andreas Gampea36dc622018-02-05 17:19:22 -08004993 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004994 private int getSubIdLocked(Network network) {
4995 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004996 }
4997
Andreas Gampea36dc622018-02-05 17:19:22 -08004998 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004999 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5000 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005001 if (!ArrayUtils.isEmpty(plans)) {
5002 for (SubscriptionPlan plan : plans) {
5003 if (plan.getCycleRule().isRecurring()) {
5004 // Recurring plans will always have an active cycle
5005 return plan;
5006 } else {
5007 // Non-recurring plans need manual test for active cycle
5008 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5009 if (cycle.contains(ZonedDateTime.now(mClock))) {
5010 return plan;
5011 }
5012 }
5013 }
5014 }
5015 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005016 }
5017
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005018 /**
5019 * This will only ever be called once - during device boot.
5020 */
5021 private void waitForAdminData() {
5022 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5023 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5024 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5025 }
5026 }
5027
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005028 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5029 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005030 if (!mNetworkManagerReady) {
5031 return;
5032 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005033 if (oldRestrictedUids == null) {
5034 for (int uid : newRestrictedUids) {
5035 updateRulesForDataUsageRestrictionsUL(uid);
5036 }
5037 return;
5038 }
5039 for (int uid : oldRestrictedUids) {
5040 if (!newRestrictedUids.contains(uid)) {
5041 updateRulesForDataUsageRestrictionsUL(uid);
5042 }
5043 }
5044 for (int uid : newRestrictedUids) {
5045 if (!oldRestrictedUids.contains(uid)) {
5046 updateRulesForDataUsageRestrictionsUL(uid);
5047 }
5048 }
5049 }
5050
5051 private boolean isRestrictedByAdminUL(int uid) {
5052 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5053 UserHandle.getUserId(uid));
5054 return restrictedUids != null && restrictedUids.contains(uid);
5055 }
5056
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005057 private static boolean hasRule(int uidRules, int rule) {
5058 return (uidRules & rule) != 0;
5059 }
5060
Jeff Sharkey2e471452018-01-19 18:02:47 +09005061 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5062 return (val != null) ? val : new NetworkState[0];
5063 }
5064
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005065 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5066 String key, boolean defaultValue) {
5067 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5068 }
5069
Chris Wren193ae6b2017-03-31 15:17:11 -04005070 private class NotificationId {
5071 private final String mTag;
5072 private final int mId;
5073
5074 NotificationId(NetworkPolicy policy, int type) {
5075 mTag = buildNotificationTag(policy, type);
5076 mId = type;
5077 }
5078
5079 @Override
5080 public boolean equals(Object o) {
5081 if (this == o) return true;
5082 if (!(o instanceof NotificationId)) return false;
5083 NotificationId that = (NotificationId) o;
5084 return Objects.equals(mTag, that.mTag);
5085 }
5086
5087 @Override
5088 public int hashCode() {
5089 return Objects.hash(mTag);
5090 }
5091
5092 /**
5093 * Build unique tag that identifies an active {@link NetworkPolicy}
5094 * notification of a specific type, like {@link #TYPE_LIMIT}.
5095 */
5096 private String buildNotificationTag(NetworkPolicy policy, int type) {
5097 return TAG + ":" + policy.template.hashCode() + ":" + type;
5098 }
5099
5100 public String getTag() {
5101 return mTag;
5102 }
5103
5104 public int getId() {
5105 return mId;
5106 }
5107 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005108}