blob: 76f969508b28bd02a3cecb2c69ed1a469d8ac137 [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
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700631 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700632 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700633 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700634 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
635 mPowerSaveWhitelistExceptIdleAppIds.clear();
636 if (whitelist != null) {
637 for (int uid : whitelist) {
638 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
639 }
640 }
641 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700642 mPowerSaveWhitelistAppIds.clear();
643 if (whitelist != null) {
644 for (int uid : whitelist) {
645 mPowerSaveWhitelistAppIds.put(uid, true);
646 }
647 }
648 } catch (RemoteException e) {
649 }
650 }
651
Felipe Lemea9505cc2016-02-26 10:28:41 -0800652 /**
653 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
654 * revoke the whitelist.
655 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700656 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800657 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700658 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700659 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800660 final List<UserInfo> users = mUserManager.getUsers();
661 final int numberUsers = users.size();
662
Felipe Lemea110eec2016-04-29 09:58:06 -0700663 boolean changed = false;
664 for (int i = 0; i < numberUsers; i++) {
665 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700666 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700667 }
668 return changed;
669 }
670
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700671 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700672 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700673 final SystemConfig sysConfig = SystemConfig.getInstance();
674 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800675 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
676 boolean changed = false;
677 for (int i = 0; i < allowDataUsage.size(); i++) {
678 final String pkg = allowDataUsage.valueAt(i);
679 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700680 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
681 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800682 final ApplicationInfo app;
683 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700684 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800685 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700686 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
687 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800688 continue;
689 }
690 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700691 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
692 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800693 continue;
694 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700695 final int uid = UserHandle.getUid(userId, app.uid);
696 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
697 if (LOGD)
698 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
699 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800700 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700701 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700702 if (LOGD)
703 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
704 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700705 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700706 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800707 }
708 }
709 return changed;
710 }
711
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800712 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700713 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800714 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700715 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800716 // Boost thread's priority during system server init
717 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700718 if (!isBandwidthControlEnabled()) {
719 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
720 return;
721 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700722
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700724 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700725
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 synchronized (mUidRulesFirstLock) {
727 synchronized (mNetworkPoliciesSecondLock) {
728 updatePowerSaveWhitelistUL();
729 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
730 mPowerManagerInternal.registerLowPowerModeObserver(
731 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800732 @Override
733 public int getServiceType() {
734 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700735 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800736
737 @Override
738 public void onLowPowerModeChanged(PowerSaveState result) {
739 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800740 if (LOGD) {
741 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
742 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800743 synchronized (mUidRulesFirstLock) {
744 if (mRestrictPower != enabled) {
745 mRestrictPower = enabled;
746 updateRulesForRestrictPowerUL();
747 }
748 }
749 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800750 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800751 mRestrictPower = mPowerManagerInternal.getLowPowerState(
752 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700753
754 mSystemReady = true;
755
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800756 waitForAdminData();
757
Felipe Leme873a83a2016-09-07 11:34:10 -0700758 // read policy from disk
759 readPolicyAL();
760
jackqdyulei29c82ab2017-03-10 14:09:16 -0800761 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700762 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800763 mRestrictBackgroundPowerState = mPowerManagerInternal
764 .getLowPowerState(ServiceType.DATA_SAVER);
765 final boolean localRestrictBackground =
766 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700767 if (localRestrictBackground && !mLoadedRestrictBackground) {
768 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800769 }
770 mPowerManagerInternal.registerLowPowerModeObserver(
771 new PowerManagerInternal.LowPowerModeListener() {
772 @Override
773 public int getServiceType() {
774 return ServiceType.DATA_SAVER;
775 }
776
777 @Override
778 public void onLowPowerModeChanged(PowerSaveState result) {
779 synchronized (mUidRulesFirstLock) {
780 updateRestrictBackgroundByLowPowerModeUL(result);
781 }
782 }
783 });
784
Felipe Leme873a83a2016-09-07 11:34:10 -0700785 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
786 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700787 }
Felipe Lemef0823852016-06-08 13:43:08 -0700788
Sudheer Shanka543339f2017-07-28 15:18:07 -0700789 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700790 updateRulesForGlobalChangeAL(false);
791 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700792 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800793 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700794
Sudheer Shankae7361852017-03-07 11:51:46 -0800795 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 try {
797 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000798 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800799 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700800 mNetworkManager.registerObserver(mAlertObserver);
801 } catch (RemoteException e) {
802 // ignored; both services live in system_server
803 }
804
805 // listen for changes to power save whitelist
806 final IntentFilter whitelistFilter = new IntentFilter(
807 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
808 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
809
Felipe Leme873a83a2016-09-07 11:34:10 -0700810 // watch for network interfaces to be claimed
811 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
812 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
813
814 // listen for package changes to update policy
815 final IntentFilter packageFilter = new IntentFilter();
816 packageFilter.addAction(ACTION_PACKAGE_ADDED);
817 packageFilter.addDataScheme("package");
818 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
819
820 // listen for UID changes to update policy
821 mContext.registerReceiver(
822 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
823
824 // listen for user changes to update policy
825 final IntentFilter userFilter = new IntentFilter();
826 userFilter.addAction(ACTION_USER_ADDED);
827 userFilter.addAction(ACTION_USER_REMOVED);
828 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
829
830 // listen for stats update events
831 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
832 mContext.registerReceiver(
833 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
834
835 // listen for restrict background changes from notifications
836 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
837 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
838
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700839 // Listen for snooze from notifications
840 mContext.registerReceiver(mSnoozeReceiver,
841 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
842 mContext.registerReceiver(mSnoozeReceiver,
843 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700844
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600845 // listen for configured wifi networks to be loaded
846 final IntentFilter wifiFilter =
847 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
848 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700849
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700850 // listen for carrier config changes to update data cycle information
851 final IntentFilter carrierConfigFilter = new IntentFilter(
852 ACTION_CARRIER_CONFIG_CHANGED);
853 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
854
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600855 // listen for meteredness changes
856 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
857 new NetworkRequest.Builder().build(), mNetworkCallback);
858
Felipe Leme873a83a2016-09-07 11:34:10 -0700859 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600860
861 // Listen for subscriber changes
862 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
863 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
864 @Override
865 public void onSubscriptionsChanged() {
866 updateNetworksInternal();
867 }
868 });
869
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800870 // tell systemReady() that the service has been initialized
871 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700872 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800873 // Restore the default priority after init is done
874 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700875 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700876 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700877 }
878
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800879 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700880 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800881 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
882 mHandler.post(() -> initService(initCompleteSignal));
883 return initCompleteSignal;
884 }
885
886 public void systemReady(CountDownLatch initCompleteSignal) {
887 // wait for initService to complete
888 try {
889 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
890 throw new IllegalStateException("Service " + TAG +" init timeout");
891 }
892 } catch (InterruptedException e) {
893 Thread.currentThread().interrupt();
894 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
895 }
896 }
897
Sudheer Shankac9d94072017-02-22 22:13:55 +0000898 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700899 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700900 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
901 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700902 }
903
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700904 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700905 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700906 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700907
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700908 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700909 }
910
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700911 @Override public void onUidIdle(int uid, boolean disabled) {
912 }
913
914 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700915 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700916 };
917
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700918 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700919 @Override
920 public void onReceive(Context context, Intent intent) {
921 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700922 synchronized (mUidRulesFirstLock) {
923 updatePowerSaveWhitelistUL();
924 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700925 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700926 }
927 }
928 };
929
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700931 @Override
932 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700933 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700934
935 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700936 final int uid = intent.getIntExtra(EXTRA_UID, -1);
937 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700938
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700939 if (ACTION_PACKAGE_ADDED.equals(action)) {
940 // update rules for UID, since it might be subject to
941 // global background data policy
942 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700943 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700944 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700945 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700946 }
947 }
948 };
949
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700950 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700951 @Override
952 public void onReceive(Context context, Intent intent) {
953 // on background handler thread, and UID_REMOVED is protected
954
955 final int uid = intent.getIntExtra(EXTRA_UID, -1);
956 if (uid == -1) return;
957
958 // remove any policy and update rules to clean up
959 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700960 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700961 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700962 synchronized (mNetworkPoliciesSecondLock) {
963 writePolicyAL();
964 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700965 }
966 }
967 };
968
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700969 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700970 @Override
971 public void onReceive(Context context, Intent intent) {
972 // on background handler thread, and USER_ADDED and USER_REMOVED
973 // broadcasts are protected
974
975 final String action = intent.getAction();
976 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
977 if (userId == -1) return;
978
Amith Yamasani15e472352015-04-24 19:06:07 -0700979 switch (action) {
980 case ACTION_USER_REMOVED:
981 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700982 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800983 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700984 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700985 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800986 // Removing outside removeUserStateUL since that can also be called when
987 // user resets app preferences.
988 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700989 if (action == ACTION_USER_ADDED) {
990 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700991 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700992 }
993 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700994 synchronized (mNetworkPoliciesSecondLock) {
995 updateRulesForGlobalChangeAL(true);
996 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700997 }
998 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700999 }
1000 }
1001 };
1002
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001003 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001004 * Receiver that watches for {@link INetworkStatsService} updates, which we
1005 * use to check against {@link NetworkPolicy#warningBytes}.
1006 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001007 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001008 @Override
1009 public void onReceive(Context context, Intent intent) {
1010 // on background handler thread, and verified
1011 // READ_NETWORK_USAGE_HISTORY permission above.
1012
Felipe Lemef0823852016-06-08 13:43:08 -07001013 synchronized (mNetworkPoliciesSecondLock) {
1014 updateNetworkEnabledNL();
1015 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 }
1017 }
1018 };
1019
1020 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001021 * Receiver that watches for {@link Notification} control of
1022 * {@link #mRestrictBackground}.
1023 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001024 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001025 @Override
1026 public void onReceive(Context context, Intent intent) {
1027 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1028 // permission above.
1029
1030 setRestrictBackground(false);
1031 }
1032 };
1033
1034 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001035 * Receiver that watches for {@link Notification} control of
1036 * {@link NetworkPolicy#lastWarningSnooze}.
1037 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001038 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001039 @Override
1040 public void onReceive(Context context, Intent intent) {
1041 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1042 // permission above.
1043
1044 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001045 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1046 performSnooze(template, TYPE_WARNING);
1047 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1048 performSnooze(template, TYPE_RAPID);
1049 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001050 }
1051 };
1052
1053 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001054 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001055 * we can perform upgrade logic. After initial upgrade logic, it updates
1056 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001057 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001058 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001059 @Override
1060 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001061 synchronized (mUidRulesFirstLock) {
1062 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001063 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001064 }
1065 }
1066 // Only need to perform upgrade logic once
1067 mContext.unregisterReceiver(this);
1068 }
1069 };
1070
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001071 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1072 Network network) {
1073 final boolean lastValue = lastValues.get(network.netId, false);
1074 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1075 if (changed) {
1076 lastValues.put(network.netId, newValue);
1077 }
1078 return changed;
1079 }
1080
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001081 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1082 @Override
1083 public void onCapabilitiesChanged(Network network,
1084 NetworkCapabilities networkCapabilities) {
1085 if (network == null || networkCapabilities == null) return;
1086
1087 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001088 final boolean newMetered = !networkCapabilities
1089 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001090 final boolean meteredChanged = updateCapabilityChange(
1091 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001092
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001093 final boolean newRoaming = !networkCapabilities
1094 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1095 final boolean roamingChanged = updateCapabilityChange(
1096 mNetworkRoaming, newRoaming, network);
1097
1098 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001099 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001100 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001101 }
1102 }
1103 }
1104 };
1105
1106 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001107 * Observer that watches for {@link INetworkManagementService} alerts.
1108 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001109 final private INetworkManagementEventObserver mAlertObserver
1110 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001111 @Override
1112 public void limitReached(String limitName, String iface) {
1113 // only someone like NMS should be calling us
1114 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1115
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001116 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1117 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 }
1119 }
1120 };
1121
1122 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001123 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1124 * to show visible notifications as needed.
1125 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001126 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001127 void updateNotificationsNL() {
1128 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001129 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001131 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001132 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134
1135 // TODO: when switching to kernel notifications, compute next future
1136 // cycle boundary to recompute notifications.
1137
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001138 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001139 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001140 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1141 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001142 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001143
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001145 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001146 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147
Jeff Sharkey53313d72017-07-13 16:47:32 -06001148 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1149 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001150 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1151 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1152 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001153
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001154 // Carrier might want to manage notifications themselves
1155 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1156 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1157 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1158 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1159 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1160 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1161 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1162
1163 // Notify when data usage is over warning
1164 if (notifyWarning) {
1165 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1166 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1167 if (!snoozedThisCycle) {
1168 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1169 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001170 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001171 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001172
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001173 // Notify when data usage is over limit
1174 if (notifyLimit) {
1175 if (policy.isOverLimit(totalBytes)) {
1176 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1177 if (snoozedThisCycle) {
1178 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1179 } else {
1180 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1181 notifyOverLimitNL(policy.template);
1182 }
1183 } else {
1184 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001185 }
1186 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001187
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001188 // Warn if average usage over last 4 days is on track to blow pretty
1189 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001190 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001191 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001192 final long recentStart = now - recentDuration;
1193 final long recentEnd = now;
1194 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001195
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001196 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001197 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001198 final long alertBytes = (policy.limitBytes * 3) / 2;
1199
1200 if (LOGD) {
1201 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1202 + projectedBytes + " alert " + alertBytes);
1203 }
1204
1205 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1206 - DateUtils.DAY_IN_MILLIS;
1207 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001208 enqueueNotification(policy, TYPE_RAPID, 0,
1209 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001210 }
1211 }
1212 }
1213
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001214 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001215 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001216 final NotificationId notificationId = beforeNotifs.valueAt(i);
1217 if (!mActiveNotifs.contains(notificationId)) {
1218 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001219 }
1220 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001221
1222 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001223 }
1224
1225 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001226 * Attempt to find a specific app to blame for rapid data usage during the
1227 * given time period.
1228 */
1229 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1230 long start, long end) {
1231 long totalBytes = 0;
1232 long maxBytes = 0;
1233 int maxUid = 0;
1234
1235 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1236 NetworkStats.Entry entry = null;
1237 for (int i = 0; i < stats.size(); i++) {
1238 entry = stats.getValues(i, entry);
1239 final long bytes = entry.rxBytes + entry.txBytes;
1240 totalBytes += bytes;
1241 if (bytes > maxBytes) {
1242 maxBytes = bytes;
1243 maxUid = entry.uid;
1244 }
1245 }
1246
1247 // Only point blame if the majority of usage was done by a single app.
1248 // TODO: support shared UIDs
1249 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1250 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001251 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001252 try {
1253 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1254 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1255 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1256 } catch (NameNotFoundException ignored) {
1257 }
1258 }
1259 }
1260
1261 return null;
1262 }
1263
1264 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001265 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001266 * current device state, such as when
1267 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1268 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001269 *
1270 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1271 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001272 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001273 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001274 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001275 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001276 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1277 final int subId = mSubIdToSubscriberId.keyAt(i);
1278 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001279 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1280 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1281 true);
1282 if (template.matches(probeIdent)) {
1283 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001284 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001285 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001286 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001287 }
1288
1289 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001290 * Notify that given {@link NetworkTemplate} is over
1291 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1292 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001293 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001294 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001295 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001296 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001297 mOverLimitNotified.add(template);
1298 }
1299 }
1300
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001301 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001302 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001303 mOverLimitNotified.remove(template);
1304 }
1305
1306 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001307 * Show notification for combined {@link NetworkPolicy} and specific type,
1308 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1309 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001310 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1311 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001312 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001313 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001314 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001315 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001316 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001317 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001318 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001319
1320 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001321 final CharSequence title;
1322 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001323 switch (type) {
1324 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001325 title = res.getText(R.string.data_usage_warning_title);
1326 body = res.getString(R.string.data_usage_warning_body,
1327 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001328
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001329 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001330
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001331 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1332 builder.setDeleteIntent(PendingIntent.getBroadcast(
1333 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1334
Wei Liu546cb772016-07-21 16:19:01 -07001335 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001336 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001337 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1338
Jeff Sharkey497e4432011-06-14 17:27:29 -07001339 break;
1340 }
1341 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001342 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001343 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001344 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001345 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001346 case MATCH_WIFI:
1347 title = res.getText(R.string.data_usage_wifi_limit_title);
1348 break;
1349 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001350 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001351 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001352 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001353
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001354 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001355 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001356
Wei Liu546cb772016-07-21 16:19:01 -07001357 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001358 builder.setContentIntent(PendingIntent.getActivity(
1359 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1360 break;
1361 }
1362 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001363 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001364 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001365 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1366 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001367 case MATCH_WIFI:
1368 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1369 break;
1370 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001371 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001372 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001373 final long overBytes = totalBytes - policy.limitBytes;
1374 body = res.getString(R.string.data_usage_limit_snoozed_body,
1375 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001376
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001377 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001378 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001379 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001380
Wei Liu546cb772016-07-21 16:19:01 -07001381 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001382 builder.setContentIntent(PendingIntent.getActivity(
1383 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001384 break;
1385 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001386 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001387 title = res.getText(R.string.data_usage_rapid_title);
1388 if (rapidBlame != null) {
1389 body = res.getString(R.string.data_usage_rapid_app_body,
1390 rapidBlame.loadLabel(mContext.getPackageManager()));
1391 } else {
1392 body = res.getString(R.string.data_usage_rapid_body);
1393 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001394
Jeff Sharkey2e471452018-01-19 18:02:47 +09001395 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001396
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001397 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1398 builder.setDeleteIntent(PendingIntent.getBroadcast(
1399 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1400
1401 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001402 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001403 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001404 break;
1405 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001406 default: {
1407 return;
1408 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001409 }
1410
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001411 builder.setTicker(title);
1412 builder.setContentTitle(title);
1413 builder.setContentText(body);
1414 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001415
1416 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1417 notificationId.getId(), builder.build(), UserHandle.ALL);
1418 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001419 }
1420
Chris Wren193ae6b2017-03-31 15:17:11 -04001421 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001422 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1423 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001424 }
1425
1426 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001427 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001428 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001429 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001430 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001431 @Override
1432 public void onReceive(Context context, Intent intent) {
1433 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1434 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001435 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001436 }
1437 };
1438
Jeff Sharkey146bb332018-04-18 15:42:57 -06001439 private void updateNetworksInternal() {
1440 // Get all of our cross-process communication with telephony out of
1441 // the way before we acquire internal locks.
1442 updateSubscriptions();
1443
1444 synchronized (mUidRulesFirstLock) {
1445 synchronized (mNetworkPoliciesSecondLock) {
1446 ensureActiveMobilePolicyAL();
1447 normalizePoliciesNL();
1448 updateNetworkEnabledNL();
1449 updateNetworkRulesNL();
1450 updateNotificationsNL();
1451 }
1452 }
1453 }
1454
Jeff Sharkey2e471452018-01-19 18:02:47 +09001455 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001456 public void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001457 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001458 final CountDownLatch latch = new CountDownLatch(1);
1459 mHandler.post(() -> {
1460 latch.countDown();
1461 });
1462 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001463 }
1464
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001466 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1467 * if necessary.
1468 *
1469 * @param subId that has its associated NetworkPolicy updated if necessary
1470 * @return if any policies were updated
1471 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001472 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001473 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001474 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001475
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001476 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001477 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001478 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001479 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001480 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1481 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1482 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001483 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1484 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001485 }
1486 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001487 return policyUpdated;
1488 }
1489
1490 /**
1491 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1492 *
1493 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1494 * to do so, it returns the fallback value.
1495 *
1496 * @param config The CarrierConfig to read the value from.
1497 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1498 * @return cycleDay to use in the mobile NetworkPolicy.
1499 */
1500 @VisibleForTesting
1501 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1502 int fallbackCycleDay) {
1503 if (config == null) {
1504 return fallbackCycleDay;
1505 }
1506 int cycleDay =
1507 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1508 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1509 return fallbackCycleDay;
1510 }
1511 // validate cycleDay value
1512 final Calendar cal = Calendar.getInstance();
1513 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1514 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1515 Slog.e(TAG, "Invalid date in "
1516 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1517 return fallbackCycleDay;
1518 }
1519 return cycleDay;
1520 }
1521
1522 /**
1523 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1524 *
1525 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1526 * to do so, it returns the fallback value.
1527 *
1528 * @param config The CarrierConfig to read the value from.
1529 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1530 * @return warningBytes to use in the mobile NetworkPolicy.
1531 */
1532 @VisibleForTesting
1533 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1534 long fallbackWarningBytes) {
1535 if (config == null) {
1536 return fallbackWarningBytes;
1537 }
1538 long warningBytes =
1539 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1540
1541 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1542 return WARNING_DISABLED;
1543 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1544 return getPlatformDefaultWarningBytes();
1545 } else if (warningBytes < 0) {
1546 Slog.e(TAG, "Invalid value in "
1547 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1548 + "non-negative value but got: " + warningBytes);
1549 return fallbackWarningBytes;
1550 }
1551
1552 return warningBytes;
1553 }
1554
1555 /**
1556 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1557 *
1558 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1559 * to do so, it returns the fallback value.
1560 *
1561 * @param config The CarrierConfig to read the value from.
1562 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1563 * @return limitBytes to use in the mobile NetworkPolicy.
1564 */
1565 @VisibleForTesting
1566 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1567 long fallbackLimitBytes) {
1568 if (config == null) {
1569 return fallbackLimitBytes;
1570 }
1571 long limitBytes =
1572 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1573
1574 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1575 return LIMIT_DISABLED;
1576 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1577 return getPlatformDefaultLimitBytes();
1578 } else if (limitBytes < 0) {
1579 Slog.e(TAG, "Invalid value in "
1580 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1581 + "non-negative value but got: " + limitBytes);
1582 return fallbackLimitBytes;
1583 }
1584 return limitBytes;
1585 }
1586
1587 /**
1588 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1589 */
1590 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1591 @Override
1592 public void onReceive(Context context, Intent intent) {
1593 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1594 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1595
1596 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1597 return;
1598 }
1599 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001600
1601 // Get all of our cross-process communication with telephony out of
1602 // the way before we acquire internal locks.
1603 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001604
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001605 synchronized (mUidRulesFirstLock) {
1606 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001607 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1608 if (subscriberId != null) {
1609 ensureActiveMobilePolicyAL(subId, subscriberId);
1610 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1611 } else {
1612 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1613 }
1614
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001615 // update network and notification rules, as the data cycle changed and it's
1616 // possible that we should be triggering warnings/limits now
1617 handleNetworkPoliciesUpdateAL(true);
1618 }
1619 }
1620 }
1621 };
1622
1623 /**
1624 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1625 * one has been updated.
1626 *
1627 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1628 * update.
1629 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001630 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001631 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1632 if (shouldNormalizePolicies) {
1633 normalizePoliciesNL();
1634 }
1635 updateNetworkEnabledNL();
1636 updateNetworkRulesNL();
1637 updateNotificationsNL();
1638 writePolicyAL();
1639 }
1640
1641 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001642 * Proactively control network data connections when they exceed
1643 * {@link NetworkPolicy#limitBytes}.
1644 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001645 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001646 void updateNetworkEnabledNL() {
1647 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001648 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001649
1650 // TODO: reset any policy-disabled networks when any policy is removed
1651 // completely, which is currently rare case.
1652
Makoto Onuki49392d32018-04-11 13:51:02 -07001653 final long startTime = mStatLogger.getTime();
1654
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001655 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1656 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001657 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001658 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001659 setNetworkTemplateEnabled(policy.template, true);
1660 continue;
1661 }
1662
Jeff Sharkey53313d72017-07-13 16:47:32 -06001663 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1664 .cycleIterator(policy).next();
1665 final long start = cycle.first.toInstant().toEpochMilli();
1666 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001667 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001668
1669 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001670 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1671 && policy.lastLimitSnooze < start;
1672 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001673
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001674 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001675 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001676
1677 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001678 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001679 }
1680
1681 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001682 * Proactively disable networks that match the given
1683 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001684 */
1685 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001686 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1687 // held. Call it via the handler.
1688 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1689 .sendToTarget();
1690 }
1691
1692 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001693 // TODO: reach into ConnectivityManager to proactively disable bringing
1694 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001695
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001696 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001697 // If mobile data usage hits the limit or if the user resumes the data, we need to
1698 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001699
Jeff Sharkey146bb332018-04-18 15:42:57 -06001700 final IntArray matchingSubIds = new IntArray();
1701 synchronized (mNetworkPoliciesSecondLock) {
1702 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1703 final int subId = mSubIdToSubscriberId.keyAt(i);
1704 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1705
1706 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1707 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1708 true);
1709 // Template is matched when subscriber id matches.
1710 if (template.matches(probeIdent)) {
1711 matchingSubIds.add(subId);
1712 }
Jack Yu8781b682016-07-08 14:28:51 -07001713 }
1714 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001715
1716 // Only talk with telephony outside of locks
1717 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1718 for (int i = 0; i < matchingSubIds.size(); i++) {
1719 final int subId = matchingSubIds.get(i);
1720 tm.setPolicyDataEnabled(enabled, subId);
1721 }
Jack Yu8781b682016-07-08 14:28:51 -07001722 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001723 }
1724
1725 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001726 * Collect all ifaces from a {@link NetworkState} into the given set.
1727 */
1728 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1729 final String baseIface = state.linkProperties.getInterfaceName();
1730 if (baseIface != null) {
1731 ifaces.add(baseIface);
1732 }
1733 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1734 final String stackedIface = stackedLink.getInterfaceName();
1735 if (stackedIface != null) {
1736 ifaces.add(stackedIface);
1737 }
1738 }
1739 }
1740
1741 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001742 * Examine all currently active subscriptions from
1743 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1744 * internal data structures.
1745 * <p>
1746 * Callers <em>must not</em> hold any locks when this method called.
1747 */
1748 void updateSubscriptions() {
1749 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1750 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1751
1752 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1753 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1754
1755 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
1756 final String[] mergedSubscriberIds = ArrayUtils.defeatNullable(tm.getMergedSubscriberIds());
1757
1758 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1759 for (int subId : subIds) {
1760 final String subscriberId = tm.getSubscriberId(subId);
1761 if (!TextUtils.isEmpty(subscriberId)) {
1762 subIdToSubscriberId.put(subId, subscriberId);
1763 } else {
1764 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1765 }
1766 }
1767
1768 synchronized (mNetworkPoliciesSecondLock) {
1769 mSubIdToSubscriberId.clear();
1770 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1771 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1772 subIdToSubscriberId.valueAt(i));
1773 }
1774
1775 mMergedSubscriberIds = mergedSubscriberIds;
1776 }
1777
1778 Trace.traceEnd(TRACE_TAG_NETWORK);
1779 }
1780
1781 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001782 * Examine all connected {@link NetworkState}, looking for
1783 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1784 * remaining quota based on usage cycle and historical stats.
1785 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001786 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001787 void updateNetworkRulesNL() {
1788 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001789 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001790
1791 final NetworkState[] states;
1792 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001793 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001794 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001795 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001796 return;
1797 }
1798
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001799 // First, generate identities of all connected networks so we can
1800 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001801 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001802 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001803 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001804 if (state.network != null) {
1805 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1806 }
Wei Liub8eaf452016-01-25 10:32:27 -08001807 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001808 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1809 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001810 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811 }
1812 }
1813
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001814 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001815 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001816
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001817 // For every well-defined policy, compute remaining data based on
1818 // current cycle and historical stats, and push to kernel.
1819 final ArraySet<String> matchingIfaces = new ArraySet<>();
1820 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1821 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1822
1823 // Collect all ifaces that match this policy
1824 matchingIfaces.clear();
1825 for (int j = identified.size() - 1; j >= 0; j--) {
1826 if (policy.template.matches(identified.valueAt(j))) {
1827 collectIfaces(matchingIfaces, identified.keyAt(j));
1828 }
1829 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001830
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001831 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001832 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001833 }
1834
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001835 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001836 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001837 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001838 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001839 if (hasLimit && policy.hasCycle()) {
1840 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1841 .cycleIterator(policy).next();
1842 final long start = cycle.first.toInstant().toEpochMilli();
1843 final long end = cycle.second.toInstant().toEpochMilli();
1844 final long totalBytes = getTotalBytes(policy.template, start, end);
1845
1846 if (policy.lastLimitSnooze >= start) {
1847 // snoozing past quota, but we still need to restrict apps,
1848 // so push really high quota.
1849 quotaBytes = Long.MAX_VALUE;
1850 } else {
1851 // remaining "quota" bytes are based on total usage in
1852 // current cycle. kernel doesn't like 0-byte rules, so we
1853 // set 1-byte quota and disable the radio later.
1854 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1855 }
1856 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001857 // metered network, but no policy limit; we still need to
1858 // restrict apps, so push really high quota.
1859 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001860 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001861
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001862 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001863 // TODO: switch to shared quota once NMS supports
1864 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001865 }
1866
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001867 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1868 final String iface = matchingIfaces.valueAt(j);
1869 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001870 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001871 }
1872 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001873
1874 // keep track of lowest warning or limit of active policies
1875 if (hasWarning && policy.warningBytes < lowestRule) {
1876 lowestRule = policy.warningBytes;
1877 }
1878 if (hasLimit && policy.limitBytes < lowestRule) {
1879 lowestRule = policy.limitBytes;
1880 }
1881 }
1882
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001883 // One final pass to catch any metered ifaces that don't have explicitly
1884 // defined policies; typically Wi-Fi networks.
1885 for (NetworkState state : states) {
1886 if (state.networkInfo != null && state.networkInfo.isConnected()
1887 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1888 matchingIfaces.clear();
1889 collectIfaces(matchingIfaces, state);
1890 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1891 final String iface = matchingIfaces.valueAt(j);
1892 if (!newMeteredIfaces.contains(iface)) {
1893 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1894 newMeteredIfaces.add(iface);
1895 }
1896 }
1897 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001898 }
1899
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001900 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001901 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1902 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001903 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001904 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001905 }
1906 }
1907 mMeteredIfaces = newMeteredIfaces;
1908
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001909 final ContentResolver cr = mContext.getContentResolver();
1910 final boolean quotaEnabled = Settings.Global.getInt(cr,
1911 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1912 final long quotaUnlimited = Settings.Global.getLong(cr,
1913 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1914 final float quotaLimited = Settings.Global.getFloat(cr,
1915 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1916
Jeff Sharkey9252b342018-01-19 07:58:35 +09001917 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001918 mSubscriptionOpportunisticQuota.clear();
1919 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001920 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001921 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001922 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001923 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001924 if (plan == null) continue;
1925
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001926 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001927 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001928 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1929 // Clamp to 0 when roaming
1930 quotaBytes = 0;
1931 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001932 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001933 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001934 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001935 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001936 } else {
1937 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001938 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1939 final long start = cycle.getLower().toInstant().toEpochMilli();
1940 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001941 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001942 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001943 .truncatedTo(ChronoUnit.DAYS)
1944 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001945 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001946 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1947 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001948 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001949 // Number of remaining days including current day
1950 final long remainingDays =
1951 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001952
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001953 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001954 }
1955
1956 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1957 }
1958
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001959 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001960 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001961
1962 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06001963
1964 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001965 }
1966
1967 /**
1968 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1969 * have at least a default mobile policy defined.
1970 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001971 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09001972 private void ensureActiveMobilePolicyAL() {
1973 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001974 if (mSuppressDefaultPolicy) return;
1975
Jeff Sharkey146bb332018-04-18 15:42:57 -06001976 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1977 final int subId = mSubIdToSubscriberId.keyAt(i);
1978 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001979
Hugo Benichi446c9c92017-04-10 09:41:10 +09001980 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001981 }
1982 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001983
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001984 /**
1985 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1986 * have at least a default mobile policy defined.
1987 *
1988 * @param subId to build a default policy for
1989 * @param subscriberId that we check for an existing policy
1990 * @return true if a mobile network policy was added, or false one already existed.
1991 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001992 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09001993 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001994 // Poke around to see if we already have a policy
1995 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001996 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001997 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1998 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1999 if (template.matches(probeIdent)) {
2000 if (LOGD) {
2001 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2002 + NetworkIdentity.scrubSubscriberId(subscriberId));
2003 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002004 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002005 }
2006 }
2007
Jeff Sharkey32566012014-12-02 18:30:14 -08002008 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2009 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002010 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002011 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002012 return true;
2013 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002014
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002015 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002016 final int dataWarningConfig = mContext.getResources().getInteger(
2017 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002018 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002019 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002020 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002021 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002022 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002023 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002024
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002025 private long getPlatformDefaultLimitBytes() {
2026 return LIMIT_DISABLED;
2027 }
2028
2029 @VisibleForTesting
2030 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002031 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002032 final RecurrenceRule cycleRule = NetworkPolicy
2033 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002034 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002035 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2036 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2037 synchronized (mUidRulesFirstLock) {
2038 synchronized (mNetworkPoliciesSecondLock) {
2039 updateDefaultMobilePolicyAL(subId, policy);
2040 }
2041 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002042 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002043 }
2044
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002045 /**
2046 * Update the given {@link NetworkPolicy} based on any carrier-provided
2047 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2048 * Leaves policy untouched if the user has modified it.
2049 *
2050 * @return if the policy was modified
2051 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002052 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002053 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2054 if (!policy.inferred) {
2055 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2056 return false;
2057 }
2058
2059 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2060 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2061 policy.lastLimitSnooze, policy.metered, policy.inferred);
2062
2063 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2064 if (!ArrayUtils.isEmpty(plans)) {
2065 final SubscriptionPlan plan = plans[0];
2066 policy.cycleRule = plan.getCycleRule();
2067 final long planLimitBytes = plan.getDataLimitBytes();
2068 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2069 policy.warningBytes = getPlatformDefaultWarningBytes();
2070 policy.limitBytes = getPlatformDefaultLimitBytes();
2071 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2072 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2073 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2074 } else {
2075 policy.warningBytes = (planLimitBytes * 9) / 10;
2076 switch (plan.getDataLimitBehavior()) {
2077 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2078 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2079 policy.limitBytes = planLimitBytes;
2080 break;
2081 default:
2082 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2083 break;
2084 }
2085 }
2086 } else {
2087 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2088 final int currentCycleDay;
2089 if (policy.cycleRule.isMonthly()) {
2090 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2091 } else {
2092 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2093 }
2094 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2095 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2096 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2097 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2098 }
2099
2100 if (policy.equals(original)) {
2101 return false;
2102 } else {
2103 Slog.d(TAG, "Updated " + original + " to " + policy);
2104 return true;
2105 }
2106 }
2107
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002108 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002109 private void readPolicyAL() {
2110 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002111
2112 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002113 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002114 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002115 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002116 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002117
2118 FileInputStream fis = null;
2119 try {
2120 fis = mPolicyFile.openRead();
2121 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002122 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002123
Felipe Leme46b451f2016-08-19 08:46:17 -07002124 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2125 // to skip UIDs that were explicitly blacklisted.
2126 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2127
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002128 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002129 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002130 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002131 while ((type = in.next()) != END_DOCUMENT) {
2132 final String tag = in.getName();
2133 if (type == START_TAG) {
2134 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002135 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002136 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002137 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2138 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002139 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2140 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2141 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002142 final String networkId;
2143 if (version >= VERSION_ADDED_NETWORK_ID) {
2144 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2145 } else {
2146 networkId = null;
2147 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002148 final RecurrenceRule cycleRule;
2149 if (version >= VERSION_ADDED_CYCLE) {
2150 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2151 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2152 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2153 cycleRule = new RecurrenceRule(
2154 RecurrenceRule.convertZonedDateTime(start),
2155 RecurrenceRule.convertZonedDateTime(end),
2156 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002157 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002158 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2159 final String cycleTimezone;
2160 if (version >= VERSION_ADDED_TIMEZONE) {
2161 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2162 } else {
2163 cycleTimezone = "UTC";
2164 }
2165 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002166 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002167 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2168 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002169 final long lastLimitSnooze;
2170 if (version >= VERSION_SPLIT_SNOOZE) {
2171 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2172 } else if (version >= VERSION_ADDED_SNOOZE) {
2173 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002174 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002175 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002176 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002177 final boolean metered;
2178 if (version >= VERSION_ADDED_METERED) {
2179 metered = readBooleanAttribute(in, ATTR_METERED);
2180 } else {
2181 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002182 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002183 metered = true;
2184 break;
2185 default:
2186 metered = false;
2187 }
2188 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002189 final long lastWarningSnooze;
2190 if (version >= VERSION_SPLIT_SNOOZE) {
2191 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2192 } else {
2193 lastWarningSnooze = SNOOZE_NEVER;
2194 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002195 final boolean inferred;
2196 if (version >= VERSION_ADDED_INFERRED) {
2197 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2198 } else {
2199 inferred = false;
2200 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002201
Jeff Sharkey32566012014-12-02 18:30:14 -08002202 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2203 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002204 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002205 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2206 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002207 lastLimitSnooze, metered, inferred));
2208 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002209
2210 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2211 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2212 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2213 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2214 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2215 RecurrenceRule.convertZonedDateTime(start),
2216 RecurrenceRule.convertZonedDateTime(end),
2217 RecurrenceRule.convertPeriod(period));
2218 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2219 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2220
2221 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2222 SubscriptionPlan.BYTES_UNKNOWN);
2223 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2224 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2225 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2226 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2227 builder.setDataLimit(limitBytes, limitBehavior);
2228 }
2229
2230 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2231 SubscriptionPlan.BYTES_UNKNOWN);
2232 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2233 SubscriptionPlan.TIME_UNKNOWN);
2234 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2235 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2236 builder.setDataUsage(usageBytes, usageTime);
2237 }
2238
2239 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2240 final SubscriptionPlan plan = builder.build();
2241 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2242 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2243
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002244 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2245 mSubscriptionPlansOwner.put(subId, ownerPackage);
2246
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002247 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002248 final int uid = readIntAttribute(in, ATTR_UID);
2249 final int policy = readIntAttribute(in, ATTR_POLICY);
2250
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002251 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002252 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002253 } else {
2254 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2255 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002257 final int appId = readIntAttribute(in, ATTR_APP_ID);
2258 final int policy = readIntAttribute(in, ATTR_POLICY);
2259
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002260 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002261 // app policy is deprecated so this is only used in pre system user split.
2262 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002263 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002264 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002265 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002267 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002268 } else if (TAG_WHITELIST.equals(tag)) {
2269 insideWhitelist = true;
2270 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2271 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002272 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002273 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2274 final int uid = readIntAttribute(in, ATTR_UID);
2275 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002276 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002277 } else if (type == END_TAG) {
2278 if (TAG_WHITELIST.equals(tag)) {
2279 insideWhitelist = false;
2280 }
2281
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002282 }
2283 }
2284
Felipe Leme46b451f2016-08-19 08:46:17 -07002285 final int size = whitelistedRestrictBackground.size();
2286 for (int i = 0; i < size; i++) {
2287 final int uid = whitelistedRestrictBackground.keyAt(i);
2288 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2289 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2290 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2291 + " because its policy is " + uidPoliciesToString(policy));
2292 continue;
2293 }
2294 if (UserHandle.isApp(uid)) {
2295 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2296 if (LOGV)
2297 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2298 setUidPolicyUncheckedUL(uid, newPolicy, false);
2299 } else {
2300 Slog.w(TAG, "unable to update policy on UID " + uid);
2301 }
2302 }
2303
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002304 } catch (FileNotFoundException e) {
2305 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002306 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002307 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002308 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002309 } finally {
2310 IoUtils.closeQuietly(fis);
2311 }
2312 }
2313
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002314 /**
2315 * Upgrade legacy background data flags, notifying listeners of one last
2316 * change to always-true.
2317 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002318 private void upgradeDefaultBackgroundDataUL() {
2319 // This method is only called when we're unable to find the network policy flag, which
2320 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002321
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002322 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002323 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002324 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2325
2326 // NOTE: We used to read the legacy setting here :
2327 //
2328 // final int legacyFlagValue = Settings.Secure.getInt(
2329 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2330 //
2331 // This is no longer necessary because we will never upgrade directly from Gingerbread
2332 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2333 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002334 }
2335
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002336 /**
2337 * Perform upgrade step of moving any user-defined meterness overrides over
2338 * into {@link WifiConfiguration}.
2339 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002340 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002341 private void upgradeWifiMeteredOverrideAL() {
2342 boolean modified = false;
2343 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2344 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2345 for (int i = 0; i < mNetworkPolicy.size(); ) {
2346 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2347 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2348 && !policy.inferred) {
2349 mNetworkPolicy.removeAt(i);
2350 modified = true;
2351
2352 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2353 for (WifiConfiguration config : configs) {
2354 if (Objects.equals(resolveNetworkId(config), networkId)) {
2355 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2356 config.meteredOverride = policy.metered
2357 ? WifiConfiguration.METERED_OVERRIDE_METERED
2358 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2359 wm.updateNetwork(config);
2360 }
2361 }
2362 } else {
2363 i++;
2364 }
2365 }
2366 if (modified) {
2367 writePolicyAL();
2368 }
2369 }
2370
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002371 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002372 void writePolicyAL() {
2373 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002374
2375 FileOutputStream fos = null;
2376 try {
2377 fos = mPolicyFile.startWrite();
2378
2379 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002380 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002381 out.startDocument(null, true);
2382
2383 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002384 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002385 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002386
2387 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002388 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2389 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002390 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002391 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002392
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002393 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002394 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2395 final String subscriberId = template.getSubscriberId();
2396 if (subscriberId != null) {
2397 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002398 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002399 final String networkId = template.getNetworkId();
2400 if (networkId != null) {
2401 out.attribute(null, ATTR_NETWORK_ID, networkId);
2402 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002403 writeStringAttribute(out, ATTR_CYCLE_START,
2404 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2405 writeStringAttribute(out, ATTR_CYCLE_END,
2406 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2407 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2408 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002409 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2410 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002411 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2412 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002413 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002414 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002415 out.endTag(null, TAG_NETWORK_POLICY);
2416 }
2417
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002418 // write all known subscription plans
2419 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2420 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002421 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002422 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2423 if (ArrayUtils.isEmpty(plans)) continue;
2424
2425 for (SubscriptionPlan plan : plans) {
2426 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2427 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002428 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002429 final RecurrenceRule cycleRule = plan.getCycleRule();
2430 writeStringAttribute(out, ATTR_CYCLE_START,
2431 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2432 writeStringAttribute(out, ATTR_CYCLE_END,
2433 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2434 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2435 RecurrenceRule.convertPeriod(cycleRule.period));
2436 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2437 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2438 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2439 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2440 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2441 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2442 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2443 }
2444 }
2445
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002446 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002447 for (int i = 0; i < mUidPolicy.size(); i++) {
2448 final int uid = mUidPolicy.keyAt(i);
2449 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002450
Jeff Sharkey497e4432011-06-14 17:27:29 -07002451 // skip writing empty policies
2452 if (policy == POLICY_NONE) continue;
2453
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002454 out.startTag(null, TAG_UID_POLICY);
2455 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002456 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002457 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002458 }
2459
2460 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002461
2462 // write all whitelists
2463 out.startTag(null, TAG_WHITELIST);
2464
Felipe Lemea9505cc2016-02-26 10:28:41 -08002465 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002466 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002467 for (int i = 0; i < size; i++) {
2468 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2469 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2470 writeIntAttribute(out, ATTR_UID, uid);
2471 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2472 }
2473
Felipe Lemeb85a6372016-01-14 16:16:16 -08002474 out.endTag(null, TAG_WHITELIST);
2475
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002476 out.endDocument();
2477
2478 mPolicyFile.finishWrite(fos);
2479 } catch (IOException e) {
2480 if (fos != null) {
2481 mPolicyFile.failWrite(fos);
2482 }
2483 }
2484 }
2485
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002486 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002487 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002488 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002489
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002490 if (!UserHandle.isApp(uid)) {
2491 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002492 }
Felipe Lemef0823852016-06-08 13:43:08 -07002493 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002494 final long token = Binder.clearCallingIdentity();
2495 try {
2496 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2497 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002498 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002499 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002500 }
2501 } finally {
2502 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002503 }
2504 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002505 }
2506
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002507 @Override
2508 public void addUidPolicy(int uid, int policy) {
2509 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002510
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002511 if (!UserHandle.isApp(uid)) {
2512 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2513 }
2514
Felipe Lemef0823852016-06-08 13:43:08 -07002515 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002516 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2517 policy |= oldPolicy;
2518 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002519 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002520 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002521 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002522 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002523 }
2524
2525 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002526 public void removeUidPolicy(int uid, int policy) {
2527 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2528
2529 if (!UserHandle.isApp(uid)) {
2530 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2531 }
2532
Felipe Lemef0823852016-06-08 13:43:08 -07002533 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002534 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2535 policy = oldPolicy & ~policy;
2536 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002537 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002538 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002539 }
2540 }
2541 }
2542
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002543 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002544 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002545 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002546
Felipe Leme57e3d312016-08-23 14:42:52 -07002547 final boolean notifyApp;
2548 if (!isUidValidForWhitelistRules(uid)) {
2549 notifyApp = false;
2550 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002551 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2552 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2553 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2554 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002555 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2556 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002557 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2558 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2559 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2560 if (LOGD)
2561 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2562 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2563 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002564 notifyApp = wasBlocked != isBlocked;
2565 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002566 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2567 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002568 if (persist) {
2569 synchronized (mNetworkPoliciesSecondLock) {
2570 writePolicyAL();
2571 }
2572 }
Felipe Leme923845f2016-03-02 13:42:48 -08002573 }
2574
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002575 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002576 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002577 if (policy == POLICY_NONE) {
2578 mUidPolicy.delete(uid);
2579 } else {
2580 mUidPolicy.put(uid, policy);
2581 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002582
2583 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002584 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002585 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002586 synchronized (mNetworkPoliciesSecondLock) {
2587 writePolicyAL();
2588 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002589 }
2590 }
2591
2592 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002593 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002594 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2595
Felipe Lemef0823852016-06-08 13:43:08 -07002596 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002597 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002598 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002599 }
2600
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002601 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002602 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002603 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2604
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002605 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002606 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002607 for (int i = 0; i < mUidPolicy.size(); i++) {
2608 final int uid = mUidPolicy.keyAt(i);
2609 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002610 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2611 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002612 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002613 }
2614 }
2615 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002616 return uids;
2617 }
2618
2619 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002620 * Removes any persistable state associated with given {@link UserHandle}, persisting
2621 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002622 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002623 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002624 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002625
Sudheer Shanka352dc572017-09-22 17:09:38 -07002626 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002627 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002628
Felipe Lemea110eec2016-04-29 09:58:06 -07002629 // Remove entries from revoked default restricted background UID whitelist
2630 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2631 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2632 if (UserHandle.getUserId(uid) == userId) {
2633 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002634 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002635 }
2636 }
2637
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002638 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002639 int[] uids = new int[0];
2640 for (int i = 0; i < mUidPolicy.size(); i++) {
2641 final int uid = mUidPolicy.keyAt(i);
2642 if (UserHandle.getUserId(uid) == userId) {
2643 uids = appendInt(uids, uid);
2644 }
2645 }
2646
2647 if (uids.length > 0) {
2648 for (int uid : uids) {
2649 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002650 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002651 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002652 }
Felipe Lemef0823852016-06-08 13:43:08 -07002653 synchronized (mNetworkPoliciesSecondLock) {
2654 updateRulesForGlobalChangeAL(true);
2655 if (writePolicy && changed) {
2656 writePolicyAL();
2657 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002658 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002659 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002660 }
2661
2662 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002663 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002664 // TODO: create permission for observing network policy
2665 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002666 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002667 }
2668
2669 @Override
2670 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002671 // TODO: create permission for observing network policy
2672 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002673 mListeners.unregister(listener);
2674 }
2675
Jeff Sharkey1b861272011-05-22 00:34:52 -07002676 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002677 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002678 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2679
Felipe Leme6a05eee2016-02-19 14:43:51 -08002680 final long token = Binder.clearCallingIdentity();
2681 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002682 synchronized (mUidRulesFirstLock) {
2683 synchronized (mNetworkPoliciesSecondLock) {
2684 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002685 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002686 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002687 }
2688 } finally {
2689 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002690 }
2691 }
2692
Hugo Benichi446c9c92017-04-10 09:41:10 +09002693 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002694 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002695 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2696 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002697 }
2698
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002699 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002700 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002701 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002702 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002703 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2704 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2705 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002706 } catch (SecurityException e) {
2707 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002708
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002709 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2710 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2711 return new NetworkPolicy[0];
2712 }
Svet Ganov16a16892015-04-16 10:32:04 -07002713 }
2714
Felipe Lemef0823852016-06-08 13:43:08 -07002715 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002716 final int size = mNetworkPolicy.size();
2717 final NetworkPolicy[] policies = new NetworkPolicy[size];
2718 for (int i = 0; i < size; i++) {
2719 policies[i] = mNetworkPolicy.valueAt(i);
2720 }
2721 return policies;
2722 }
2723 }
2724
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002725 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002726 private void normalizePoliciesNL() {
2727 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002728 }
2729
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002730 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002731 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002732 mNetworkPolicy.clear();
2733 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002734 if (policy == null) {
2735 continue;
2736 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002737 // When two normalized templates conflict, prefer the most
2738 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002739 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002740 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2741 if (existing == null || existing.compareTo(policy) > 0) {
2742 if (existing != null) {
2743 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2744 }
2745 mNetworkPolicy.put(policy.template, policy);
2746 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002747 }
2748 }
2749
2750 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002751 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002752 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002753
2754 final long token = Binder.clearCallingIdentity();
2755 try {
2756 performSnooze(template, TYPE_LIMIT);
2757 } finally {
2758 Binder.restoreCallingIdentity(token);
2759 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002760 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002761
Dianne Hackborn497175b2014-07-01 12:56:08 -07002762 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002763 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002764 synchronized (mUidRulesFirstLock) {
2765 synchronized (mNetworkPoliciesSecondLock) {
2766 // find and snooze local policy that matches
2767 final NetworkPolicy policy = mNetworkPolicy.get(template);
2768 if (policy == null) {
2769 throw new IllegalArgumentException("unable to find policy for " + template);
2770 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002771
Felipe Lemef0823852016-06-08 13:43:08 -07002772 switch (type) {
2773 case TYPE_WARNING:
2774 policy.lastWarningSnooze = currentTime;
2775 break;
2776 case TYPE_LIMIT:
2777 policy.lastLimitSnooze = currentTime;
2778 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002779 case TYPE_RAPID:
2780 policy.lastRapidSnooze = currentTime;
2781 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002782 default:
2783 throw new IllegalArgumentException("unexpected type");
2784 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002785
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002786 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002787 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002788 }
2789 }
2790
2791 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002792 public void onTetheringChanged(String iface, boolean tethering) {
2793 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002794 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002795 if (mRestrictBackground && tethering) {
2796 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2797 setRestrictBackground(false);
2798 }
2799 }
2800 }
2801
2802 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002803 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002804 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002805 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002806 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2807 final long token = Binder.clearCallingIdentity();
2808 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002809 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002810 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002811 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002812 } finally {
2813 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002814 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002815 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002816 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002817 }
2818 }
2819
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002820 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002821 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002822 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002823 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002824 if (restrictBackground == mRestrictBackground) {
2825 // Ideally, UI should never allow this scenario...
2826 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002827 return;
2828 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002829 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2830 final boolean oldRestrictBackground = mRestrictBackground;
2831 mRestrictBackground = restrictBackground;
2832 // Must whitelist foreground apps before turning data saver mode on.
2833 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2834 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2835 updateRulesForRestrictBackgroundUL();
2836 try {
2837 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2838 Slog.e(TAG,
2839 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2840 mRestrictBackground = oldRestrictBackground;
2841 // TODO: if it knew the foreground apps (see TODO above), it could call
2842 // updateRulesForRestrictBackgroundUL() again to restore state.
2843 return;
2844 }
2845 } catch (RemoteException e) {
2846 // ignored; service lives in system_server
2847 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002848
Sudheer Shanka543339f2017-07-28 15:18:07 -07002849 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002850 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002851
2852 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2853 mRestrictBackgroundChangedInBsm = true;
2854 }
2855 synchronized (mNetworkPoliciesSecondLock) {
2856 updateNotificationsNL();
2857 writePolicyAL();
2858 }
2859 } finally {
2860 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002861 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002862 }
2863
2864 private void sendRestrictBackgroundChangedMsg() {
2865 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2866 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2867 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002868 }
2869
Felipe Lemeb85a6372016-01-14 16:16:16 -08002870 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002871 public int getRestrictBackgroundByCaller() {
2872 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2873 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002874
Felipe Lemef0823852016-06-08 13:43:08 -07002875 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002876 // Must clear identity because getUidPolicy() is restricted to system.
2877 final long token = Binder.clearCallingIdentity();
2878 final int policy;
2879 try {
2880 policy = getUidPolicy(uid);
2881 } finally {
2882 Binder.restoreCallingIdentity(token);
2883 }
2884 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2885 // App is blacklisted.
2886 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2887 }
Felipe Leme1b103232016-01-22 09:44:57 -08002888 if (!mRestrictBackground) {
2889 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2890 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002891 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002892 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2893 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2894 }
2895 }
2896
2897 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002898 public boolean getRestrictBackground() {
2899 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2900
Felipe Lemef0823852016-06-08 13:43:08 -07002901 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002902 return mRestrictBackground;
2903 }
2904 }
2905
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002906 @Override
2907 public void setDeviceIdleMode(boolean enabled) {
2908 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002909 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2910 try {
2911 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002912 if (mDeviceIdleMode == enabled) {
2913 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002914 }
Felipe Lemeea014392016-09-06 13:59:54 -07002915 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002916 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002917 if (mSystemReady) {
2918 // Device idle change means we need to rebuild rules for all
2919 // known apps, so do a global refresh.
2920 updateRulesForRestrictPowerUL();
2921 }
2922 }
2923 if (enabled) {
2924 EventLogTags.writeDeviceIdleOnPhase("net");
2925 } else {
2926 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002927 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002928 } finally {
2929 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002930 }
2931 }
2932
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002933 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002934 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2935 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002936 final long token = Binder.clearCallingIdentity();
2937 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002938 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2939 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2940 for (WifiConfiguration config : configs) {
2941 if (Objects.equals(resolveNetworkId(config), networkId)) {
2942 config.meteredOverride = meteredOverride;
2943 wm.updateNetwork(config);
2944 }
2945 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002946 } finally {
2947 Binder.restoreCallingIdentity(token);
2948 }
2949 }
2950
Jeff Sharkey46645002011-07-27 21:11:21 -07002951 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002952 @Deprecated
2953 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2954 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2955 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2956 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002957 }
2958
Jeff Sharkey53313d72017-07-13 16:47:32 -06002959 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2960 // Verify they're not lying about package name
2961 mAppOps.checkPackage(callingUid, callingPackage);
2962
Jeff Sharkey53313d72017-07-13 16:47:32 -06002963 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002964 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002965 final long token = Binder.clearCallingIdentity();
2966 try {
2967 si = mContext.getSystemService(SubscriptionManager.class)
2968 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002969 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002970 } finally {
2971 Binder.restoreCallingIdentity(token);
2972 }
2973
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002974 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002975 if (si != null) {
2976 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2977 return;
2978 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002979 }
2980
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002981 // Second check: has the CarrierService delegated access?
2982 if (config != null) {
2983 final String overridePackage = config
2984 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2985 if (!TextUtils.isEmpty(overridePackage)
2986 && Objects.equals(overridePackage, callingPackage)) {
2987 return;
2988 }
2989 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002990
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002991 // Third check: is caller the fallback/default CarrierService?
2992 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2993 if (!TextUtils.isEmpty(defaultPackage)
2994 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002995 return;
2996 }
2997
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002998 // Fourth check: is caller a testing app?
2999 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3000 if (!TextUtils.isEmpty(testPackage)
3001 && Objects.equals(testPackage, callingPackage)) {
3002 return;
3003 }
3004
3005 // Fifth check: is caller a legacy testing app?
3006 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3007 if (!TextUtils.isEmpty(legacyTestPackage)
3008 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003009 return;
3010 }
3011
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003012 // Final check: does the caller hold a permission?
3013 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003014 }
3015
3016 @Override
3017 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3018 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3019
Jeff Sharkey53313d72017-07-13 16:47:32 -06003020 final String fake = SystemProperties.get("fw.fake_plan");
3021 if (!TextUtils.isEmpty(fake)) {
3022 final List<SubscriptionPlan> plans = new ArrayList<>();
3023 if ("month_hard".equals(fake)) {
3024 plans.add(SubscriptionPlan.Builder
3025 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3026 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003027 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3028 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3029 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3030 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3031 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003032 plans.add(SubscriptionPlan.Builder
3033 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3034 .setTitle("G-Mobile Happy")
3035 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3036 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3037 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3038 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3039 .build());
3040 plans.add(SubscriptionPlan.Builder
3041 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3042 .setTitle("G-Mobile, Charged after limit")
3043 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3044 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3045 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3046 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3047 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003048 } else if ("month_soft".equals(fake)) {
3049 plans.add(SubscriptionPlan.Builder
3050 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3051 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3052 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3053 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003054 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3055 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3056 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3057 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3058 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003059 plans.add(SubscriptionPlan.Builder
3060 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3061 .setTitle("G-Mobile, Throttled after limit")
3062 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3063 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3064 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3065 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3066 .build());
3067 plans.add(SubscriptionPlan.Builder
3068 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3069 .setTitle("G-Mobile, No data connection after limit")
3070 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3071 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3072 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3073 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3074 .build());
3075
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003076 } else if ("month_over".equals(fake)) {
3077 plans.add(SubscriptionPlan.Builder
3078 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3079 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3080 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3081 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3082 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3083 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3084 .build());
3085 plans.add(SubscriptionPlan.Builder
3086 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3087 .setTitle("G-Mobile, Throttled after limit")
3088 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3089 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3090 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3091 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3092 .build());
3093 plans.add(SubscriptionPlan.Builder
3094 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3095 .setTitle("G-Mobile, No data connection after limit")
3096 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3097 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3098 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3099 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3100 .build());
3101
Jeff Sharkey53313d72017-07-13 16:47:32 -06003102 } else if ("month_none".equals(fake)) {
3103 plans.add(SubscriptionPlan.Builder
3104 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3105 .setTitle("G-Mobile")
3106 .build());
3107 } else if ("prepaid".equals(fake)) {
3108 plans.add(SubscriptionPlan.Builder
3109 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3110 ZonedDateTime.now().plusDays(10))
3111 .setTitle("G-Mobile")
3112 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3113 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3114 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3115 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3116 .build());
3117 } else if ("prepaid_crazy".equals(fake)) {
3118 plans.add(SubscriptionPlan.Builder
3119 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3120 ZonedDateTime.now().plusDays(10))
3121 .setTitle("G-Mobile Anytime")
3122 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3123 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3124 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3125 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3126 .build());
3127 plans.add(SubscriptionPlan.Builder
3128 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3129 ZonedDateTime.now().plusDays(20))
3130 .setTitle("G-Mobile Nickel Nights")
3131 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003132 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3133 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003134 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3135 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3136 .build());
3137 plans.add(SubscriptionPlan.Builder
3138 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3139 ZonedDateTime.now().plusDays(20))
3140 .setTitle("G-Mobile Bonus 3G")
3141 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003142 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003143 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3144 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3145 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3146 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003147 } else if ("unlimited".equals(fake)) {
3148 plans.add(SubscriptionPlan.Builder
3149 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3150 ZonedDateTime.now().plusDays(10))
3151 .setTitle("G-Mobile Awesome")
3152 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3153 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3154 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3155 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3156 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003157 }
3158 return plans.toArray(new SubscriptionPlan[plans.size()]);
3159 }
3160
Jeff Sharkey4635f102017-09-01 11:27:13 -06003161 synchronized (mNetworkPoliciesSecondLock) {
3162 // Only give out plan details to the package that defined them,
3163 // so that we don't risk leaking plans between apps. We always
3164 // let in core system components (like the Settings app).
3165 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3166 if (Objects.equals(ownerPackage, callingPackage)
3167 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3168 return mSubscriptionPlans.get(subId);
3169 } else {
3170 Log.w(TAG, "Not returning plans because caller " + callingPackage
3171 + " doesn't match owner " + ownerPackage);
3172 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003173 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003174 }
3175 }
3176
3177 @Override
3178 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3179 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3180
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003181 for (SubscriptionPlan plan : plans) {
3182 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003183 }
3184
3185 final long token = Binder.clearCallingIdentity();
3186 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003187 synchronized (mUidRulesFirstLock) {
3188 synchronized (mNetworkPoliciesSecondLock) {
3189 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003190 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003191
Jeff Sharkey146bb332018-04-18 15:42:57 -06003192 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3193 if (subscriberId != null) {
3194 ensureActiveMobilePolicyAL(subId, subscriberId);
3195 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3196 } else {
3197 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3198 }
3199
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003200 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003201 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003202 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003203
3204 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3205 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3206 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3207 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003208 } finally {
3209 Binder.restoreCallingIdentity(token);
3210 }
3211 }
3212
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003213 /**
3214 * Only visible for testing purposes. This doesn't give any access to
3215 * existing plans; it simply lets the debug package define new plans.
3216 */
3217 void setSubscriptionPlansOwner(int subId, String packageName) {
3218 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3219 }
3220
Jeff Sharkey53313d72017-07-13 16:47:32 -06003221 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003222 public String getSubscriptionPlansOwner(int subId) {
3223 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3224 throw new SecurityException();
3225 }
3226
3227 synchronized (mNetworkPoliciesSecondLock) {
3228 return mSubscriptionPlansOwner.get(subId);
3229 }
3230 }
3231
3232 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003233 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3234 long timeoutMillis, String callingPackage) {
3235 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3236
3237 // We can only override when carrier told us about plans
3238 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003239 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3240 if (plan == null
3241 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003242 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003243 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003244 }
3245 }
3246
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003247 // Only allow overrides when feature is enabled. However, we always
3248 // allow disabling of overrides for safety reasons.
3249 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3250 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3251 if (overrideEnabled || overrideValue == 0) {
3252 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3253 overrideMask, overrideValue, subId));
3254 if (timeoutMillis > 0) {
3255 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3256 overrideMask, 0, subId), timeoutMillis);
3257 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003258 }
3259 }
3260
3261 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003262 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003263 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003264
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003265 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3266
Dianne Hackborn497175b2014-07-01 12:56:08 -07003267 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003268 for (String arg : args) {
3269 argSet.add(arg);
3270 }
3271
Felipe Lemef0823852016-06-08 13:43:08 -07003272 synchronized (mUidRulesFirstLock) {
3273 synchronized (mNetworkPoliciesSecondLock) {
3274 if (argSet.contains("--unsnooze")) {
3275 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3276 mNetworkPolicy.valueAt(i).clearSnooze();
3277 }
3278
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003279 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003280
3281 fout.println("Cleared snooze timestamps");
3282 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003283 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003284
Felipe Lemef0823852016-06-08 13:43:08 -07003285 fout.print("System ready: "); fout.println(mSystemReady);
3286 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3287 fout.print("Restrict power: "); fout.println(mRestrictPower);
3288 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003289 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3290
3291 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003292 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003293 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003294 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3295 fout.println(mNetworkPolicy.valueAt(i).toString());
3296 }
3297 fout.decreaseIndent();
3298
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003299 fout.println();
3300 fout.println("Subscription plans:");
3301 fout.increaseIndent();
3302 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3303 final int subId = mSubscriptionPlans.keyAt(i);
3304 fout.println("Subscriber ID " + subId + ":");
3305 fout.increaseIndent();
3306 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3307 if (!ArrayUtils.isEmpty(plans)) {
3308 for (SubscriptionPlan plan : plans) {
3309 fout.println(plan);
3310 }
3311 }
3312 fout.decreaseIndent();
3313 }
3314 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003315
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003316 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003317 fout.println("Active subscriptions:");
3318 fout.increaseIndent();
3319 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3320 final int subId = mSubIdToSubscriberId.keyAt(i);
3321 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3322
3323 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3324 }
3325 fout.decreaseIndent();
3326
3327 fout.println();
3328 fout.println("Merged subscriptions: "
3329 + Arrays.toString(NetworkIdentity.scrubSubscriberId(mMergedSubscriberIds)));
3330
3331 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003332 fout.println("Policy for UIDs:");
3333 fout.increaseIndent();
3334 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003335 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003336 final int uid = mUidPolicy.keyAt(i);
3337 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003338 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003339 fout.print(uid);
3340 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003341 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003342 fout.println();
3343 }
3344 fout.decreaseIndent();
3345
3346 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3347 if (size > 0) {
3348 fout.println("Power save whitelist (except idle) app ids:");
3349 fout.increaseIndent();
3350 for (int i = 0; i < size; i++) {
3351 fout.print("UID=");
3352 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3353 fout.print(": ");
3354 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3355 fout.println();
3356 }
3357 fout.decreaseIndent();
3358 }
3359
3360 size = mPowerSaveWhitelistAppIds.size();
3361 if (size > 0) {
3362 fout.println("Power save whitelist app ids:");
3363 fout.increaseIndent();
3364 for (int i = 0; i < size; i++) {
3365 fout.print("UID=");
3366 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3367 fout.print(": ");
3368 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3369 fout.println();
3370 }
3371 fout.decreaseIndent();
3372 }
3373
Felipe Lemef0823852016-06-08 13:43:08 -07003374 size = mDefaultRestrictBackgroundWhitelistUids.size();
3375 if (size > 0) {
3376 fout.println("Default restrict background whitelist uids:");
3377 fout.increaseIndent();
3378 for (int i = 0; i < size; i++) {
3379 fout.print("UID=");
3380 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3381 fout.println();
3382 }
3383 fout.decreaseIndent();
3384 }
3385
3386 size = mRestrictBackgroundWhitelistRevokedUids.size();
3387 if (size > 0) {
3388 fout.println("Default restrict background whitelist uids revoked by users:");
3389 fout.increaseIndent();
3390 for (int i = 0; i < size; i++) {
3391 fout.print("UID=");
3392 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3393 fout.println();
3394 }
3395 fout.decreaseIndent();
3396 }
3397
3398 final SparseBooleanArray knownUids = new SparseBooleanArray();
3399 collectKeys(mUidState, knownUids);
3400 collectKeys(mUidRules, knownUids);
3401
3402 fout.println("Status for all known UIDs:");
3403 fout.increaseIndent();
3404 size = knownUids.size();
3405 for (int i = 0; i < size; i++) {
3406 final int uid = knownUids.keyAt(i);
3407 fout.print("UID=");
3408 fout.print(uid);
3409
3410 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3411 fout.print(" state=");
3412 fout.print(state);
3413 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3414 fout.print(" (fg)");
3415 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003416 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003417 ? " (fg svc)" : " (bg)");
3418 }
3419
3420 final int uidRules = mUidRules.get(uid, RULE_NONE);
3421 fout.print(" rules=");
3422 fout.print(uidRulesToString(uidRules));
3423 fout.println();
3424 }
3425 fout.decreaseIndent();
3426
3427 fout.println("Status for just UIDs with rules:");
3428 fout.increaseIndent();
3429 size = mUidRules.size();
3430 for (int i = 0; i < size; i++) {
3431 final int uid = mUidRules.keyAt(i);
3432 fout.print("UID=");
3433 fout.print(uid);
3434 final int uidRules = mUidRules.get(uid, RULE_NONE);
3435 fout.print(" rules=");
3436 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003437 fout.println();
3438 }
3439 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003440
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003441 fout.println("Admin restricted uids for metered data:");
3442 fout.increaseIndent();
3443 size = mMeteredRestrictedUids.size();
3444 for (int i = 0; i < size; ++i) {
3445 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3446 fout.println(mMeteredRestrictedUids.valueAt(i));
3447 }
3448 fout.decreaseIndent();
3449
Makoto Onuki49392d32018-04-11 13:51:02 -07003450 fout.println();
3451 mStatLogger.dump(fout);
3452
Sudheer Shanka352dc572017-09-22 17:09:38 -07003453 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003454 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003455 }
3456 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003457
3458 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003459 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003460 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003461 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003462 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003463 }
3464
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003465 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003466 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003467 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003468 return isUidStateForeground(
3469 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003470 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003471 }
3472
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003473 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003474 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003475 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003476 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003477 }
3478
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003479 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003480 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003481 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3482 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3483 }
3484
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003485 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003486 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003487 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003488 }
3489
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003490 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003491 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003492 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3493 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003494 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003495 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00003496 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003497 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3498 try {
3499 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3500 if (oldUidState != uidState) {
3501 // state changed, push updated rules
3502 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003503 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3504 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3505 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003506 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003507 if (mDeviceIdleMode) {
3508 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003509 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003510 if (mRestrictPower) {
3511 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003512 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003513 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003514 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003515 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003516 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003517 } finally {
3518 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003519 }
3520 }
3521
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003522 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003523 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003524 final int index = mUidState.indexOfKey(uid);
3525 if (index >= 0) {
3526 final int oldUidState = mUidState.valueAt(index);
3527 mUidState.removeAt(index);
3528 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003529 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003530 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003531 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003532 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003533 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003534 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003535 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003536 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003537 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003538 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003539 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003540 }
3541 }
3542
Felipe Lemef28983d2016-03-25 12:18:23 -07003543 // adjust stats accounting based on foreground status
3544 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003545 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3546 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3547 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3548 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003549 try {
3550 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003551 } finally {
3552 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003553 }
3554 }
3555
Sudheer Shankac9d94072017-02-22 22:13:55 +00003556 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3557 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003558 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003559 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003560 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003561 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003562 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003563 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003564 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003565 }
3566
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003567 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003568 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003569 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3570 try {
3571 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3572 mUidFirewallPowerSaveRules);
3573 } finally {
3574 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3575 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003576 }
3577
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003578 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003579 void updateRuleForRestrictPowerUL(int uid) {
3580 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003581 }
3582
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003583 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003584 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003585 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3586 try {
3587 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3588 mUidFirewallDozableRules);
3589 } finally {
3590 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3591 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003592 }
3593
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003594 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003595 void updateRuleForDeviceIdleUL(int uid) {
3596 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003597 }
3598
Felipe Lemef28983d2016-03-25 12:18:23 -07003599 // NOTE: since both fw_dozable and fw_powersave uses the same map
3600 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003601 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003602 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003603 SparseIntArray rules) {
3604 if (enabled) {
3605 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003606 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003607 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003608 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003609 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003610 for (int ui = users.size() - 1; ui >= 0; ui--) {
3611 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003612 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3613 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3614 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3615 updateRulesForWhitelistedAppIds(uidRules,
3616 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003617 }
3618 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003619 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003620 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003621 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3622 }
3623 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003624 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003625 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003626 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003627 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003628 }
3629
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003630 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3631 final SparseBooleanArray whitelistedAppIds, int userId) {
3632 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3633 if (whitelistedAppIds.valueAt(i)) {
3634 final int appId = whitelistedAppIds.keyAt(i);
3635 final int uid = UserHandle.getUid(userId, appId);
3636 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3637 }
3638 }
3639 }
3640
3641 /**
3642 * @param deviceIdleMode if true then we don't consider
3643 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3644 * whitelisted.
3645 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003646 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003647 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003648 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003649 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3650 || mPowerSaveWhitelistAppIds.get(appId);
3651 if (!deviceIdleMode) {
3652 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3653 }
3654 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003655 }
3656
Felipe Lemef28983d2016-03-25 12:18:23 -07003657 // NOTE: since both fw_dozable and fw_powersave uses the same map
3658 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003659 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003660 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003661 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003662 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3663 chain == FIREWALL_CHAIN_DOZABLE);
3664 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003665 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003666 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003667 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003668 }
3669 }
3670 }
3671
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003672 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003673 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003674 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3675 try {
3676 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3677 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003678
Felipe Leme873a83a2016-09-07 11:34:10 -07003679 // Fully update the app idle firewall chain.
3680 final List<UserInfo> users = mUserManager.getUsers();
3681 for (int ui = users.size() - 1; ui >= 0; ui--) {
3682 UserInfo user = users.get(ui);
3683 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3684 for (int uid : idleUids) {
3685 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3686 // quick check: if this uid doesn't have INTERNET permission, it
3687 // doesn't have network access anyway, so it is a waste to mess
3688 // with it here.
3689 if (hasInternetPermissions(uid)) {
3690 uidRules.put(uid, FIREWALL_RULE_DENY);
3691 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003692 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003693 }
3694 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003695
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003696 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003697 } finally {
3698 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3699 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003700 }
3701
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003702 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003703 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003704 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003705
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003706 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3707 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3708 }
3709 try {
3710 int appId = UserHandle.getAppId(uid);
3711 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3712 && !isUidForegroundOnRestrictPowerUL(uid)) {
3713 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3714 } else {
3715 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3716 }
3717 } finally {
3718 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003719 }
3720 }
3721
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003722 /**
3723 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3724 * changed.
3725 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003726 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003727 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003728 boolean paroled = mUsageStats.isAppIdleParoleOn();
3729 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003730 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003731
3732 int ruleCount = mUidFirewallStandbyRules.size();
3733 for (int i = 0; i < ruleCount; i++) {
3734 int uid = mUidFirewallStandbyRules.keyAt(i);
3735 int oldRules = mUidRules.get(uid);
3736 if (enableChain) {
3737 // Chain wasn't enabled before and the other power-related
3738 // chains are whitelists, so we can clear the
3739 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3740 // the effective rules result in blocking network access.
3741 oldRules &= MASK_METERED_NETWORKS;
3742 } else {
3743 // Skip if it had no restrictions to begin with
3744 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3745 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003746 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3747 if (newUidRules == RULE_NONE) {
3748 mUidRules.delete(uid);
3749 } else {
3750 mUidRules.put(uid, newUidRules);
3751 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003752 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003753 }
3754
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003755 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003756 * Update rules that might be changed by {@link #mRestrictBackground},
3757 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003758 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003759 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003760 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003761 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3762 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3763 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3764 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003765 try {
Felipe Leme09700462016-09-08 09:33:48 -07003766 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003767 updateRulesForRestrictPowerUL();
3768 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003769
Felipe Leme873a83a2016-09-07 11:34:10 -07003770 // If the set of restricted networks may have changed, re-evaluate those.
3771 if (restrictedNetworksChanged) {
3772 normalizePoliciesNL();
3773 updateNetworkRulesNL();
3774 }
3775 } finally {
3776 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003777 }
3778 }
3779
Felipe Leme09700462016-09-08 09:33:48 -07003780 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003781 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003782 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003783 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3784 try {
3785 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003786 updateRulesForPowerSaveUL();
3787 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3788 } finally {
3789 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3790 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003791 }
3792
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003793 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003794 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003795 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3796 try {
3797 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3798 } finally {
3799 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3800 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003801 }
3802
3803 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3804 private static final int TYPE_RESTRICT_POWER = 2;
3805 @Retention(RetentionPolicy.SOURCE)
3806 @IntDef(flag = false, value = {
3807 TYPE_RESTRICT_BACKGROUND,
3808 TYPE_RESTRICT_POWER,
3809 })
3810 public @interface RestrictType {
3811 }
3812
3813 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003814 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003815 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003816 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3817 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3818 }
3819 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003820 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003821
3822 final PackageManager pm = mContext.getPackageManager();
3823 final List<UserInfo> users;
3824 final List<ApplicationInfo> apps;
3825
3826 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3827 try {
3828 users = mUserManager.getUsers();
3829 } finally {
3830 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3831 }
3832 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3833 try {
3834 apps = pm.getInstalledApplications(
3835 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3836 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3837 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3838 } finally {
3839 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3840 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003841
Felipe Leme873a83a2016-09-07 11:34:10 -07003842 final int usersSize = users.size();
3843 final int appsSize = apps.size();
3844 for (int i = 0; i < usersSize; i++) {
3845 final UserInfo user = users.get(i);
3846 for (int j = 0; j < appsSize; j++) {
3847 final ApplicationInfo app = apps.get(j);
3848 final int uid = UserHandle.getUid(user.id, app.uid);
3849 switch (type) {
3850 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003851 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003852 break;
3853 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003854 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003855 break;
3856 default:
3857 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3858 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003859 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003860 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003861 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003862 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003863 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003864 }
3865
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003866 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003867 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003868 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003869 final int numUsers = users.size();
3870 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003871 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003872 int uid = UserHandle.getUid(user.id, appId);
3873 // Update external firewall rules.
3874 updateRuleForAppIdleUL(uid);
3875 updateRuleForDeviceIdleUL(uid);
3876 updateRuleForRestrictPowerUL(uid);
3877 // Update internal rules.
3878 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003879 }
3880 }
3881
Felipe Leme70c57c22016-03-29 10:45:13 -07003882 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3883 // methods below could be merged into a isUidValidForRules() method.
3884 private boolean isUidValidForBlacklistRules(int uid) {
3885 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003886 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003887 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003888 return true;
3889 }
3890
3891 return false;
3892 }
3893
Felipe Leme70c57c22016-03-29 10:45:13 -07003894 private boolean isUidValidForWhitelistRules(int uid) {
3895 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3896 }
3897
Amith Yamasani15e472352015-04-24 19:06:07 -07003898 private boolean isUidIdle(int uid) {
3899 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3900 final int userId = UserHandle.getUserId(uid);
3901
songjinshi0655edd2016-05-18 19:55:32 +08003902 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003903 for (String packageName : packages) {
3904 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3905 return false;
3906 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003907 }
3908 }
3909 return true;
3910 }
3911
3912 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003913 * Checks if an uid has INTERNET permissions.
3914 * <p>
3915 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003916 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003917 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003918 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003919 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003920 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003921 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003922 }
3923 } catch (RemoteException e) {
3924 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003925 return true;
3926 }
3927
3928 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003929 * Clears all state - internal and external - associated with an UID.
3930 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003931 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07003932 private void onUidDeletedUL(int uid) {
3933 // First cleanup in-memory state synchronously...
3934 mUidRules.delete(uid);
3935 mUidPolicy.delete(uid);
3936 mUidFirewallStandbyRules.delete(uid);
3937 mUidFirewallDozableRules.delete(uid);
3938 mUidFirewallPowerSaveRules.delete(uid);
3939 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3940 mPowerSaveWhitelistAppIds.delete(uid);
3941 mPowerSaveTempWhitelistAppIds.delete(uid);
3942
3943 // ...then update iptables asynchronously.
3944 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3945 }
3946
3947 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003948 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003949 *
Felipe Leme781ba142016-05-09 16:24:48 -07003950 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003951 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003952 * <li>Doze mode
3953 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003954 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003955 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003956 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003957 *
3958 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003959 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003960 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07003961 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003962 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003963 updateRuleForDeviceIdleUL(uid);
3964 updateRuleForAppIdleUL(uid);
3965 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003966
3967 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003968 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003969
3970 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003971 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003972 }
3973
Felipe Leme70c57c22016-03-29 10:45:13 -07003974 /**
3975 * Applies network rules to bandwidth controllers based on process state and user-defined
3976 * restrictions (blacklist / whitelist).
3977 *
3978 * <p>
3979 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3980 * networks:
3981 * <ul>
3982 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3983 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3984 * also blacklisted.
3985 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3986 * no UIDs other those whitelisted will have access.
3987 * <ul>
3988 *
3989 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3990 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3991 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3992 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003993 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003994 * {@link INetworkManagementService}, but this method should also be called in events (like
3995 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3996 * following rules should also be applied:
3997 *
3998 * <ul>
3999 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4000 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4001 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4002 * {@code bw_penalty_box}.
4003 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4004 * </ul>
4005 *
4006 * <p>For optimization, the rules are only applied on user apps that have internet access
4007 * permission, since there is no need to change the {@code iptables} rule if the app does not
4008 * have permission to use the internet.
4009 *
4010 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004011 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004012 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004013 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004014 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4015 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4016 "updateRulesForDataUsageRestrictionsUL: " + uid);
4017 }
4018 try {
4019 updateRulesForDataUsageRestrictionsULInner(uid);
4020 } finally {
4021 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4022 }
4023 }
4024
4025 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004026 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004027 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004028 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004029 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004030
Dianne Hackborn497175b2014-07-01 12:56:08 -07004031 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004032 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004033 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004034 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004035
Felipe Leme781ba142016-05-09 16:24:48 -07004036 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004037 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004038 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4039 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004040
Felipe Leme70c57c22016-03-29 10:45:13 -07004041 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004042 if (isRestrictedByAdmin) {
4043 newRule = RULE_REJECT_METERED;
4044 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004045 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4046 newRule = RULE_TEMPORARY_ALLOW_METERED;
4047 } else if (isWhitelisted) {
4048 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004049 }
4050 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004051 if (isBlacklisted) {
4052 newRule = RULE_REJECT_METERED;
4053 } else if (mRestrictBackground && isWhitelisted) {
4054 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004055 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004056 }
Felipe Leme781ba142016-05-09 16:24:48 -07004057 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004058
Felipe Lemef28983d2016-03-25 12:18:23 -07004059 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004060 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004061 + ": isForeground=" +isForeground
4062 + ", isBlacklisted=" + isBlacklisted
4063 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004064 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004065 + ", oldRule=" + uidRulesToString(oldRule)
4066 + ", newRule=" + uidRulesToString(newRule)
4067 + ", newUidRules=" + uidRulesToString(newUidRules)
4068 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004069 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004070
Felipe Leme46c4fc32016-05-04 09:21:43 -07004071 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004072 mUidRules.delete(uid);
4073 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004074 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004075 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004076
Felipe Leme70c57c22016-03-29 10:45:13 -07004077 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004078 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004079 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004080 // Temporarily whitelist foreground app, removing from blacklist if necessary
4081 // (since bw_penalty_box prevails over bw_happy_box).
4082
4083 setMeteredNetworkWhitelist(uid, true);
4084 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4085 // but ideally it should be just:
4086 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004087 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004088 setMeteredNetworkBlacklist(uid, false);
4089 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004090 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004091 // Remove temporary whitelist from app that is not on foreground anymore.
4092
4093 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4094 // but ideally they should be just:
4095 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4096 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004097 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004098 setMeteredNetworkWhitelist(uid, false);
4099 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004100 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004101 setMeteredNetworkBlacklist(uid, true);
4102 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004103 } else if (hasRule(newRule, RULE_REJECT_METERED)
4104 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004105 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004106 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004107 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004108 // Since blacklist prevails over whitelist, we need to handle the special case
4109 // where app is whitelisted and blacklisted at the same time (although such
4110 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004111 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004112 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004113 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4114 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004115 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004116 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004117 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004118 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004119 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4120 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004121 + ", whitelisted=" + isWhitelisted
4122 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004123 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004124 + ", newRule=" + uidRulesToString(newUidRules)
4125 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004126 }
Felipe Leme781ba142016-05-09 16:24:48 -07004127
Sudheer Shankac9d94072017-02-22 22:13:55 +00004128 // Dispatch changed rule to existing listeners.
4129 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004130 }
4131 }
4132
4133 /**
4134 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4135 * listeners in case of change.
4136 * <p>
4137 * There are 3 power-related rules that affects whether an app has background access on
4138 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4139 * restriction, it's added to the equivalent firewall chain:
4140 * <ul>
4141 * <li>App is idle: {@code fw_standby} firewall chain.
4142 * <li>Device is idle: {@code fw_dozable} firewall chain.
4143 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4144 * </ul>
4145 * <p>
4146 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4147 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4148 * <p>
4149 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4150 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004151 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004152 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004153 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4154
Sudheer Shankac9d94072017-02-22 22:13:55 +00004155 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004156
Sudheer Shankac9d94072017-02-22 22:13:55 +00004157 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004158 mUidRules.delete(uid);
4159 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004160 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004161 }
4162 }
4163
4164 /**
4165 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4166 *
4167 * @param uid the uid of the app to update rules for
4168 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4169 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4170 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004171 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004172 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004173 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004174 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4175 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4176 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4177 + (paroled ? "P" : "-"));
4178 }
4179 try {
4180 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4181 } finally {
4182 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4183 }
4184 }
4185
4186 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004187 if (!isUidValidForBlacklistRules(uid)) {
4188 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004189 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004190 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004191
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004192 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004193 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004194 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004195
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07004196 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004197 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4198 int newRule = RULE_NONE;
4199
4200 // First step: define the new rule based on user restrictions and foreground state.
4201
4202 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4203 // by considering the foreground and non-foreground states.
4204 if (isForeground) {
4205 if (restrictMode) {
4206 newRule = RULE_ALLOW_ALL;
4207 }
4208 } else if (restrictMode) {
4209 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4210 }
4211
4212 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4213
4214 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004215 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004216 + ", isIdle: " + isIdle
4217 + ", mRestrictPower: " + mRestrictPower
4218 + ", mDeviceIdleMode: " + mDeviceIdleMode
4219 + ", isForeground=" + isForeground
4220 + ", isWhitelisted=" + isWhitelisted
4221 + ", oldRule=" + uidRulesToString(oldRule)
4222 + ", newRule=" + uidRulesToString(newRule)
4223 + ", newUidRules=" + uidRulesToString(newUidRules)
4224 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4225 }
4226
Felipe Leme781ba142016-05-09 16:24:48 -07004227 // Second step: notify listeners if state changed.
4228 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004229 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004230 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004231 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004232 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4233 } else {
4234 // All scenarios should have been covered above
4235 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4236 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004237 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004238 + ", newRule=" + uidRulesToString(newUidRules)
4239 + ", oldRule=" + uidRulesToString(oldUidRules));
4240 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004241 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004242 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004243
Sudheer Shankac9d94072017-02-22 22:13:55 +00004244 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004245 }
4246
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004247 private class AppIdleStateChangeListener
4248 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4249
4250 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004251 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4252 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004253 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004254 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4255 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004256 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004257 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004258 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004259 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004260 }
4261 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004262 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004263 }
4264
4265 @Override
4266 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004267 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004268 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004269 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004270 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004271 }
4272 }
4273
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004274 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4275 if (listener != null) {
4276 try {
4277 listener.onUidRulesChanged(uid, uidRules);
4278 } catch (RemoteException ignored) {
4279 }
4280 }
4281 }
4282
4283 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4284 String[] meteredIfaces) {
4285 if (listener != null) {
4286 try {
4287 listener.onMeteredIfacesChanged(meteredIfaces);
4288 } catch (RemoteException ignored) {
4289 }
4290 }
4291 }
4292
4293 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4294 boolean restrictBackground) {
4295 if (listener != null) {
4296 try {
4297 listener.onRestrictBackgroundChanged(restrictBackground);
4298 } catch (RemoteException ignored) {
4299 }
4300 }
4301 }
4302
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004303 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4304 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004305 if (listener != null) {
4306 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004307 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004308 } catch (RemoteException ignored) {
4309 }
4310 }
4311 }
4312
Jeff Sharkey9252b342018-01-19 07:58:35 +09004313 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4314 int overrideMask, int overrideValue) {
4315 if (listener != null) {
4316 try {
4317 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4318 } catch (RemoteException ignored) {
4319 }
4320 }
4321 }
4322
Makoto Onuki8e777332017-03-28 11:25:47 -07004323 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004324 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004325 public boolean handleMessage(Message msg) {
4326 switch (msg.what) {
4327 case MSG_RULES_CHANGED: {
4328 final int uid = msg.arg1;
4329 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004330 final int length = mListeners.beginBroadcast();
4331 for (int i = 0; i < length; i++) {
4332 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4333 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004334 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004335 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004336 return true;
4337 }
4338 case MSG_METERED_IFACES_CHANGED: {
4339 final String[] meteredIfaces = (String[]) msg.obj;
4340 final int length = mListeners.beginBroadcast();
4341 for (int i = 0; i < length; i++) {
4342 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004343 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004344 }
4345 mListeners.finishBroadcast();
4346 return true;
4347 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004348 case MSG_LIMIT_REACHED: {
4349 final String iface = (String) msg.obj;
4350
Felipe Lemef0823852016-06-08 13:43:08 -07004351 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004352 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004353 // force stats update to make sure we have
4354 // numbers that caused alert to trigger.
4355 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004356
Felipe Lemef0823852016-06-08 13:43:08 -07004357 updateNetworkEnabledNL();
4358 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004359 }
4360 }
4361 return true;
4362 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004363 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4364 final boolean restrictBackground = msg.arg1 != 0;
4365 final int length = mListeners.beginBroadcast();
4366 for (int i = 0; i < length; i++) {
4367 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004368 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004369 }
4370 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004371 final Intent intent =
4372 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4373 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4374 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4375 return true;
4376 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004377 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004378 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004379 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004380 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004381 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004382 final int length = mListeners.beginBroadcast();
4383 for (int i = 0; i < length; i++) {
4384 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004385 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004386 }
4387 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004388 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4389 if (notifyApp.booleanValue()) {
4390 broadcastRestrictBackgroundChanged(uid, notifyApp);
4391 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004392 return true;
4393 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004394 case MSG_ADVISE_PERSIST_THRESHOLD: {
4395 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004396 // make sure stats are recorded frequently enough; we aim
4397 // for 2MB threshold for 2GB/month rules.
4398 final long persistThreshold = lowestRule / 1000;
4399 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004400 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004401 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004402 case MSG_UPDATE_INTERFACE_QUOTA: {
4403 removeInterfaceQuota((String) msg.obj);
4404 // int params need to be stitched back into a long
4405 setInterfaceQuota((String) msg.obj,
4406 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4407 return true;
4408 }
4409 case MSG_REMOVE_INTERFACE_QUOTA: {
4410 removeInterfaceQuota((String) msg.obj);
4411 return true;
4412 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004413 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4414 resetUidFirewallRules(msg.arg1);
4415 return true;
4416 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004417 case MSG_SUBSCRIPTION_OVERRIDE: {
4418 final int overrideMask = msg.arg1;
4419 final int overrideValue = msg.arg2;
4420 final int subId = (int) msg.obj;
4421 final int length = mListeners.beginBroadcast();
4422 for (int i = 0; i < length; i++) {
4423 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4424 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4425 }
4426 mListeners.finishBroadcast();
4427 return true;
4428 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004429 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4430 final int userId = msg.arg1;
4431 final Set<String> packageNames = (Set<String>) msg.obj;
4432 setMeteredRestrictedPackagesInternal(packageNames, userId);
4433 return true;
4434 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004435 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4436 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4437 final boolean enabled = msg.arg1 != 0;
4438 setNetworkTemplateEnabledInner(template, enabled);
4439 return true;
4440 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004441 default: {
4442 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004443 }
4444 }
4445 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004446 };
4447
4448 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4449 @Override
4450 public boolean handleMessage(Message msg) {
4451 switch (msg.what) {
4452 case UID_MSG_STATE_CHANGED: {
4453 final int uid = msg.arg1;
4454 final int procState = msg.arg2;
4455 final long procStateSeq = (Long) msg.obj;
4456
4457 handleUidChanged(uid, procState, procStateSeq);
4458 return true;
4459 }
4460 case UID_MSG_GONE: {
4461 final int uid = msg.arg1;
4462 handleUidGone(uid);
4463 return true;
4464 }
4465 default: {
4466 return false;
4467 }
4468 }
4469 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004470
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004471 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004472
Makoto Onuki8e777332017-03-28 11:25:47 -07004473 void handleUidChanged(int uid, int procState, long procStateSeq) {
4474 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4475 try {
4476 synchronized (mUidRulesFirstLock) {
4477 // We received a uid state change callback, add it to the history so that it
4478 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004479 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004480 // Now update the network policy rules as per the updated uid state.
4481 updateUidStateUL(uid, procState);
4482 // Updating the network rules is done, so notify AMS about this.
4483 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4484 }
4485 } finally {
4486 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4487 }
4488 }
4489
4490 void handleUidGone(int uid) {
4491 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4492 try {
4493 synchronized (mUidRulesFirstLock) {
4494 removeUidStateUL(uid);
4495 }
4496 } finally {
4497 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4498 }
4499 }
4500
Felipe Leme57e3d312016-08-23 14:42:52 -07004501 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4502 final PackageManager pm = mContext.getPackageManager();
4503 final String[] packages = pm.getPackagesForUid(uid);
4504 if (packages != null) {
4505 final int userId = UserHandle.getUserId(uid);
4506 for (String packageName : packages) {
4507 final Intent intent =
4508 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4509 intent.setPackage(packageName);
4510 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4511 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4512 }
4513 }
4514 }
4515
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004516 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4517 // long quotaBytes split up into two ints to fit in message
4518 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4519 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4520 }
4521
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004522 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004523 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004524 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004525 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004526 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004527 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004528 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004529 }
4530 }
4531
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004532 private void removeInterfaceQuotaAsync(String iface) {
4533 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4534 }
4535
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004536 private void removeInterfaceQuota(String iface) {
4537 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004538 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004539 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004540 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004541 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004542 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004543 }
4544 }
4545
Felipe Leme70c57c22016-03-29 10:45:13 -07004546 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4547 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004548 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004549 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004550 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004551 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4552 } catch (RemoteException e) {
4553 // ignored; service lives in system_server
4554 }
4555 }
4556
4557 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4558 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4559 try {
4560 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4561 } catch (IllegalStateException e) {
4562 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004563 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004564 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004565 }
4566 }
4567
Felipe Lemebc853dd2016-09-08 13:26:55 -07004568 private static final int CHAIN_TOGGLE_NONE = 0;
4569 private static final int CHAIN_TOGGLE_ENABLE = 1;
4570 private static final int CHAIN_TOGGLE_DISABLE = 2;
4571 @Retention(RetentionPolicy.SOURCE)
4572 @IntDef(flag = false, value = {
4573 CHAIN_TOGGLE_NONE,
4574 CHAIN_TOGGLE_ENABLE,
4575 CHAIN_TOGGLE_DISABLE
4576 })
4577 public @interface ChainToggleType {
4578 }
4579
4580 /**
4581 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004582 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004583 *
4584 * @param chain firewall chain.
4585 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4586 * @param toggle whether the chain should be enabled, disabled, or not changed.
4587 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004588 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004589 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004590 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004591 if (uidRules != null) {
4592 setUidFirewallRulesUL(chain, uidRules);
4593 }
4594 if (toggle != CHAIN_TOGGLE_NONE) {
4595 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4596 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004597 }
4598
Amith Yamasani15e472352015-04-24 19:06:07 -07004599 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004600 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4601 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4602 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004603 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004604 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004605 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004606 int size = uidRules.size();
4607 int[] uids = new int[size];
4608 int[] rules = new int[size];
4609 for(int index = size - 1; index >= 0; --index) {
4610 uids[index] = uidRules.keyAt(index);
4611 rules[index] = uidRules.valueAt(index);
4612 }
4613 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004614 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004615 } catch (IllegalStateException e) {
4616 Log.wtf(TAG, "problem setting firewall uid rules", e);
4617 } catch (RemoteException e) {
4618 // ignored; service lives in system_server
4619 }
4620 }
4621
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004622 /**
4623 * Add or remove a uid to the firewall blacklist for all network ifaces.
4624 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004625 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004626 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4627 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4628 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004629 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004630 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004631 if (chain == FIREWALL_CHAIN_DOZABLE) {
4632 mUidFirewallDozableRules.put(uid, rule);
4633 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4634 mUidFirewallStandbyRules.put(uid, rule);
4635 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4636 mUidFirewallPowerSaveRules.put(uid, rule);
4637 }
4638
4639 try {
4640 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004641 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004642 } catch (IllegalStateException e) {
4643 Log.wtf(TAG, "problem setting firewall uid rules", e);
4644 } catch (RemoteException e) {
4645 // ignored; service lives in system_server
4646 }
4647 } finally {
4648 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004649 }
4650 }
4651
4652 /**
4653 * Add or remove a uid to the firewall blacklist for all network ifaces.
4654 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004655 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004656 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004657 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4658 mFirewallChainStates.get(chain) == enable) {
4659 // All is the same, nothing to do.
4660 return;
4661 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004662 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004663 try {
4664 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004665 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004666 } catch (IllegalStateException e) {
4667 Log.wtf(TAG, "problem enable firewall chain", e);
4668 } catch (RemoteException e) {
4669 // ignored; service lives in system_server
4670 }
4671 }
4672
Felipe Leme03e95e22016-09-09 09:25:31 -07004673 /**
4674 * Resets all firewall rules associated with an UID.
4675 */
4676 private void resetUidFirewallRules(int uid) {
4677 try {
4678 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4679 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4680 mNetworkManager
4681 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4682 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4683 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4684 } catch (IllegalStateException e) {
4685 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4686 } catch (RemoteException e) {
4687 // ignored; service lives in system_server
4688 }
4689 }
4690
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004691 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004692 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004693 return getNetworkTotalBytes(template, start, end);
4694 }
4695
4696 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004697 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004698 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004699 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004700 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004701 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004702 }
4703 }
4704
4705 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4706 try {
4707 return mNetworkStats.getNetworkUidBytes(template, start, end);
4708 } catch (RuntimeException e) {
4709 Slog.w(TAG, "Failed to read network stats: " + e);
4710 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004711 }
4712 }
4713
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004714 private boolean isBandwidthControlEnabled() {
4715 final long token = Binder.clearCallingIdentity();
4716 try {
4717 return mNetworkManager.isBandwidthControlEnabled();
4718 } catch (RemoteException e) {
4719 // ignored; service lives in system_server
4720 return false;
4721 } finally {
4722 Binder.restoreCallingIdentity(token);
4723 }
4724 }
4725
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004726 private static Intent buildAllowBackgroundDataIntent() {
4727 return new Intent(ACTION_ALLOW_BACKGROUND);
4728 }
4729
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004730 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4731 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004732 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4733 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4734 return intent;
4735 }
4736
4737 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4738 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4739 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004740 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4741 return intent;
4742 }
4743
Wei Liu546cb772016-07-21 16:19:01 -07004744 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004745 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004746 intent.setComponent(ComponentName.unflattenFromString(
4747 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004748 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4749 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4750 return intent;
4751 }
4752
Wei Liu546cb772016-07-21 16:19:01 -07004753 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004754 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004755 intent.setComponent(ComponentName.unflattenFromString(
4756 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004757 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4758 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4759 return intent;
4760 }
4761
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004762 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004763 public void addIdleHandler(IdleHandler handler) {
4764 mHandler.getLooper().getQueue().addIdleHandler(handler);
4765 }
4766
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004767 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004768 @VisibleForTesting
4769 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4770 mRestrictBackgroundPowerState = result;
4771
4772 boolean restrictBackground = result.batterySaverEnabled;
4773 boolean shouldInvokeRestrictBackground;
4774 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4775 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4776
4777 if (result.globalBatterySaverEnabled) {
4778 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4779 // turn it on.
4780 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4781 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4782 localRestrictBgChangedInBsm = false;
4783 } else {
4784 // Try to restore the restrictBackground if it doesn't change in bsm
4785 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4786 restrictBackground = mRestrictBackgroundBeforeBsm;
4787 }
4788
4789 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004790 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004791 }
4792
4793 // Change it at last so setRestrictBackground() won't affect this variable
4794 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4795 }
4796
Jeff Sharkey1b861272011-05-22 00:34:52 -07004797 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4798 final int size = source.size();
4799 for (int i = 0; i < size; i++) {
4800 target.put(source.keyAt(i), true);
4801 }
4802 }
4803
Stuart Scottf1fb3972015-04-02 18:00:02 -07004804 @Override
4805 public void factoryReset(String subscriber) {
4806 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4807
Stuart Scotte3e314d2015-04-20 14:07:45 -07004808 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4809 return;
4810 }
4811
Stuart Scottf1fb3972015-04-02 18:00:02 -07004812 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004813 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004814 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4815 for (NetworkPolicy policy : policies) {
4816 if (policy.template.equals(template)) {
4817 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4818 policy.inferred = false;
4819 policy.clearSnooze();
4820 }
4821 }
4822 setNetworkPolicies(policies);
4823
4824 // Turn restrict background data off
4825 setRestrictBackground(false);
4826
Stuart Scotte3e314d2015-04-20 14:07:45 -07004827 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4828 // Remove app's "restrict background data" flag
4829 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4830 setUidPolicy(uid, POLICY_NONE);
4831 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004832 }
4833 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004834
Sudheer Shankab8f23162017-08-04 13:30:10 -07004835 @Override
4836 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004837 final long startTime = mStatLogger.getTime();
4838
Sudheer Shankab8f23162017-08-04 13:30:10 -07004839 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Makoto Onuki49392d32018-04-11 13:51:02 -07004840 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4841
4842 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4843
4844 return ret;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004845 }
4846
4847 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4848 final int uidRules;
4849 final boolean isBackgroundRestricted;
4850 synchronized (mUidRulesFirstLock) {
4851 uidRules = mUidRules.get(uid, RULE_NONE);
4852 isBackgroundRestricted = mRestrictBackground;
4853 }
4854 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004855 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004856 return true;
4857 }
4858 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004859 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004860 return false;
4861 }
4862 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004863 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004864 return true;
4865 }
4866 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004867 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004868 return false;
4869 }
4870 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004871 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004872 return false;
4873 }
4874 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004875 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004876 return true;
4877 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004878 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004879 return false;
4880 }
4881
Felipe Lemed17fda42016-04-29 11:12:45 -07004882 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4883
4884 @Override
4885 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004886 synchronized (mUidRulesFirstLock) {
4887 boolean changed = removeUserStateUL(userId, false);
4888 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004889 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004890 synchronized (mNetworkPoliciesSecondLock) {
4891 writePolicyAL();
4892 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004893 }
4894 }
4895 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004896
4897 /**
4898 * @return true if the given uid is restricted from doing networking on metered networks.
4899 */
4900 @Override
4901 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4902 final int uidRules;
4903 final boolean isBackgroundRestricted;
4904 synchronized (mUidRulesFirstLock) {
4905 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4906 isBackgroundRestricted = mRestrictBackground;
4907 }
4908 return isBackgroundRestricted
4909 && !hasRule(uidRules, RULE_ALLOW_METERED)
4910 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4911 }
4912
4913 /**
4914 * @return true if networking is blocked on the given interface for the given uid according
4915 * to current networking policies.
4916 */
4917 @Override
4918 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004919 final long startTime = mStatLogger.getTime();
4920
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004921 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004922 synchronized (mNetworkPoliciesSecondLock) {
4923 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004924 }
Makoto Onuki49392d32018-04-11 13:51:02 -07004925 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4926
4927 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4928
4929 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004930 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004931
4932 @Override
4933 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4934 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004935 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004936 if (added) {
4937 mPowerSaveTempWhitelistAppIds.put(appId, true);
4938 } else {
4939 mPowerSaveTempWhitelistAppIds.delete(appId);
4940 }
4941 updateRulesForTempWhitelistChangeUL(appId);
4942 }
4943 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004944
4945 @Override
4946 public SubscriptionPlan getSubscriptionPlan(Network network) {
4947 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004948 final int subId = getSubIdLocked(network);
4949 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004950 }
4951 }
4952
4953 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06004954 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
4955 synchronized (mNetworkPoliciesSecondLock) {
4956 final int subId = findRelevantSubIdNL(template);
4957 return getPrimarySubscriptionPlanLocked(subId);
4958 }
4959 }
4960
4961 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09004962 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004963 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004964 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004965 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004966 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004967 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004968 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4969 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4970 }
4971
4972 if (quotaType == QUOTA_TYPE_JOBS) {
4973 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4974 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4975 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4976 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4977 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4978 } else {
4979 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4980 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004981 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004982
4983 @Override
4984 public void onAdminDataAvailable() {
4985 mAdminDataAvailableLatch.countDown();
4986 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004987
4988 @Override
4989 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4990 setMeteredRestrictedPackagesInternal(packageNames, userId);
4991 }
4992
4993 @Override
4994 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4995 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4996 userId, 0, packageNames).sendToTarget();
4997 }
4998 }
4999
5000 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5001 synchronized (mUidRulesFirstLock) {
5002 final Set<Integer> newRestrictedUids = new ArraySet<>();
5003 for (String packageName : packageNames) {
5004 final int uid = getUidForPackage(packageName, userId);
5005 if (uid >= 0) {
5006 newRestrictedUids.add(uid);
5007 }
5008 }
5009 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5010 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5011 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5012 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5013 }
5014 }
5015
5016 private int getUidForPackage(String packageName, int userId) {
5017 try {
5018 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5019 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5020 } catch (NameNotFoundException e) {
5021 return -1;
5022 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005023 }
5024
5025 private int parseSubId(NetworkState state) {
5026 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5027 int subId = INVALID_SUBSCRIPTION_ID;
5028 if (state != null && state.networkCapabilities != null
5029 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5030 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5031 if (spec instanceof StringNetworkSpecifier) {
5032 try {
5033 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5034 } catch (NumberFormatException e) {
5035 }
5036 }
5037 }
5038 return subId;
5039 }
5040
Andreas Gampea36dc622018-02-05 17:19:22 -08005041 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005042 private int getSubIdLocked(Network network) {
5043 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005044 }
5045
Andreas Gampea36dc622018-02-05 17:19:22 -08005046 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005047 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5048 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005049 if (!ArrayUtils.isEmpty(plans)) {
5050 for (SubscriptionPlan plan : plans) {
5051 if (plan.getCycleRule().isRecurring()) {
5052 // Recurring plans will always have an active cycle
5053 return plan;
5054 } else {
5055 // Non-recurring plans need manual test for active cycle
5056 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5057 if (cycle.contains(ZonedDateTime.now(mClock))) {
5058 return plan;
5059 }
5060 }
5061 }
5062 }
5063 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005064 }
5065
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005066 /**
5067 * This will only ever be called once - during device boot.
5068 */
5069 private void waitForAdminData() {
5070 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5071 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5072 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5073 }
5074 }
5075
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005076 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5077 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005078 if (!mNetworkManagerReady) {
5079 return;
5080 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005081 if (oldRestrictedUids == null) {
5082 for (int uid : newRestrictedUids) {
5083 updateRulesForDataUsageRestrictionsUL(uid);
5084 }
5085 return;
5086 }
5087 for (int uid : oldRestrictedUids) {
5088 if (!newRestrictedUids.contains(uid)) {
5089 updateRulesForDataUsageRestrictionsUL(uid);
5090 }
5091 }
5092 for (int uid : newRestrictedUids) {
5093 if (!oldRestrictedUids.contains(uid)) {
5094 updateRulesForDataUsageRestrictionsUL(uid);
5095 }
5096 }
5097 }
5098
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005099 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005100 private boolean isRestrictedByAdminUL(int uid) {
5101 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5102 UserHandle.getUserId(uid));
5103 return restrictedUids != null && restrictedUids.contains(uid);
5104 }
5105
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005106 private static boolean hasRule(int uidRules, int rule) {
5107 return (uidRules & rule) != 0;
5108 }
5109
Jeff Sharkey2e471452018-01-19 18:02:47 +09005110 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5111 return (val != null) ? val : new NetworkState[0];
5112 }
5113
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005114 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5115 String key, boolean defaultValue) {
5116 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5117 }
5118
Chris Wren193ae6b2017-03-31 15:17:11 -04005119 private class NotificationId {
5120 private final String mTag;
5121 private final int mId;
5122
5123 NotificationId(NetworkPolicy policy, int type) {
5124 mTag = buildNotificationTag(policy, type);
5125 mId = type;
5126 }
5127
5128 @Override
5129 public boolean equals(Object o) {
5130 if (this == o) return true;
5131 if (!(o instanceof NotificationId)) return false;
5132 NotificationId that = (NotificationId) o;
5133 return Objects.equals(mTag, that.mTag);
5134 }
5135
5136 @Override
5137 public int hashCode() {
5138 return Objects.hash(mTag);
5139 }
5140
5141 /**
5142 * Build unique tag that identifies an active {@link NetworkPolicy}
5143 * notification of a specific type, like {@link #TYPE_LIMIT}.
5144 */
5145 private String buildNotificationTag(NetworkPolicy policy, int type) {
5146 return TAG + ":" + policy.template.hashCode() + ":" + type;
5147 }
5148
5149 public String getTag() {
5150 return mTag;
5151 }
5152
5153 public int getId() {
5154 return mId;
5155 }
5156 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005157}