blob: 5b8e8c0c7fe2b09ea130f35b6bd69056590befb6 [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 Sharkey53313d72017-07-13 16:47:32 -0600192import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700193import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400194import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700195import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700196import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700197import android.util.ArrayMap;
198import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700199import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900200import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700201import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700202import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600203import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600204import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700205import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600206import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700207import android.util.SparseBooleanArray;
208import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900209import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700211
Jeff Sharkey497e4432011-06-14 17:27:29 -0700212import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700213import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800214import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400215import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500216import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700217import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800218import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800219import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600220import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700222import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600223import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700224import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700225import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700226import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700227import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800228import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600229
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600230import libcore.io.IoUtils;
231
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233import org.xmlpull.v1.XmlSerializer;
234
235import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700236import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import java.io.FileInputStream;
238import java.io.FileNotFoundException;
239import java.io.FileOutputStream;
240import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700241import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700242import java.lang.annotation.Retention;
243import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100244import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700245import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900246import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600247import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700248import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600249import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900250import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700252import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600253import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400254import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800255import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800256import java.util.concurrent.CountDownLatch;
257import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700258
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700259/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 * Service that maintains low-level network policy rules, using
261 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700262 * <p>
263 * Derives active rules by combining a given policy with other system status,
264 * and delivers to listeners, such as {@link ConnectivityManager}, for
265 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700266 *
267 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000268 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700269 * <ul>
270 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
271 * rules).
272 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
273 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000274 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
275 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700276 * </ul>
277 *
278 * <p>
279 * As such, methods that require synchronization have the following prefixes:
280 * <ul>
281 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
282 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000283 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
284 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700285 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700286 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700287public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700288 static final String TAG = NetworkPolicyLogger.TAG;
289 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
290 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700291
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900292 /**
293 * No opportunistic quota could be calculated from user data plan or data settings.
294 */
295 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
296
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 private static final int VERSION_INIT = 1;
298 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700299 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800300 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800301 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800302 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700303 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700304 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700305 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700306 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600307 private static final int VERSION_ADDED_CYCLE = 11;
308 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800310 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400311 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800312 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400313 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400315 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900316 @VisibleForTesting
317 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700318
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319 private static final String TAG_POLICY_LIST = "policy-list";
320 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600321 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700323 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800324 private static final String TAG_WHITELIST = "whitelist";
325 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800326 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327
328 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700329 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
331 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700332 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600333 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
334 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
335 private static final String ATTR_CYCLE_START = "cycleStart";
336 private static final String ATTR_CYCLE_END = "cycleEnd";
337 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700338 private static final String ATTR_WARNING_BYTES = "warningBytes";
339 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700340 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800341 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
342 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800343 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700344 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700346 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700347 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600348 private static final String ATTR_SUB_ID = "subId";
349 private static final String ATTR_TITLE = "title";
350 private static final String ATTR_SUMMARY = "summary";
351 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
352 private static final String ATTR_USAGE_BYTES = "usageBytes";
353 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600354 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700355
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800356 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800357 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800358 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800359 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700360 private static final String ACTION_SNOOZE_RAPID =
361 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700362
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800363 /**
364 * Indicates the maximum wait time for admin data to be available;
365 */
366 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
367
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600368 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
369 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
370 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
371 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
372
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700373 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700374 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800375 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800376 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700377 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700378 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
379 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700380 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700381 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900382 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800383 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700384 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700385
Makoto Onuki8e777332017-03-28 11:25:47 -0700386 private static final int UID_MSG_STATE_CHANGED = 100;
387 private static final int UID_MSG_GONE = 101;
388
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600389 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
390
Jeff Sharkey75279902011-05-24 18:39:45 -0700391 private final Context mContext;
392 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700393 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700394 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700395 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700396 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700397 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700398 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399
400 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700401 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700402 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800403 @GuardedBy("mUidRulesFirstLock")
404 private PowerSaveState mRestrictBackgroundPowerState;
405
406 // Store the status of restrict background before turning on battery saver.
407 // Used to restore mRestrictBackground when battery saver is turned off.
408 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700409
Sudheer Shanka543339f2017-07-28 15:18:07 -0700410 // Denotes the status of restrict background read from disk.
411 private boolean mLoadedRestrictBackground;
412
Felipe Lemef0823852016-06-08 13:43:08 -0700413 // See main javadoc for instructions on how to use these locks.
414 final Object mUidRulesFirstLock = new Object();
415 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("allLocks") volatile boolean mSystemReady;
Jeff Sharkey050151e2018-04-13 14:28:30 -0600418 volatile boolean mSystemReallyReady;
Felipe Lemef0823852016-06-08 13:43:08 -0700419
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
421 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
422 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800423 // Store whether user flipped restrict background in battery saver mode
424 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700425
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700426 private final boolean mSuppressDefaultPolicy;
427
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800428 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
429
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700430 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600431 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800432 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700433
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600434 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600435 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600436 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600437 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600438 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600439 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600440
Jeff Sharkey9252b342018-01-19 07:58:35 +0900441 /** Map from subId to daily opportunistic quota. */
442 @GuardedBy("mNetworkPoliciesSecondLock")
443 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
444
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700445 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700446 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700447 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700448 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700449
Felipe Lemef0823852016-06-08 13:43:08 -0700450 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700451 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700453 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700454 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800455 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700456
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700457 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700459 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
460
Jeff Sharkey32566012014-12-02 18:30:14 -0800461 /**
462 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700463 * in power save mode, except device idle (doze) still applies.
464 * TODO: An int array might be sufficient
465 */
Felipe Lemef0823852016-06-08 13:43:08 -0700466 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700467 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
468
469 /**
470 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800471 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700472 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800473 */
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700475 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700476
Felipe Lemef0823852016-06-08 13:43:08 -0700477 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700478 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
479
Felipe Lemeb85a6372016-01-14 16:16:16 -0800480 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800481 * UIDs that have been initially white-listed by system to avoid restricted background.
482 */
Felipe Lemef0823852016-06-08 13:43:08 -0700483 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800484 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
485 new SparseBooleanArray();
486
487 /**
488 * UIDs that have been initially white-listed by system to avoid restricted background,
489 * but later revoked by user.
490 */
Felipe Lemef0823852016-06-08 13:43:08 -0700491 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800492 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
493 new SparseBooleanArray();
494
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700495 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700496 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800497 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700498 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700499 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800500 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700501
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700502 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700503 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400504 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700505
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700506 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700507 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800508 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700509
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600510 /** Map from network ID to last observed meteredness state */
511 @GuardedBy("mNetworkPoliciesSecondLock")
512 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
513
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900514 /** Map from network ID to last observed roaming state */
515 @GuardedBy("mNetworkPoliciesSecondLock")
516 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
517
Jeff Sharkey9252b342018-01-19 07:58:35 +0900518 /** Map from netId to subId as of last update */
519 @GuardedBy("mNetworkPoliciesSecondLock")
520 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
521
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800522 /**
523 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
524 * userId to restricted uids which belong to that user.
525 */
526 @GuardedBy("mUidRulesFirstLock")
527 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
528
Jeff Sharkey32566012014-12-02 18:30:14 -0800529 private final RemoteCallbackList<INetworkPolicyListener>
530 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700531
Dianne Hackborn497175b2014-07-01 12:56:08 -0700532 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700533 @VisibleForTesting
534 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700535
536 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700537
Felipe Lemef0823852016-06-08 13:43:08 -0700538 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700539 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700540
Svet Ganov16a16892015-04-16 10:32:04 -0700541 private final AppOpsManager mAppOps;
542
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800543 private final IPackageManager mIPm;
544
Sudheer Shankae7361852017-03-07 11:51:46 -0800545 private ActivityManagerInternal mActivityManagerInternal;
546
Sudheer Shanka352dc572017-09-22 17:09:38 -0700547 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800548
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700549 // TODO: keep whitelist of system-critical services that should never have
550 // rules enforced, such as system, phone, and radio UIDs.
551
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700552 // TODO: migrate notifications to SystemUI
553
Makoto Onuki49392d32018-04-11 13:51:02 -0700554
555 interface Stats {
556 int UPDATE_NETWORK_ENABLED = 0;
557 int IS_UID_NETWORKING_BLOCKED = 1;
558
559 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
560 }
561
562 public final StatLogger mStatLogger = new StatLogger(new String[] {
563 "updateNetworkEnabledNL()",
564 "isUidNetworkingBlocked()",
565 });
566
Jeff Sharkey75279902011-05-24 18:39:45 -0700567 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700568 INetworkManagementService networkManagement) {
569 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
570 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700571 }
572
Jeff Sharkey9911a282018-02-14 22:29:11 -0700573 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700574 return new File(Environment.getDataDirectory(), "system");
575 }
576
Jeff Sharkey9911a282018-02-14 22:29:11 -0700577 private static @NonNull Clock getDefaultClock() {
578 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
579 Clock.systemUTC());
580 }
581
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700582 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700583 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
584 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700585 mContext = checkNotNull(context, "missing context");
586 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700587 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700588 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700589 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700590 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700591 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700592 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700593 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700594
Amith Yamasani450a16b2013-09-18 16:28:50 -0700595 HandlerThread thread = new HandlerThread(TAG);
596 thread.start();
597 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598
Makoto Onuki8e777332017-03-28 11:25:47 -0700599 // We create another thread for the UID events, which are more time-critical.
600 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
601 /*allowIo=*/ false);
602 mUidEventThread.start();
603 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
604
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700605 mSuppressDefaultPolicy = suppressDefaultPolicy;
606
Dianne Hackborne17b4452018-01-10 13:15:40 -0800607 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700608
609 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800610
Felipe Lemed17fda42016-04-29 11:12:45 -0700611 // Expose private service for system components to use.
612 LocalServices.addService(NetworkPolicyManagerInternal.class,
613 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700614 }
615
616 public void bindConnectivityManager(IConnectivityManager connManager) {
617 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700618 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700619
Felipe Lemef0823852016-06-08 13:43:08 -0700620 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700621 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700622 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
623 mPowerSaveWhitelistExceptIdleAppIds.clear();
624 if (whitelist != null) {
625 for (int uid : whitelist) {
626 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
627 }
628 }
629 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700630 mPowerSaveWhitelistAppIds.clear();
631 if (whitelist != null) {
632 for (int uid : whitelist) {
633 mPowerSaveWhitelistAppIds.put(uid, true);
634 }
635 }
636 } catch (RemoteException e) {
637 }
638 }
639
Felipe Lemea9505cc2016-02-26 10:28:41 -0800640 /**
641 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
642 * revoke the whitelist.
643 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700644 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800645 */
Felipe Lemef0823852016-06-08 13:43:08 -0700646 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800647 final List<UserInfo> users = mUserManager.getUsers();
648 final int numberUsers = users.size();
649
Felipe Lemea110eec2016-04-29 09:58:06 -0700650 boolean changed = false;
651 for (int i = 0; i < numberUsers; i++) {
652 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700653 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700654 }
655 return changed;
656 }
657
Felipe Lemef0823852016-06-08 13:43:08 -0700658 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700659 final SystemConfig sysConfig = SystemConfig.getInstance();
660 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800661 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
662 boolean changed = false;
663 for (int i = 0; i < allowDataUsage.size(); i++) {
664 final String pkg = allowDataUsage.valueAt(i);
665 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700666 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
667 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800668 final ApplicationInfo app;
669 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700670 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800671 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700672 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
673 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800674 continue;
675 }
676 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700677 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
678 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800679 continue;
680 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700681 final int uid = UserHandle.getUid(userId, app.uid);
682 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
683 if (LOGD)
684 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
685 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800686 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700687 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700688 if (LOGD)
689 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
690 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700691 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700692 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800693 }
694 }
695 return changed;
696 }
697
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800698 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700699 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800700 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700701 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800702 // Boost thread's priority during system server init
703 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700704 if (!isBandwidthControlEnabled()) {
705 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
706 return;
707 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700708
Felipe Leme873a83a2016-09-07 11:34:10 -0700709 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700710 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700711
Felipe Leme873a83a2016-09-07 11:34:10 -0700712 synchronized (mUidRulesFirstLock) {
713 synchronized (mNetworkPoliciesSecondLock) {
714 updatePowerSaveWhitelistUL();
715 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
716 mPowerManagerInternal.registerLowPowerModeObserver(
717 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800718 @Override
719 public int getServiceType() {
720 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700721 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800722
723 @Override
724 public void onLowPowerModeChanged(PowerSaveState result) {
725 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800726 if (LOGD) {
727 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
728 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800729 synchronized (mUidRulesFirstLock) {
730 if (mRestrictPower != enabled) {
731 mRestrictPower = enabled;
732 updateRulesForRestrictPowerUL();
733 }
734 }
735 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800736 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800737 mRestrictPower = mPowerManagerInternal.getLowPowerState(
738 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700739
740 mSystemReady = true;
741
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800742 waitForAdminData();
743
Felipe Leme873a83a2016-09-07 11:34:10 -0700744 // read policy from disk
745 readPolicyAL();
746
jackqdyulei29c82ab2017-03-10 14:09:16 -0800747 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700748 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800749 mRestrictBackgroundPowerState = mPowerManagerInternal
750 .getLowPowerState(ServiceType.DATA_SAVER);
751 final boolean localRestrictBackground =
752 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700753 if (localRestrictBackground && !mLoadedRestrictBackground) {
754 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800755 }
756 mPowerManagerInternal.registerLowPowerModeObserver(
757 new PowerManagerInternal.LowPowerModeListener() {
758 @Override
759 public int getServiceType() {
760 return ServiceType.DATA_SAVER;
761 }
762
763 @Override
764 public void onLowPowerModeChanged(PowerSaveState result) {
765 synchronized (mUidRulesFirstLock) {
766 updateRestrictBackgroundByLowPowerModeUL(result);
767 }
768 }
769 });
770
Felipe Leme873a83a2016-09-07 11:34:10 -0700771 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
772 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700773 }
Felipe Lemef0823852016-06-08 13:43:08 -0700774
Sudheer Shanka543339f2017-07-28 15:18:07 -0700775 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700776 updateRulesForGlobalChangeAL(false);
777 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700778 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800779 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700780
Sudheer Shankae7361852017-03-07 11:51:46 -0800781 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700782 try {
783 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000784 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800785 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700786 mNetworkManager.registerObserver(mAlertObserver);
787 } catch (RemoteException e) {
788 // ignored; both services live in system_server
789 }
790
791 // listen for changes to power save whitelist
792 final IntentFilter whitelistFilter = new IntentFilter(
793 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
794 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 // watch for network interfaces to be claimed
797 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
798 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
799
800 // listen for package changes to update policy
801 final IntentFilter packageFilter = new IntentFilter();
802 packageFilter.addAction(ACTION_PACKAGE_ADDED);
803 packageFilter.addDataScheme("package");
804 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
805
806 // listen for UID changes to update policy
807 mContext.registerReceiver(
808 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
809
810 // listen for user changes to update policy
811 final IntentFilter userFilter = new IntentFilter();
812 userFilter.addAction(ACTION_USER_ADDED);
813 userFilter.addAction(ACTION_USER_REMOVED);
814 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
815
816 // listen for stats update events
817 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
818 mContext.registerReceiver(
819 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
820
821 // listen for restrict background changes from notifications
822 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
823 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
824
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700825 // Listen for snooze from notifications
826 mContext.registerReceiver(mSnoozeReceiver,
827 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
828 mContext.registerReceiver(mSnoozeReceiver,
829 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700830
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600831 // listen for configured wifi networks to be loaded
832 final IntentFilter wifiFilter =
833 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
834 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700835
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700836 // listen for carrier config changes to update data cycle information
837 final IntentFilter carrierConfigFilter = new IntentFilter(
838 ACTION_CARRIER_CONFIG_CHANGED);
839 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
840
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600841 // listen for meteredness changes
842 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
843 new NetworkRequest.Builder().build(), mNetworkCallback);
844
Felipe Leme873a83a2016-09-07 11:34:10 -0700845 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800846 // tell systemReady() that the service has been initialized
847 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700848 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800849 // Restore the default priority after init is done
850 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700851 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700852 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700853 }
854
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800855 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
856 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
857 mHandler.post(() -> initService(initCompleteSignal));
858 return initCompleteSignal;
859 }
860
861 public void systemReady(CountDownLatch initCompleteSignal) {
862 // wait for initService to complete
863 try {
864 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
865 throw new IllegalStateException("Service " + TAG +" init timeout");
866 }
867 } catch (InterruptedException e) {
868 Thread.currentThread().interrupt();
869 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
870 }
Jeff Sharkey050151e2018-04-13 14:28:30 -0600871 mSystemReallyReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800872 }
873
Sudheer Shankac9d94072017-02-22 22:13:55 +0000874 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700875 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700876 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
877 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700878 }
879
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700880 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700881 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700882 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700883
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700884 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700885 }
886
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700887 @Override public void onUidIdle(int uid, boolean disabled) {
888 }
889
890 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700891 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700892 };
893
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700894 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700895 @Override
896 public void onReceive(Context context, Intent intent) {
897 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700898 synchronized (mUidRulesFirstLock) {
899 updatePowerSaveWhitelistUL();
900 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700901 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700902 }
903 }
904 };
905
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700906 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700907 @Override
908 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700909 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700910
911 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700912 final int uid = intent.getIntExtra(EXTRA_UID, -1);
913 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700914
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700915 if (ACTION_PACKAGE_ADDED.equals(action)) {
916 // update rules for UID, since it might be subject to
917 // global background data policy
918 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700919 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700920 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700921 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700922 }
923 }
924 };
925
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700926 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700927 @Override
928 public void onReceive(Context context, Intent intent) {
929 // on background handler thread, and UID_REMOVED is protected
930
931 final int uid = intent.getIntExtra(EXTRA_UID, -1);
932 if (uid == -1) return;
933
934 // remove any policy and update rules to clean up
935 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700936 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700937 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700938 synchronized (mNetworkPoliciesSecondLock) {
939 writePolicyAL();
940 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700941 }
942 }
943 };
944
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700945 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700946 @Override
947 public void onReceive(Context context, Intent intent) {
948 // on background handler thread, and USER_ADDED and USER_REMOVED
949 // broadcasts are protected
950
951 final String action = intent.getAction();
952 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
953 if (userId == -1) return;
954
Amith Yamasani15e472352015-04-24 19:06:07 -0700955 switch (action) {
956 case ACTION_USER_REMOVED:
957 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700958 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800959 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700960 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700961 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800962 // Removing outside removeUserStateUL since that can also be called when
963 // user resets app preferences.
964 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700965 if (action == ACTION_USER_ADDED) {
966 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700967 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700968 }
969 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700970 synchronized (mNetworkPoliciesSecondLock) {
971 updateRulesForGlobalChangeAL(true);
972 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700973 }
974 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700975 }
976 }
977 };
978
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700979 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700980 * Receiver that watches for {@link INetworkStatsService} updates, which we
981 * use to check against {@link NetworkPolicy#warningBytes}.
982 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700983 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700984 @Override
985 public void onReceive(Context context, Intent intent) {
986 // on background handler thread, and verified
987 // READ_NETWORK_USAGE_HISTORY permission above.
988
Felipe Lemef0823852016-06-08 13:43:08 -0700989 synchronized (mNetworkPoliciesSecondLock) {
990 updateNetworkEnabledNL();
991 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700992 }
993 }
994 };
995
996 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700997 * Receiver that watches for {@link Notification} control of
998 * {@link #mRestrictBackground}.
999 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001000 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001001 @Override
1002 public void onReceive(Context context, Intent intent) {
1003 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1004 // permission above.
1005
1006 setRestrictBackground(false);
1007 }
1008 };
1009
1010 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001011 * Receiver that watches for {@link Notification} control of
1012 * {@link NetworkPolicy#lastWarningSnooze}.
1013 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001014 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001015 @Override
1016 public void onReceive(Context context, Intent intent) {
1017 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1018 // permission above.
1019
1020 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001021 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1022 performSnooze(template, TYPE_WARNING);
1023 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1024 performSnooze(template, TYPE_RAPID);
1025 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001026 }
1027 };
1028
1029 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001030 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001031 * we can perform upgrade logic. After initial upgrade logic, it updates
1032 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001033 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001034 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001035 @Override
1036 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001037 synchronized (mUidRulesFirstLock) {
1038 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001039 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001040 }
1041 }
1042 // Only need to perform upgrade logic once
1043 mContext.unregisterReceiver(this);
1044 }
1045 };
1046
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001047 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1048 Network network) {
1049 final boolean lastValue = lastValues.get(network.netId, false);
1050 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1051 if (changed) {
1052 lastValues.put(network.netId, newValue);
1053 }
1054 return changed;
1055 }
1056
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001057 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1058 @Override
1059 public void onCapabilitiesChanged(Network network,
1060 NetworkCapabilities networkCapabilities) {
1061 if (network == null || networkCapabilities == null) return;
1062
1063 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001064 final boolean newMetered = !networkCapabilities
1065 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001066 final boolean meteredChanged = updateCapabilityChange(
1067 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001068
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001069 final boolean newRoaming = !networkCapabilities
1070 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1071 final boolean roamingChanged = updateCapabilityChange(
1072 mNetworkRoaming, newRoaming, network);
1073
1074 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001075 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001076 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001077 }
1078 }
1079 }
1080 };
1081
1082 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001083 * Observer that watches for {@link INetworkManagementService} alerts.
1084 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001085 final private INetworkManagementEventObserver mAlertObserver
1086 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001087 @Override
1088 public void limitReached(String limitName, String iface) {
1089 // only someone like NMS should be calling us
1090 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1091
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001092 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1093 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001094 }
1095 }
1096 };
1097
1098 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1100 * to show visible notifications as needed.
1101 */
Felipe Lemef0823852016-06-08 13:43:08 -07001102 void updateNotificationsNL() {
1103 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001104 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001105
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001107 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001108 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001109
1110 // TODO: when switching to kernel notifications, compute next future
1111 // cycle boundary to recompute notifications.
1112
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001113 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001114 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001115 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1116 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001117 final int subId = findRelevantSubId(policy.template);
1118
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001120 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001121 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122
Jeff Sharkey53313d72017-07-13 16:47:32 -06001123 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1124 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001125 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1126 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1127 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001128
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001129 // Carrier might want to manage notifications themselves
1130 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1131 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1132 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1133 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1134 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1135 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1136 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1137
1138 // Notify when data usage is over warning
1139 if (notifyWarning) {
1140 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1141 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1142 if (!snoozedThisCycle) {
1143 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1144 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001146 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001148 // Notify when data usage is over limit
1149 if (notifyLimit) {
1150 if (policy.isOverLimit(totalBytes)) {
1151 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1152 if (snoozedThisCycle) {
1153 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1154 } else {
1155 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1156 notifyOverLimitNL(policy.template);
1157 }
1158 } else {
1159 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 }
1161 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001162
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001163 // Warn if average usage over last 4 days is on track to blow pretty
1164 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001165 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001166 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001167 final long recentStart = now - recentDuration;
1168 final long recentEnd = now;
1169 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001170
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001171 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001172 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001173 final long alertBytes = (policy.limitBytes * 3) / 2;
1174
1175 if (LOGD) {
1176 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1177 + projectedBytes + " alert " + alertBytes);
1178 }
1179
1180 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1181 - DateUtils.DAY_IN_MILLIS;
1182 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001183 enqueueNotification(policy, TYPE_RAPID, 0,
1184 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001185 }
1186 }
1187 }
1188
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001190 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001191 final NotificationId notificationId = beforeNotifs.valueAt(i);
1192 if (!mActiveNotifs.contains(notificationId)) {
1193 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001194 }
1195 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001196
1197 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 }
1199
1200 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001201 * Attempt to find a specific app to blame for rapid data usage during the
1202 * given time period.
1203 */
1204 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1205 long start, long end) {
1206 long totalBytes = 0;
1207 long maxBytes = 0;
1208 int maxUid = 0;
1209
1210 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1211 NetworkStats.Entry entry = null;
1212 for (int i = 0; i < stats.size(); i++) {
1213 entry = stats.getValues(i, entry);
1214 final long bytes = entry.rxBytes + entry.txBytes;
1215 totalBytes += bytes;
1216 if (bytes > maxBytes) {
1217 maxBytes = bytes;
1218 maxUid = entry.uid;
1219 }
1220 }
1221
1222 // Only point blame if the majority of usage was done by a single app.
1223 // TODO: support shared UIDs
1224 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1225 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001226 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001227 try {
1228 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1229 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1230 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1231 } catch (NameNotFoundException ignored) {
1232 }
1233 }
1234 }
1235
1236 return null;
1237 }
1238
1239 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001241 * current device state, such as when
1242 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1243 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001244 *
1245 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1246 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001247 */
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001248 private int findRelevantSubId(NetworkTemplate template) {
1249 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1250 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001251
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001252 // Mobile template is relevant when any active subscriber matches
1253 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
1254 for (int subId : subIds) {
1255 final String subscriberId = tele.getSubscriberId(subId);
1256 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1257 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1258 true);
1259 if (template.matches(probeIdent)) {
1260 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001261 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001262 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001263 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001264 }
1265
1266 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001267 * Notify that given {@link NetworkTemplate} is over
1268 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1269 */
Felipe Lemef0823852016-06-08 13:43:08 -07001270 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001271 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001272 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001273 mOverLimitNotified.add(template);
1274 }
1275 }
1276
Felipe Lemef0823852016-06-08 13:43:08 -07001277 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001278 mOverLimitNotified.remove(template);
1279 }
1280
1281 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001282 * Show notification for combined {@link NetworkPolicy} and specific type,
1283 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1284 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001285 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1286 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001287 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001288 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001289 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001290 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001291 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001292 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001293 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001294
1295 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001296 final CharSequence title;
1297 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001298 switch (type) {
1299 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001300 title = res.getText(R.string.data_usage_warning_title);
1301 body = res.getString(R.string.data_usage_warning_body,
1302 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001303
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001304 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001305
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001306 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1307 builder.setDeleteIntent(PendingIntent.getBroadcast(
1308 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1309
Wei Liu546cb772016-07-21 16:19:01 -07001310 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001311 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001312 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1313
Jeff Sharkey497e4432011-06-14 17:27:29 -07001314 break;
1315 }
1316 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001317 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001318 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001319 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001320 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001321 case MATCH_WIFI:
1322 title = res.getText(R.string.data_usage_wifi_limit_title);
1323 break;
1324 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001325 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001326 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001327 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001328
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001329 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001330 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001331
Wei Liu546cb772016-07-21 16:19:01 -07001332 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001333 builder.setContentIntent(PendingIntent.getActivity(
1334 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1335 break;
1336 }
1337 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001338 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001339 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001340 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1341 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001342 case MATCH_WIFI:
1343 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1344 break;
1345 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001346 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001347 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001348 final long overBytes = totalBytes - policy.limitBytes;
1349 body = res.getString(R.string.data_usage_limit_snoozed_body,
1350 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001351
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001352 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001353 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001354 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001355
Wei Liu546cb772016-07-21 16:19:01 -07001356 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001357 builder.setContentIntent(PendingIntent.getActivity(
1358 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001359 break;
1360 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001361 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001362 title = res.getText(R.string.data_usage_rapid_title);
1363 if (rapidBlame != null) {
1364 body = res.getString(R.string.data_usage_rapid_app_body,
1365 rapidBlame.loadLabel(mContext.getPackageManager()));
1366 } else {
1367 body = res.getString(R.string.data_usage_rapid_body);
1368 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001369
Jeff Sharkey2e471452018-01-19 18:02:47 +09001370 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001371
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001372 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1373 builder.setDeleteIntent(PendingIntent.getBroadcast(
1374 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1375
1376 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001377 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001378 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001379 break;
1380 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001381 default: {
1382 return;
1383 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001384 }
1385
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001386 builder.setTicker(title);
1387 builder.setContentTitle(title);
1388 builder.setContentText(body);
1389 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001390
1391 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1392 notificationId.getId(), builder.build(), UserHandle.ALL);
1393 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001394 }
1395
Chris Wren193ae6b2017-03-31 15:17:11 -04001396 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001397 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1398 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001399 }
1400
1401 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001402 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001403 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001404 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001405 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001406 @Override
1407 public void onReceive(Context context, Intent intent) {
1408 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1409 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001410
Jeff Sharkey050151e2018-04-13 14:28:30 -06001411 if (!mSystemReallyReady) return;
Hugo Benichi446c9c92017-04-10 09:41:10 +09001412 synchronized (mUidRulesFirstLock) {
1413 synchronized (mNetworkPoliciesSecondLock) {
1414 ensureActiveMobilePolicyAL();
1415 normalizePoliciesNL();
1416 updateNetworkEnabledNL();
1417 updateNetworkRulesNL();
1418 updateNotificationsNL();
1419 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001420 }
1421 }
1422 };
1423
Jeff Sharkey2e471452018-01-19 18:02:47 +09001424 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001425 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001426 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001427 final CountDownLatch latch = new CountDownLatch(1);
1428 mHandler.post(() -> {
1429 latch.countDown();
1430 });
1431 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001432 }
1433
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001435 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1436 * if necessary.
1437 *
1438 * @param subId that has its associated NetworkPolicy updated if necessary
1439 * @return if any policies were updated
1440 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001441 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1442 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001443
1444 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001445 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1446 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001447
1448 // find and update the mobile NetworkPolicy for this subscriber id
1449 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001450 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001451 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1452 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1453 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001454 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1455 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001456 }
1457 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001458 return policyUpdated;
1459 }
1460
1461 /**
1462 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1463 *
1464 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1465 * to do so, it returns the fallback value.
1466 *
1467 * @param config The CarrierConfig to read the value from.
1468 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1469 * @return cycleDay to use in the mobile NetworkPolicy.
1470 */
1471 @VisibleForTesting
1472 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1473 int fallbackCycleDay) {
1474 if (config == null) {
1475 return fallbackCycleDay;
1476 }
1477 int cycleDay =
1478 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1479 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1480 return fallbackCycleDay;
1481 }
1482 // validate cycleDay value
1483 final Calendar cal = Calendar.getInstance();
1484 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1485 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1486 Slog.e(TAG, "Invalid date in "
1487 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1488 return fallbackCycleDay;
1489 }
1490 return cycleDay;
1491 }
1492
1493 /**
1494 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1495 *
1496 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1497 * to do so, it returns the fallback value.
1498 *
1499 * @param config The CarrierConfig to read the value from.
1500 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1501 * @return warningBytes to use in the mobile NetworkPolicy.
1502 */
1503 @VisibleForTesting
1504 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1505 long fallbackWarningBytes) {
1506 if (config == null) {
1507 return fallbackWarningBytes;
1508 }
1509 long warningBytes =
1510 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1511
1512 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1513 return WARNING_DISABLED;
1514 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1515 return getPlatformDefaultWarningBytes();
1516 } else if (warningBytes < 0) {
1517 Slog.e(TAG, "Invalid value in "
1518 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1519 + "non-negative value but got: " + warningBytes);
1520 return fallbackWarningBytes;
1521 }
1522
1523 return warningBytes;
1524 }
1525
1526 /**
1527 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1528 *
1529 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1530 * to do so, it returns the fallback value.
1531 *
1532 * @param config The CarrierConfig to read the value from.
1533 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1534 * @return limitBytes to use in the mobile NetworkPolicy.
1535 */
1536 @VisibleForTesting
1537 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1538 long fallbackLimitBytes) {
1539 if (config == null) {
1540 return fallbackLimitBytes;
1541 }
1542 long limitBytes =
1543 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1544
1545 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1546 return LIMIT_DISABLED;
1547 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1548 return getPlatformDefaultLimitBytes();
1549 } else if (limitBytes < 0) {
1550 Slog.e(TAG, "Invalid value in "
1551 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1552 + "non-negative value but got: " + limitBytes);
1553 return fallbackLimitBytes;
1554 }
1555 return limitBytes;
1556 }
1557
1558 /**
1559 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1560 */
1561 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1562 @Override
1563 public void onReceive(Context context, Intent intent) {
1564 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1565 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1566
1567 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1568 return;
1569 }
1570 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001571 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001572 final String subscriberId = tele.getSubscriberId(subId);
1573
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001574 synchronized (mUidRulesFirstLock) {
1575 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001576 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001577 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001578 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001579 if (!updated) return;
1580 // update network and notification rules, as the data cycle changed and it's
1581 // possible that we should be triggering warnings/limits now
1582 handleNetworkPoliciesUpdateAL(true);
1583 }
1584 }
1585 }
1586 };
1587
1588 /**
1589 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1590 * one has been updated.
1591 *
1592 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1593 * update.
1594 */
1595 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1596 if (shouldNormalizePolicies) {
1597 normalizePoliciesNL();
1598 }
1599 updateNetworkEnabledNL();
1600 updateNetworkRulesNL();
1601 updateNotificationsNL();
1602 writePolicyAL();
1603 }
1604
1605 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001606 * Proactively control network data connections when they exceed
1607 * {@link NetworkPolicy#limitBytes}.
1608 */
Felipe Lemef0823852016-06-08 13:43:08 -07001609 void updateNetworkEnabledNL() {
1610 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001611 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001612
1613 // TODO: reset any policy-disabled networks when any policy is removed
1614 // completely, which is currently rare case.
1615
Makoto Onuki49392d32018-04-11 13:51:02 -07001616 final long startTime = mStatLogger.getTime();
1617
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001618 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1619 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001620 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001621 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001622 setNetworkTemplateEnabled(policy.template, true);
1623 continue;
1624 }
1625
Jeff Sharkey53313d72017-07-13 16:47:32 -06001626 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1627 .cycleIterator(policy).next();
1628 final long start = cycle.first.toInstant().toEpochMilli();
1629 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001630 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001631
1632 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001633 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1634 && policy.lastLimitSnooze < start;
1635 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001636
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001637 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001638 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001639
1640 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001641 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001642 }
1643
1644 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001645 * Proactively disable networks that match the given
1646 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001647 */
1648 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001649 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1650 // held. Call it via the handler.
1651 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1652 .sendToTarget();
1653 }
1654
1655 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001656 // TODO: reach into ConnectivityManager to proactively disable bringing
1657 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001658
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001659 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001660 // If mobile data usage hits the limit or if the user resumes the data, we need to
1661 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001662 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1663 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001664
Jeff Sharkey2e471452018-01-19 18:02:47 +09001665 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001666 for (int subId : subIds) {
1667 final String subscriberId = tm.getSubscriberId(subId);
1668 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001669 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1670 true);
Jack Yu8781b682016-07-08 14:28:51 -07001671 // Template is matched when subscriber id matches.
1672 if (template.matches(probeIdent)) {
1673 tm.setPolicyDataEnabled(enabled, subId);
1674 }
1675 }
1676 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001677 }
1678
1679 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001680 * Collect all ifaces from a {@link NetworkState} into the given set.
1681 */
1682 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1683 final String baseIface = state.linkProperties.getInterfaceName();
1684 if (baseIface != null) {
1685 ifaces.add(baseIface);
1686 }
1687 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1688 final String stackedIface = stackedLink.getInterfaceName();
1689 if (stackedIface != null) {
1690 ifaces.add(stackedIface);
1691 }
1692 }
1693 }
1694
1695 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001696 * Examine all connected {@link NetworkState}, looking for
1697 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1698 * remaining quota based on usage cycle and historical stats.
1699 */
Felipe Lemef0823852016-06-08 13:43:08 -07001700 void updateNetworkRulesNL() {
1701 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001702 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001703
1704 final NetworkState[] states;
1705 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001706 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001707 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001708 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001709 return;
1710 }
1711
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001712 // First, generate identities of all connected networks so we can
1713 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001714 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001715 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001717 if (state.network != null) {
1718 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1719 }
Wei Liub8eaf452016-01-25 10:32:27 -08001720 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001721 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1722 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001723 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001724 }
1725 }
1726
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001727 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001728 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001729
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001730 // For every well-defined policy, compute remaining data based on
1731 // current cycle and historical stats, and push to kernel.
1732 final ArraySet<String> matchingIfaces = new ArraySet<>();
1733 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1734 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1735
1736 // Collect all ifaces that match this policy
1737 matchingIfaces.clear();
1738 for (int j = identified.size() - 1; j >= 0; j--) {
1739 if (policy.template.matches(identified.valueAt(j))) {
1740 collectIfaces(matchingIfaces, identified.keyAt(j));
1741 }
1742 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001743
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001744 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001745 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001746 }
1747
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001748 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001749 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001750 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001751 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001752 if (hasLimit && policy.hasCycle()) {
1753 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1754 .cycleIterator(policy).next();
1755 final long start = cycle.first.toInstant().toEpochMilli();
1756 final long end = cycle.second.toInstant().toEpochMilli();
1757 final long totalBytes = getTotalBytes(policy.template, start, end);
1758
1759 if (policy.lastLimitSnooze >= start) {
1760 // snoozing past quota, but we still need to restrict apps,
1761 // so push really high quota.
1762 quotaBytes = Long.MAX_VALUE;
1763 } else {
1764 // remaining "quota" bytes are based on total usage in
1765 // current cycle. kernel doesn't like 0-byte rules, so we
1766 // set 1-byte quota and disable the radio later.
1767 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1768 }
1769 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001770 // metered network, but no policy limit; we still need to
1771 // restrict apps, so push really high quota.
1772 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001773 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001774
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001775 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001776 // TODO: switch to shared quota once NMS supports
1777 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001778 }
1779
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001780 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1781 final String iface = matchingIfaces.valueAt(j);
1782 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001783 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001784 }
1785 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001786
1787 // keep track of lowest warning or limit of active policies
1788 if (hasWarning && policy.warningBytes < lowestRule) {
1789 lowestRule = policy.warningBytes;
1790 }
1791 if (hasLimit && policy.limitBytes < lowestRule) {
1792 lowestRule = policy.limitBytes;
1793 }
1794 }
1795
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001796 // One final pass to catch any metered ifaces that don't have explicitly
1797 // defined policies; typically Wi-Fi networks.
1798 for (NetworkState state : states) {
1799 if (state.networkInfo != null && state.networkInfo.isConnected()
1800 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1801 matchingIfaces.clear();
1802 collectIfaces(matchingIfaces, state);
1803 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1804 final String iface = matchingIfaces.valueAt(j);
1805 if (!newMeteredIfaces.contains(iface)) {
1806 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1807 newMeteredIfaces.add(iface);
1808 }
1809 }
1810 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001811 }
1812
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001813 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001814 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1815 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001816 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001817 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001818 }
1819 }
1820 mMeteredIfaces = newMeteredIfaces;
1821
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001822 final ContentResolver cr = mContext.getContentResolver();
1823 final boolean quotaEnabled = Settings.Global.getInt(cr,
1824 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1825 final long quotaUnlimited = Settings.Global.getLong(cr,
1826 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1827 final float quotaLimited = Settings.Global.getFloat(cr,
1828 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1829
Jeff Sharkey9252b342018-01-19 07:58:35 +09001830 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001831 mSubscriptionOpportunisticQuota.clear();
1832 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001833 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001834 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001835 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001836 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001837 if (plan == null) continue;
1838
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001839 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001840 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001841 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1842 // Clamp to 0 when roaming
1843 quotaBytes = 0;
1844 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001845 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001846 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001847 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001848 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001849 } else {
1850 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001851 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1852 final long start = cycle.getLower().toInstant().toEpochMilli();
1853 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001854 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001855 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001856 .truncatedTo(ChronoUnit.DAYS)
1857 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001858 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001859 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1860 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001861 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001862 // Number of remaining days including current day
1863 final long remainingDays =
1864 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001865
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001866 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001867 }
1868
1869 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1870 }
1871
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001872 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001873 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001874
1875 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06001876
1877 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001878 }
1879
1880 /**
1881 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1882 * have at least a default mobile policy defined.
1883 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001884 private void ensureActiveMobilePolicyAL() {
1885 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001886 if (mSuppressDefaultPolicy) return;
1887
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001888 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1889 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001890
Jeff Sharkey2e471452018-01-19 18:02:47 +09001891 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001892 for (int subId : subIds) {
1893 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001894 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001895 }
1896 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001897
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001898 /**
1899 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1900 * have at least a default mobile policy defined.
1901 *
1902 * @param subId to build a default policy for
1903 * @param subscriberId that we check for an existing policy
1904 * @return true if a mobile network policy was added, or false one already existed.
1905 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001906 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001907 // Poke around to see if we already have a policy
1908 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001909 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001910 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1911 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1912 if (template.matches(probeIdent)) {
1913 if (LOGD) {
1914 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1915 + NetworkIdentity.scrubSubscriberId(subscriberId));
1916 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001917 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001918 }
1919 }
1920
Jeff Sharkey32566012014-12-02 18:30:14 -08001921 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1922 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001923 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001924 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001925 return true;
1926 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001927
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001928 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001929 final int dataWarningConfig = mContext.getResources().getInteger(
1930 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001931 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001932 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001933 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001934 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001935 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001936 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001937
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001938 private long getPlatformDefaultLimitBytes() {
1939 return LIMIT_DISABLED;
1940 }
1941
1942 @VisibleForTesting
1943 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001944 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001945 final RecurrenceRule cycleRule = NetworkPolicy
1946 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001947 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001948 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1949 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1950 synchronized (mUidRulesFirstLock) {
1951 synchronized (mNetworkPoliciesSecondLock) {
1952 updateDefaultMobilePolicyAL(subId, policy);
1953 }
1954 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001955 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001956 }
1957
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001958 /**
1959 * Update the given {@link NetworkPolicy} based on any carrier-provided
1960 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1961 * Leaves policy untouched if the user has modified it.
1962 *
1963 * @return if the policy was modified
1964 */
1965 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1966 if (!policy.inferred) {
1967 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1968 return false;
1969 }
1970
1971 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1972 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1973 policy.lastLimitSnooze, policy.metered, policy.inferred);
1974
1975 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1976 if (!ArrayUtils.isEmpty(plans)) {
1977 final SubscriptionPlan plan = plans[0];
1978 policy.cycleRule = plan.getCycleRule();
1979 final long planLimitBytes = plan.getDataLimitBytes();
1980 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1981 policy.warningBytes = getPlatformDefaultWarningBytes();
1982 policy.limitBytes = getPlatformDefaultLimitBytes();
1983 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1984 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1985 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1986 } else {
1987 policy.warningBytes = (planLimitBytes * 9) / 10;
1988 switch (plan.getDataLimitBehavior()) {
1989 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1990 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1991 policy.limitBytes = planLimitBytes;
1992 break;
1993 default:
1994 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1995 break;
1996 }
1997 }
1998 } else {
1999 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2000 final int currentCycleDay;
2001 if (policy.cycleRule.isMonthly()) {
2002 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2003 } else {
2004 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2005 }
2006 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2007 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2008 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2009 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2010 }
2011
2012 if (policy.equals(original)) {
2013 return false;
2014 } else {
2015 Slog.d(TAG, "Updated " + original + " to " + policy);
2016 return true;
2017 }
2018 }
2019
Felipe Lemef0823852016-06-08 13:43:08 -07002020 private void readPolicyAL() {
2021 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002022
2023 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002024 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002025 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002026 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002027 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002028
2029 FileInputStream fis = null;
2030 try {
2031 fis = mPolicyFile.openRead();
2032 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002033 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002034
Felipe Leme46b451f2016-08-19 08:46:17 -07002035 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2036 // to skip UIDs that were explicitly blacklisted.
2037 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2038
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002039 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002040 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002041 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002042 while ((type = in.next()) != END_DOCUMENT) {
2043 final String tag = in.getName();
2044 if (type == START_TAG) {
2045 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002046 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002047 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002048 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2049 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002050 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2051 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2052 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002053 final String networkId;
2054 if (version >= VERSION_ADDED_NETWORK_ID) {
2055 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2056 } else {
2057 networkId = null;
2058 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002059 final RecurrenceRule cycleRule;
2060 if (version >= VERSION_ADDED_CYCLE) {
2061 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2062 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2063 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2064 cycleRule = new RecurrenceRule(
2065 RecurrenceRule.convertZonedDateTime(start),
2066 RecurrenceRule.convertZonedDateTime(end),
2067 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002068 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002069 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2070 final String cycleTimezone;
2071 if (version >= VERSION_ADDED_TIMEZONE) {
2072 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2073 } else {
2074 cycleTimezone = "UTC";
2075 }
2076 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002077 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002078 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2079 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002080 final long lastLimitSnooze;
2081 if (version >= VERSION_SPLIT_SNOOZE) {
2082 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2083 } else if (version >= VERSION_ADDED_SNOOZE) {
2084 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002085 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002086 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002087 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002088 final boolean metered;
2089 if (version >= VERSION_ADDED_METERED) {
2090 metered = readBooleanAttribute(in, ATTR_METERED);
2091 } else {
2092 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002093 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002094 metered = true;
2095 break;
2096 default:
2097 metered = false;
2098 }
2099 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002100 final long lastWarningSnooze;
2101 if (version >= VERSION_SPLIT_SNOOZE) {
2102 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2103 } else {
2104 lastWarningSnooze = SNOOZE_NEVER;
2105 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002106 final boolean inferred;
2107 if (version >= VERSION_ADDED_INFERRED) {
2108 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2109 } else {
2110 inferred = false;
2111 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002112
Jeff Sharkey32566012014-12-02 18:30:14 -08002113 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2114 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002115 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002116 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2117 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002118 lastLimitSnooze, metered, inferred));
2119 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002120
2121 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2122 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2123 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2124 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2125 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2126 RecurrenceRule.convertZonedDateTime(start),
2127 RecurrenceRule.convertZonedDateTime(end),
2128 RecurrenceRule.convertPeriod(period));
2129 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2130 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2131
2132 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2133 SubscriptionPlan.BYTES_UNKNOWN);
2134 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2135 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2136 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2137 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2138 builder.setDataLimit(limitBytes, limitBehavior);
2139 }
2140
2141 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2142 SubscriptionPlan.BYTES_UNKNOWN);
2143 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2144 SubscriptionPlan.TIME_UNKNOWN);
2145 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2146 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2147 builder.setDataUsage(usageBytes, usageTime);
2148 }
2149
2150 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2151 final SubscriptionPlan plan = builder.build();
2152 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2153 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2154
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002155 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2156 mSubscriptionPlansOwner.put(subId, ownerPackage);
2157
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002158 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159 final int uid = readIntAttribute(in, ATTR_UID);
2160 final int policy = readIntAttribute(in, ATTR_POLICY);
2161
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002162 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002163 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002164 } else {
2165 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2166 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002167 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002168 final int appId = readIntAttribute(in, ATTR_APP_ID);
2169 final int policy = readIntAttribute(in, ATTR_POLICY);
2170
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002171 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002172 // app policy is deprecated so this is only used in pre system user split.
2173 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002174 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002175 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002176 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002177 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002178 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002179 } else if (TAG_WHITELIST.equals(tag)) {
2180 insideWhitelist = true;
2181 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2182 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002183 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002184 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2185 final int uid = readIntAttribute(in, ATTR_UID);
2186 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002188 } else if (type == END_TAG) {
2189 if (TAG_WHITELIST.equals(tag)) {
2190 insideWhitelist = false;
2191 }
2192
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002193 }
2194 }
2195
Felipe Leme46b451f2016-08-19 08:46:17 -07002196 final int size = whitelistedRestrictBackground.size();
2197 for (int i = 0; i < size; i++) {
2198 final int uid = whitelistedRestrictBackground.keyAt(i);
2199 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2200 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2201 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2202 + " because its policy is " + uidPoliciesToString(policy));
2203 continue;
2204 }
2205 if (UserHandle.isApp(uid)) {
2206 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2207 if (LOGV)
2208 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2209 setUidPolicyUncheckedUL(uid, newPolicy, false);
2210 } else {
2211 Slog.w(TAG, "unable to update policy on UID " + uid);
2212 }
2213 }
2214
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002215 } catch (FileNotFoundException e) {
2216 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002217 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002218 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002219 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002220 } finally {
2221 IoUtils.closeQuietly(fis);
2222 }
2223 }
2224
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002225 /**
2226 * Upgrade legacy background data flags, notifying listeners of one last
2227 * change to always-true.
2228 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002229 private void upgradeDefaultBackgroundDataUL() {
2230 // This method is only called when we're unable to find the network policy flag, which
2231 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002232
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002233 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002234 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002235 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2236
2237 // NOTE: We used to read the legacy setting here :
2238 //
2239 // final int legacyFlagValue = Settings.Secure.getInt(
2240 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2241 //
2242 // This is no longer necessary because we will never upgrade directly from Gingerbread
2243 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2244 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002245 }
2246
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002247 /**
2248 * Perform upgrade step of moving any user-defined meterness overrides over
2249 * into {@link WifiConfiguration}.
2250 */
2251 private void upgradeWifiMeteredOverrideAL() {
2252 boolean modified = false;
2253 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2254 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2255 for (int i = 0; i < mNetworkPolicy.size(); ) {
2256 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2257 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2258 && !policy.inferred) {
2259 mNetworkPolicy.removeAt(i);
2260 modified = true;
2261
2262 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2263 for (WifiConfiguration config : configs) {
2264 if (Objects.equals(resolveNetworkId(config), networkId)) {
2265 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2266 config.meteredOverride = policy.metered
2267 ? WifiConfiguration.METERED_OVERRIDE_METERED
2268 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2269 wm.updateNetwork(config);
2270 }
2271 }
2272 } else {
2273 i++;
2274 }
2275 }
2276 if (modified) {
2277 writePolicyAL();
2278 }
2279 }
2280
Felipe Lemef0823852016-06-08 13:43:08 -07002281 void writePolicyAL() {
2282 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002283
2284 FileOutputStream fos = null;
2285 try {
2286 fos = mPolicyFile.startWrite();
2287
2288 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002289 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002290 out.startDocument(null, true);
2291
2292 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002293 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002294 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002295
2296 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002297 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2298 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002299 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002300 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002301
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002302 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002303 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2304 final String subscriberId = template.getSubscriberId();
2305 if (subscriberId != null) {
2306 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002307 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002308 final String networkId = template.getNetworkId();
2309 if (networkId != null) {
2310 out.attribute(null, ATTR_NETWORK_ID, networkId);
2311 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002312 writeStringAttribute(out, ATTR_CYCLE_START,
2313 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2314 writeStringAttribute(out, ATTR_CYCLE_END,
2315 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2316 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2317 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002318 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2319 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002320 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2321 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002322 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002323 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002324 out.endTag(null, TAG_NETWORK_POLICY);
2325 }
2326
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002327 // write all known subscription plans
2328 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2329 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002330 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002331 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2332 if (ArrayUtils.isEmpty(plans)) continue;
2333
2334 for (SubscriptionPlan plan : plans) {
2335 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2336 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002337 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002338 final RecurrenceRule cycleRule = plan.getCycleRule();
2339 writeStringAttribute(out, ATTR_CYCLE_START,
2340 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2341 writeStringAttribute(out, ATTR_CYCLE_END,
2342 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2343 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2344 RecurrenceRule.convertPeriod(cycleRule.period));
2345 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2346 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2347 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2348 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2349 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2350 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2351 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2352 }
2353 }
2354
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002355 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002356 for (int i = 0; i < mUidPolicy.size(); i++) {
2357 final int uid = mUidPolicy.keyAt(i);
2358 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002359
Jeff Sharkey497e4432011-06-14 17:27:29 -07002360 // skip writing empty policies
2361 if (policy == POLICY_NONE) continue;
2362
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002363 out.startTag(null, TAG_UID_POLICY);
2364 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002366 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002367 }
2368
2369 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002370
2371 // write all whitelists
2372 out.startTag(null, TAG_WHITELIST);
2373
Felipe Lemea9505cc2016-02-26 10:28:41 -08002374 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002375 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002376 for (int i = 0; i < size; i++) {
2377 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2378 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2379 writeIntAttribute(out, ATTR_UID, uid);
2380 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2381 }
2382
Felipe Lemeb85a6372016-01-14 16:16:16 -08002383 out.endTag(null, TAG_WHITELIST);
2384
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002385 out.endDocument();
2386
2387 mPolicyFile.finishWrite(fos);
2388 } catch (IOException e) {
2389 if (fos != null) {
2390 mPolicyFile.failWrite(fos);
2391 }
2392 }
2393 }
2394
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002395 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002396 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002397 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002398
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002399 if (!UserHandle.isApp(uid)) {
2400 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002401 }
Felipe Lemef0823852016-06-08 13:43:08 -07002402 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002403 final long token = Binder.clearCallingIdentity();
2404 try {
2405 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2406 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002407 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002408 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002409 }
2410 } finally {
2411 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002412 }
2413 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002414 }
2415
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002416 @Override
2417 public void addUidPolicy(int uid, int policy) {
2418 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002419
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002420 if (!UserHandle.isApp(uid)) {
2421 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2422 }
2423
Felipe Lemef0823852016-06-08 13:43:08 -07002424 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002425 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2426 policy |= oldPolicy;
2427 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002428 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002429 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002430 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002431 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002432 }
2433
2434 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002435 public void removeUidPolicy(int uid, int policy) {
2436 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2437
2438 if (!UserHandle.isApp(uid)) {
2439 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2440 }
2441
Felipe Lemef0823852016-06-08 13:43:08 -07002442 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002443 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2444 policy = oldPolicy & ~policy;
2445 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002446 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002447 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002448 }
2449 }
2450 }
2451
Felipe Lemef0823852016-06-08 13:43:08 -07002452 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002453 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002454
Felipe Leme57e3d312016-08-23 14:42:52 -07002455 final boolean notifyApp;
2456 if (!isUidValidForWhitelistRules(uid)) {
2457 notifyApp = false;
2458 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002459 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2460 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2461 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2462 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002463 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2464 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002465 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2466 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2467 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2468 if (LOGD)
2469 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2470 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2471 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002472 notifyApp = wasBlocked != isBlocked;
2473 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002474 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2475 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002476 if (persist) {
2477 synchronized (mNetworkPoliciesSecondLock) {
2478 writePolicyAL();
2479 }
2480 }
Felipe Leme923845f2016-03-02 13:42:48 -08002481 }
2482
Felipe Lemef0823852016-06-08 13:43:08 -07002483 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002484 if (policy == POLICY_NONE) {
2485 mUidPolicy.delete(uid);
2486 } else {
2487 mUidPolicy.put(uid, policy);
2488 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002489
2490 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002491 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002492 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002493 synchronized (mNetworkPoliciesSecondLock) {
2494 writePolicyAL();
2495 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002496 }
2497 }
2498
2499 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002500 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002501 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2502
Felipe Lemef0823852016-06-08 13:43:08 -07002503 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002504 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002505 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002506 }
2507
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002508 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002509 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002510 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2511
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002512 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002513 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002514 for (int i = 0; i < mUidPolicy.size(); i++) {
2515 final int uid = mUidPolicy.keyAt(i);
2516 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002517 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2518 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002519 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002520 }
2521 }
2522 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002523 return uids;
2524 }
2525
2526 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002527 * Removes any persistable state associated with given {@link UserHandle}, persisting
2528 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002529 */
Felipe Lemef0823852016-06-08 13:43:08 -07002530 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002531
Sudheer Shanka352dc572017-09-22 17:09:38 -07002532 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002533 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002534
Felipe Lemea110eec2016-04-29 09:58:06 -07002535 // Remove entries from revoked default restricted background UID whitelist
2536 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2537 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2538 if (UserHandle.getUserId(uid) == userId) {
2539 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002540 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002541 }
2542 }
2543
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002544 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002545 int[] uids = new int[0];
2546 for (int i = 0; i < mUidPolicy.size(); i++) {
2547 final int uid = mUidPolicy.keyAt(i);
2548 if (UserHandle.getUserId(uid) == userId) {
2549 uids = appendInt(uids, uid);
2550 }
2551 }
2552
2553 if (uids.length > 0) {
2554 for (int uid : uids) {
2555 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002556 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002557 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002558 }
Felipe Lemef0823852016-06-08 13:43:08 -07002559 synchronized (mNetworkPoliciesSecondLock) {
2560 updateRulesForGlobalChangeAL(true);
2561 if (writePolicy && changed) {
2562 writePolicyAL();
2563 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002564 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002565 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002566 }
2567
2568 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002569 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002570 // TODO: create permission for observing network policy
2571 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002572 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002573 }
2574
2575 @Override
2576 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002577 // TODO: create permission for observing network policy
2578 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002579 mListeners.unregister(listener);
2580 }
2581
Jeff Sharkey1b861272011-05-22 00:34:52 -07002582 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002583 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2585
Felipe Leme6a05eee2016-02-19 14:43:51 -08002586 final long token = Binder.clearCallingIdentity();
2587 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002588 synchronized (mUidRulesFirstLock) {
2589 synchronized (mNetworkPoliciesSecondLock) {
2590 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002591 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002592 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002593 }
2594 } finally {
2595 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002596 }
2597 }
2598
Hugo Benichi446c9c92017-04-10 09:41:10 +09002599 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002600 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002601 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2602 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002603 }
2604
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002605 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002606 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002607 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002608 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002609 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2610 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2611 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002612 } catch (SecurityException e) {
2613 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002614
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002615 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2616 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2617 return new NetworkPolicy[0];
2618 }
Svet Ganov16a16892015-04-16 10:32:04 -07002619 }
2620
Felipe Lemef0823852016-06-08 13:43:08 -07002621 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002622 final int size = mNetworkPolicy.size();
2623 final NetworkPolicy[] policies = new NetworkPolicy[size];
2624 for (int i = 0; i < size; i++) {
2625 policies[i] = mNetworkPolicy.valueAt(i);
2626 }
2627 return policies;
2628 }
2629 }
2630
Felipe Lemef0823852016-06-08 13:43:08 -07002631 private void normalizePoliciesNL() {
2632 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002633 }
2634
Felipe Lemef0823852016-06-08 13:43:08 -07002635 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002636 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002637 final String[] merged = tele.getMergedSubscriberIds();
2638
2639 mNetworkPolicy.clear();
2640 for (NetworkPolicy policy : policies) {
2641 // When two normalized templates conflict, prefer the most
2642 // restrictive policy
2643 policy.template = NetworkTemplate.normalize(policy.template, merged);
2644 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2645 if (existing == null || existing.compareTo(policy) > 0) {
2646 if (existing != null) {
2647 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2648 }
2649 mNetworkPolicy.put(policy.template, policy);
2650 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002651 }
2652 }
2653
2654 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002655 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002656 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002657
2658 final long token = Binder.clearCallingIdentity();
2659 try {
2660 performSnooze(template, TYPE_LIMIT);
2661 } finally {
2662 Binder.restoreCallingIdentity(token);
2663 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002664 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002665
Dianne Hackborn497175b2014-07-01 12:56:08 -07002666 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002667 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002668 synchronized (mUidRulesFirstLock) {
2669 synchronized (mNetworkPoliciesSecondLock) {
2670 // find and snooze local policy that matches
2671 final NetworkPolicy policy = mNetworkPolicy.get(template);
2672 if (policy == null) {
2673 throw new IllegalArgumentException("unable to find policy for " + template);
2674 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002675
Felipe Lemef0823852016-06-08 13:43:08 -07002676 switch (type) {
2677 case TYPE_WARNING:
2678 policy.lastWarningSnooze = currentTime;
2679 break;
2680 case TYPE_LIMIT:
2681 policy.lastLimitSnooze = currentTime;
2682 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002683 case TYPE_RAPID:
2684 policy.lastRapidSnooze = currentTime;
2685 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002686 default:
2687 throw new IllegalArgumentException("unexpected type");
2688 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002689
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002690 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002691 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002692 }
2693 }
2694
2695 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002696 public void onTetheringChanged(String iface, boolean tethering) {
2697 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002698 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002699 if (mRestrictBackground && tethering) {
2700 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2701 setRestrictBackground(false);
2702 }
2703 }
2704 }
2705
2706 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002707 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002708 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002709 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002710 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2711 final long token = Binder.clearCallingIdentity();
2712 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002713 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002714 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002715 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002716 } finally {
2717 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002718 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002719 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002720 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002721 }
2722 }
2723
Felipe Lemef0823852016-06-08 13:43:08 -07002724 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002725 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002726 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002727 if (restrictBackground == mRestrictBackground) {
2728 // Ideally, UI should never allow this scenario...
2729 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002730 return;
2731 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002732 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2733 final boolean oldRestrictBackground = mRestrictBackground;
2734 mRestrictBackground = restrictBackground;
2735 // Must whitelist foreground apps before turning data saver mode on.
2736 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2737 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2738 updateRulesForRestrictBackgroundUL();
2739 try {
2740 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2741 Slog.e(TAG,
2742 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2743 mRestrictBackground = oldRestrictBackground;
2744 // TODO: if it knew the foreground apps (see TODO above), it could call
2745 // updateRulesForRestrictBackgroundUL() again to restore state.
2746 return;
2747 }
2748 } catch (RemoteException e) {
2749 // ignored; service lives in system_server
2750 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002751
Sudheer Shanka543339f2017-07-28 15:18:07 -07002752 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002753 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002754
2755 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2756 mRestrictBackgroundChangedInBsm = true;
2757 }
2758 synchronized (mNetworkPoliciesSecondLock) {
2759 updateNotificationsNL();
2760 writePolicyAL();
2761 }
2762 } finally {
2763 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002764 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002765 }
2766
2767 private void sendRestrictBackgroundChangedMsg() {
2768 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2769 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2770 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002771 }
2772
Felipe Lemeb85a6372016-01-14 16:16:16 -08002773 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002774 public int getRestrictBackgroundByCaller() {
2775 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2776 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002777
Felipe Lemef0823852016-06-08 13:43:08 -07002778 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002779 // Must clear identity because getUidPolicy() is restricted to system.
2780 final long token = Binder.clearCallingIdentity();
2781 final int policy;
2782 try {
2783 policy = getUidPolicy(uid);
2784 } finally {
2785 Binder.restoreCallingIdentity(token);
2786 }
2787 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2788 // App is blacklisted.
2789 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2790 }
Felipe Leme1b103232016-01-22 09:44:57 -08002791 if (!mRestrictBackground) {
2792 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2793 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002794 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002795 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2796 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2797 }
2798 }
2799
2800 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002801 public boolean getRestrictBackground() {
2802 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2803
Felipe Lemef0823852016-06-08 13:43:08 -07002804 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002805 return mRestrictBackground;
2806 }
2807 }
2808
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002809 @Override
2810 public void setDeviceIdleMode(boolean enabled) {
2811 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002812 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2813 try {
2814 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002815 if (mDeviceIdleMode == enabled) {
2816 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002817 }
Felipe Lemeea014392016-09-06 13:59:54 -07002818 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002819 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002820 if (mSystemReady) {
2821 // Device idle change means we need to rebuild rules for all
2822 // known apps, so do a global refresh.
2823 updateRulesForRestrictPowerUL();
2824 }
2825 }
2826 if (enabled) {
2827 EventLogTags.writeDeviceIdleOnPhase("net");
2828 } else {
2829 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002830 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002831 } finally {
2832 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002833 }
2834 }
2835
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002836 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002837 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2838 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002839 final long token = Binder.clearCallingIdentity();
2840 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002841 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2842 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2843 for (WifiConfiguration config : configs) {
2844 if (Objects.equals(resolveNetworkId(config), networkId)) {
2845 config.meteredOverride = meteredOverride;
2846 wm.updateNetwork(config);
2847 }
2848 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002849 } finally {
2850 Binder.restoreCallingIdentity(token);
2851 }
2852 }
2853
Jeff Sharkey46645002011-07-27 21:11:21 -07002854 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002855 @Deprecated
2856 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2857 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2858 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2859 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002860 }
2861
Jeff Sharkey53313d72017-07-13 16:47:32 -06002862 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2863 // Verify they're not lying about package name
2864 mAppOps.checkPackage(callingUid, callingPackage);
2865
Jeff Sharkey53313d72017-07-13 16:47:32 -06002866 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002867 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002868 final long token = Binder.clearCallingIdentity();
2869 try {
2870 si = mContext.getSystemService(SubscriptionManager.class)
2871 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002872 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002873 } finally {
2874 Binder.restoreCallingIdentity(token);
2875 }
2876
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002877 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002878 if (si != null) {
2879 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2880 return;
2881 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002882 }
2883
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002884 // Second check: has the CarrierService delegated access?
2885 if (config != null) {
2886 final String overridePackage = config
2887 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2888 if (!TextUtils.isEmpty(overridePackage)
2889 && Objects.equals(overridePackage, callingPackage)) {
2890 return;
2891 }
2892 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002893
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002894 // Third check: is caller the fallback/default CarrierService?
2895 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2896 if (!TextUtils.isEmpty(defaultPackage)
2897 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002898 return;
2899 }
2900
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002901 // Fourth check: is caller a testing app?
2902 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2903 if (!TextUtils.isEmpty(testPackage)
2904 && Objects.equals(testPackage, callingPackage)) {
2905 return;
2906 }
2907
2908 // Fifth check: is caller a legacy testing app?
2909 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2910 if (!TextUtils.isEmpty(legacyTestPackage)
2911 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002912 return;
2913 }
2914
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002915 // Final check: does the caller hold a permission?
2916 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002917 }
2918
2919 @Override
2920 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2921 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2922
Jeff Sharkey53313d72017-07-13 16:47:32 -06002923 final String fake = SystemProperties.get("fw.fake_plan");
2924 if (!TextUtils.isEmpty(fake)) {
2925 final List<SubscriptionPlan> plans = new ArrayList<>();
2926 if ("month_hard".equals(fake)) {
2927 plans.add(SubscriptionPlan.Builder
2928 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2929 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002930 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2931 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2932 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2933 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2934 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002935 plans.add(SubscriptionPlan.Builder
2936 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2937 .setTitle("G-Mobile Happy")
2938 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2939 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2940 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2941 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2942 .build());
2943 plans.add(SubscriptionPlan.Builder
2944 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2945 .setTitle("G-Mobile, Charged after limit")
2946 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2947 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2948 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2949 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2950 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002951 } else if ("month_soft".equals(fake)) {
2952 plans.add(SubscriptionPlan.Builder
2953 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2954 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2955 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2956 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002957 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2958 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2959 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2960 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2961 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002962 plans.add(SubscriptionPlan.Builder
2963 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2964 .setTitle("G-Mobile, Throttled after limit")
2965 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2966 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2967 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2968 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2969 .build());
2970 plans.add(SubscriptionPlan.Builder
2971 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2972 .setTitle("G-Mobile, No data connection after limit")
2973 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2974 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2975 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2976 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2977 .build());
2978
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002979 } else if ("month_over".equals(fake)) {
2980 plans.add(SubscriptionPlan.Builder
2981 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2982 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2983 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2984 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2985 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2986 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2987 .build());
2988 plans.add(SubscriptionPlan.Builder
2989 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2990 .setTitle("G-Mobile, Throttled after limit")
2991 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2992 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2993 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2994 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2995 .build());
2996 plans.add(SubscriptionPlan.Builder
2997 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2998 .setTitle("G-Mobile, No data connection after limit")
2999 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3000 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3001 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3002 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3003 .build());
3004
Jeff Sharkey53313d72017-07-13 16:47:32 -06003005 } else if ("month_none".equals(fake)) {
3006 plans.add(SubscriptionPlan.Builder
3007 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3008 .setTitle("G-Mobile")
3009 .build());
3010 } else if ("prepaid".equals(fake)) {
3011 plans.add(SubscriptionPlan.Builder
3012 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3013 ZonedDateTime.now().plusDays(10))
3014 .setTitle("G-Mobile")
3015 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3016 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3017 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3018 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3019 .build());
3020 } else if ("prepaid_crazy".equals(fake)) {
3021 plans.add(SubscriptionPlan.Builder
3022 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3023 ZonedDateTime.now().plusDays(10))
3024 .setTitle("G-Mobile Anytime")
3025 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3026 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3027 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3028 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3029 .build());
3030 plans.add(SubscriptionPlan.Builder
3031 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3032 ZonedDateTime.now().plusDays(20))
3033 .setTitle("G-Mobile Nickel Nights")
3034 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003035 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3036 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003037 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3038 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3039 .build());
3040 plans.add(SubscriptionPlan.Builder
3041 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3042 ZonedDateTime.now().plusDays(20))
3043 .setTitle("G-Mobile Bonus 3G")
3044 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003045 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003046 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3047 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3048 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3049 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003050 } else if ("unlimited".equals(fake)) {
3051 plans.add(SubscriptionPlan.Builder
3052 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3053 ZonedDateTime.now().plusDays(10))
3054 .setTitle("G-Mobile Awesome")
3055 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3056 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3057 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3058 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3059 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003060 }
3061 return plans.toArray(new SubscriptionPlan[plans.size()]);
3062 }
3063
Jeff Sharkey4635f102017-09-01 11:27:13 -06003064 synchronized (mNetworkPoliciesSecondLock) {
3065 // Only give out plan details to the package that defined them,
3066 // so that we don't risk leaking plans between apps. We always
3067 // let in core system components (like the Settings app).
3068 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3069 if (Objects.equals(ownerPackage, callingPackage)
3070 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3071 return mSubscriptionPlans.get(subId);
3072 } else {
3073 Log.w(TAG, "Not returning plans because caller " + callingPackage
3074 + " doesn't match owner " + ownerPackage);
3075 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003076 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003077 }
3078 }
3079
3080 @Override
3081 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3082 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3083
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003084 for (SubscriptionPlan plan : plans) {
3085 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003086 }
3087
3088 final long token = Binder.clearCallingIdentity();
3089 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003090 synchronized (mUidRulesFirstLock) {
3091 synchronized (mNetworkPoliciesSecondLock) {
3092 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003093 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003094
3095 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
3096 .getSubscriberId(subId);
3097 ensureActiveMobilePolicyAL(subId, subscriberId);
3098 maybeUpdateMobilePolicyCycleAL(subId);
3099 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003100 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003101 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003102
3103 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3104 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3105 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3106 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003107 } finally {
3108 Binder.restoreCallingIdentity(token);
3109 }
3110 }
3111
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003112 /**
3113 * Only visible for testing purposes. This doesn't give any access to
3114 * existing plans; it simply lets the debug package define new plans.
3115 */
3116 void setSubscriptionPlansOwner(int subId, String packageName) {
3117 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3118 }
3119
Jeff Sharkey53313d72017-07-13 16:47:32 -06003120 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003121 public String getSubscriptionPlansOwner(int subId) {
3122 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3123 throw new SecurityException();
3124 }
3125
3126 synchronized (mNetworkPoliciesSecondLock) {
3127 return mSubscriptionPlansOwner.get(subId);
3128 }
3129 }
3130
3131 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003132 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3133 long timeoutMillis, String callingPackage) {
3134 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3135
3136 // We can only override when carrier told us about plans
3137 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003138 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3139 if (plan == null
3140 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003141 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003142 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003143 }
3144 }
3145
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003146 // Only allow overrides when feature is enabled. However, we always
3147 // allow disabling of overrides for safety reasons.
3148 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3149 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3150 if (overrideEnabled || overrideValue == 0) {
3151 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3152 overrideMask, overrideValue, subId));
3153 if (timeoutMillis > 0) {
3154 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3155 overrideMask, 0, subId), timeoutMillis);
3156 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003157 }
3158 }
3159
3160 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003161 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003162 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003163
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003164 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3165
Dianne Hackborn497175b2014-07-01 12:56:08 -07003166 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003167 for (String arg : args) {
3168 argSet.add(arg);
3169 }
3170
Felipe Lemef0823852016-06-08 13:43:08 -07003171 synchronized (mUidRulesFirstLock) {
3172 synchronized (mNetworkPoliciesSecondLock) {
3173 if (argSet.contains("--unsnooze")) {
3174 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3175 mNetworkPolicy.valueAt(i).clearSnooze();
3176 }
3177
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003178 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003179
3180 fout.println("Cleared snooze timestamps");
3181 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003182 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003183
Felipe Lemef0823852016-06-08 13:43:08 -07003184 fout.print("System ready: "); fout.println(mSystemReady);
3185 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3186 fout.print("Restrict power: "); fout.println(mRestrictPower);
3187 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003188 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3189
3190 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003191 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003192 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003193 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3194 fout.println(mNetworkPolicy.valueAt(i).toString());
3195 }
3196 fout.decreaseIndent();
3197
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003198 fout.println();
3199 fout.println("Subscription plans:");
3200 fout.increaseIndent();
3201 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3202 final int subId = mSubscriptionPlans.keyAt(i);
3203 fout.println("Subscriber ID " + subId + ":");
3204 fout.increaseIndent();
3205 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3206 if (!ArrayUtils.isEmpty(plans)) {
3207 for (SubscriptionPlan plan : plans) {
3208 fout.println(plan);
3209 }
3210 }
3211 fout.decreaseIndent();
3212 }
3213 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003214
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003215 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003216 fout.println("Policy for UIDs:");
3217 fout.increaseIndent();
3218 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003219 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003220 final int uid = mUidPolicy.keyAt(i);
3221 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003222 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003223 fout.print(uid);
3224 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003225 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003226 fout.println();
3227 }
3228 fout.decreaseIndent();
3229
3230 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3231 if (size > 0) {
3232 fout.println("Power save whitelist (except idle) app ids:");
3233 fout.increaseIndent();
3234 for (int i = 0; i < size; i++) {
3235 fout.print("UID=");
3236 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3237 fout.print(": ");
3238 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3239 fout.println();
3240 }
3241 fout.decreaseIndent();
3242 }
3243
3244 size = mPowerSaveWhitelistAppIds.size();
3245 if (size > 0) {
3246 fout.println("Power save whitelist app ids:");
3247 fout.increaseIndent();
3248 for (int i = 0; i < size; i++) {
3249 fout.print("UID=");
3250 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3251 fout.print(": ");
3252 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3253 fout.println();
3254 }
3255 fout.decreaseIndent();
3256 }
3257
Felipe Lemef0823852016-06-08 13:43:08 -07003258 size = mDefaultRestrictBackgroundWhitelistUids.size();
3259 if (size > 0) {
3260 fout.println("Default restrict background whitelist uids:");
3261 fout.increaseIndent();
3262 for (int i = 0; i < size; i++) {
3263 fout.print("UID=");
3264 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3265 fout.println();
3266 }
3267 fout.decreaseIndent();
3268 }
3269
3270 size = mRestrictBackgroundWhitelistRevokedUids.size();
3271 if (size > 0) {
3272 fout.println("Default restrict background whitelist uids revoked by users:");
3273 fout.increaseIndent();
3274 for (int i = 0; i < size; i++) {
3275 fout.print("UID=");
3276 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3277 fout.println();
3278 }
3279 fout.decreaseIndent();
3280 }
3281
3282 final SparseBooleanArray knownUids = new SparseBooleanArray();
3283 collectKeys(mUidState, knownUids);
3284 collectKeys(mUidRules, knownUids);
3285
3286 fout.println("Status for all known UIDs:");
3287 fout.increaseIndent();
3288 size = knownUids.size();
3289 for (int i = 0; i < size; i++) {
3290 final int uid = knownUids.keyAt(i);
3291 fout.print("UID=");
3292 fout.print(uid);
3293
3294 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3295 fout.print(" state=");
3296 fout.print(state);
3297 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3298 fout.print(" (fg)");
3299 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003300 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003301 ? " (fg svc)" : " (bg)");
3302 }
3303
3304 final int uidRules = mUidRules.get(uid, RULE_NONE);
3305 fout.print(" rules=");
3306 fout.print(uidRulesToString(uidRules));
3307 fout.println();
3308 }
3309 fout.decreaseIndent();
3310
3311 fout.println("Status for just UIDs with rules:");
3312 fout.increaseIndent();
3313 size = mUidRules.size();
3314 for (int i = 0; i < size; i++) {
3315 final int uid = mUidRules.keyAt(i);
3316 fout.print("UID=");
3317 fout.print(uid);
3318 final int uidRules = mUidRules.get(uid, RULE_NONE);
3319 fout.print(" rules=");
3320 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003321 fout.println();
3322 }
3323 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003324
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003325 fout.println("Admin restricted uids for metered data:");
3326 fout.increaseIndent();
3327 size = mMeteredRestrictedUids.size();
3328 for (int i = 0; i < size; ++i) {
3329 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3330 fout.println(mMeteredRestrictedUids.valueAt(i));
3331 }
3332 fout.decreaseIndent();
3333
Makoto Onuki49392d32018-04-11 13:51:02 -07003334 fout.println();
3335 mStatLogger.dump(fout);
3336
Sudheer Shanka352dc572017-09-22 17:09:38 -07003337 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003338 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003339 }
3340 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003341
3342 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003343 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003344 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003345 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003346 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003347 }
3348
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003349 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003350 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003351 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003352 return isUidStateForeground(
3353 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003354 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003355 }
3356
Felipe Lemef0823852016-06-08 13:43:08 -07003357 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003358 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003359 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003360 }
3361
Felipe Lemef0823852016-06-08 13:43:08 -07003362 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003363 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3364 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3365 }
3366
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003367 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003368 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003369 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003370 }
3371
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003372 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003373 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003374 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3375 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003376 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003377 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003378 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3379 try {
3380 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3381 if (oldUidState != uidState) {
3382 // state changed, push updated rules
3383 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003384 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3385 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3386 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003387 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003388 if (mDeviceIdleMode) {
3389 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003390 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003391 if (mRestrictPower) {
3392 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003393 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003394 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003395 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003396 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003397 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003398 } finally {
3399 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003400 }
3401 }
3402
Felipe Lemef0823852016-06-08 13:43:08 -07003403 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003404 final int index = mUidState.indexOfKey(uid);
3405 if (index >= 0) {
3406 final int oldUidState = mUidState.valueAt(index);
3407 mUidState.removeAt(index);
3408 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003409 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003410 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003411 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003412 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003413 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003414 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003415 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003416 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003417 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003418 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003419 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003420 }
3421 }
3422
Felipe Lemef28983d2016-03-25 12:18:23 -07003423 // adjust stats accounting based on foreground status
3424 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003425 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3426 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3427 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3428 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003429 try {
3430 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003431 } finally {
3432 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003433 }
3434 }
3435
Sudheer Shankac9d94072017-02-22 22:13:55 +00003436 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3437 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003438 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003439 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003440 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003441 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003442 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003443 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003444 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003445 }
3446
Felipe Lemef0823852016-06-08 13:43:08 -07003447 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003448 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3449 try {
3450 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3451 mUidFirewallPowerSaveRules);
3452 } finally {
3453 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3454 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003455 }
3456
Felipe Lemef0823852016-06-08 13:43:08 -07003457 void updateRuleForRestrictPowerUL(int uid) {
3458 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003459 }
3460
Felipe Lemef0823852016-06-08 13:43:08 -07003461 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003462 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3463 try {
3464 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3465 mUidFirewallDozableRules);
3466 } finally {
3467 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3468 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003469 }
3470
Felipe Lemef0823852016-06-08 13:43:08 -07003471 void updateRuleForDeviceIdleUL(int uid) {
3472 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003473 }
3474
Felipe Lemef28983d2016-03-25 12:18:23 -07003475 // NOTE: since both fw_dozable and fw_powersave uses the same map
3476 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003477 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003478 SparseIntArray rules) {
3479 if (enabled) {
3480 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003481 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003482 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003483 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003484 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003485 for (int ui = users.size() - 1; ui >= 0; ui--) {
3486 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003487 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3488 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3489 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3490 updateRulesForWhitelistedAppIds(uidRules,
3491 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003492 }
3493 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003494 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003495 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003496 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3497 }
3498 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003499 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003500 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003501 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003502 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003503 }
3504
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003505 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3506 final SparseBooleanArray whitelistedAppIds, int userId) {
3507 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3508 if (whitelistedAppIds.valueAt(i)) {
3509 final int appId = whitelistedAppIds.keyAt(i);
3510 final int uid = UserHandle.getUid(userId, appId);
3511 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3512 }
3513 }
3514 }
3515
3516 /**
3517 * @param deviceIdleMode if true then we don't consider
3518 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3519 * whitelisted.
3520 */
3521 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003522 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003523 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3524 || mPowerSaveWhitelistAppIds.get(appId);
3525 if (!deviceIdleMode) {
3526 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3527 }
3528 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003529 }
3530
Felipe Lemef28983d2016-03-25 12:18:23 -07003531 // NOTE: since both fw_dozable and fw_powersave uses the same map
3532 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003533 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003534 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003535 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3536 chain == FIREWALL_CHAIN_DOZABLE);
3537 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003538 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003539 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003540 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003541 }
3542 }
3543 }
3544
Felipe Lemef0823852016-06-08 13:43:08 -07003545 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003546 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3547 try {
3548 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3549 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003550
Felipe Leme873a83a2016-09-07 11:34:10 -07003551 // Fully update the app idle firewall chain.
3552 final List<UserInfo> users = mUserManager.getUsers();
3553 for (int ui = users.size() - 1; ui >= 0; ui--) {
3554 UserInfo user = users.get(ui);
3555 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3556 for (int uid : idleUids) {
3557 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3558 // quick check: if this uid doesn't have INTERNET permission, it
3559 // doesn't have network access anyway, so it is a waste to mess
3560 // with it here.
3561 if (hasInternetPermissions(uid)) {
3562 uidRules.put(uid, FIREWALL_RULE_DENY);
3563 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003564 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003565 }
3566 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003567
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003568 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003569 } finally {
3570 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3571 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003572 }
3573
Felipe Lemef0823852016-06-08 13:43:08 -07003574 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003575 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003576
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003577 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3578 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3579 }
3580 try {
3581 int appId = UserHandle.getAppId(uid);
3582 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3583 && !isUidForegroundOnRestrictPowerUL(uid)) {
3584 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3585 } else {
3586 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3587 }
3588 } finally {
3589 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003590 }
3591 }
3592
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003593 /**
3594 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3595 * changed.
3596 */
Felipe Lemef0823852016-06-08 13:43:08 -07003597 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003598 boolean paroled = mUsageStats.isAppIdleParoleOn();
3599 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003600 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003601
3602 int ruleCount = mUidFirewallStandbyRules.size();
3603 for (int i = 0; i < ruleCount; i++) {
3604 int uid = mUidFirewallStandbyRules.keyAt(i);
3605 int oldRules = mUidRules.get(uid);
3606 if (enableChain) {
3607 // Chain wasn't enabled before and the other power-related
3608 // chains are whitelists, so we can clear the
3609 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3610 // the effective rules result in blocking network access.
3611 oldRules &= MASK_METERED_NETWORKS;
3612 } else {
3613 // Skip if it had no restrictions to begin with
3614 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3615 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003616 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3617 if (newUidRules == RULE_NONE) {
3618 mUidRules.delete(uid);
3619 } else {
3620 mUidRules.put(uid, newUidRules);
3621 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003622 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003623 }
3624
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003625 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003626 * Update rules that might be changed by {@link #mRestrictBackground},
3627 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003628 */
Felipe Lemef0823852016-06-08 13:43:08 -07003629 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003630 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3631 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3632 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3633 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003634 try {
Felipe Leme09700462016-09-08 09:33:48 -07003635 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003636 updateRulesForRestrictPowerUL();
3637 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003638
Felipe Leme873a83a2016-09-07 11:34:10 -07003639 // If the set of restricted networks may have changed, re-evaluate those.
3640 if (restrictedNetworksChanged) {
3641 normalizePoliciesNL();
3642 updateNetworkRulesNL();
3643 }
3644 } finally {
3645 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003646 }
3647 }
3648
Felipe Leme09700462016-09-08 09:33:48 -07003649 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003650 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003651 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3652 try {
3653 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003654 updateRulesForPowerSaveUL();
3655 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3656 } finally {
3657 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3658 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003659 }
3660
Felipe Lemef0823852016-06-08 13:43:08 -07003661 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003662 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3663 try {
3664 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3665 } finally {
3666 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3667 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003668 }
3669
3670 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3671 private static final int TYPE_RESTRICT_POWER = 2;
3672 @Retention(RetentionPolicy.SOURCE)
3673 @IntDef(flag = false, value = {
3674 TYPE_RESTRICT_BACKGROUND,
3675 TYPE_RESTRICT_POWER,
3676 })
3677 public @interface RestrictType {
3678 }
3679
3680 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003681 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003682 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3683 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3684 }
3685 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003686 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003687
3688 final PackageManager pm = mContext.getPackageManager();
3689 final List<UserInfo> users;
3690 final List<ApplicationInfo> apps;
3691
3692 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3693 try {
3694 users = mUserManager.getUsers();
3695 } finally {
3696 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3697 }
3698 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3699 try {
3700 apps = pm.getInstalledApplications(
3701 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3702 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3703 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3704 } finally {
3705 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3706 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003707
Felipe Leme873a83a2016-09-07 11:34:10 -07003708 final int usersSize = users.size();
3709 final int appsSize = apps.size();
3710 for (int i = 0; i < usersSize; i++) {
3711 final UserInfo user = users.get(i);
3712 for (int j = 0; j < appsSize; j++) {
3713 final ApplicationInfo app = apps.get(j);
3714 final int uid = UserHandle.getUid(user.id, app.uid);
3715 switch (type) {
3716 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003717 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003718 break;
3719 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003720 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003721 break;
3722 default:
3723 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3724 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003725 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003726 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003727 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003728 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003729 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003730 }
3731
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003732 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003733 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003734 final int numUsers = users.size();
3735 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003736 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003737 int uid = UserHandle.getUid(user.id, appId);
3738 // Update external firewall rules.
3739 updateRuleForAppIdleUL(uid);
3740 updateRuleForDeviceIdleUL(uid);
3741 updateRuleForRestrictPowerUL(uid);
3742 // Update internal rules.
3743 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003744 }
3745 }
3746
Felipe Leme70c57c22016-03-29 10:45:13 -07003747 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3748 // methods below could be merged into a isUidValidForRules() method.
3749 private boolean isUidValidForBlacklistRules(int uid) {
3750 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003751 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003752 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003753 return true;
3754 }
3755
3756 return false;
3757 }
3758
Felipe Leme70c57c22016-03-29 10:45:13 -07003759 private boolean isUidValidForWhitelistRules(int uid) {
3760 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3761 }
3762
Amith Yamasani15e472352015-04-24 19:06:07 -07003763 private boolean isUidIdle(int uid) {
3764 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3765 final int userId = UserHandle.getUserId(uid);
3766
songjinshi0655edd2016-05-18 19:55:32 +08003767 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003768 for (String packageName : packages) {
3769 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3770 return false;
3771 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003772 }
3773 }
3774 return true;
3775 }
3776
3777 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003778 * Checks if an uid has INTERNET permissions.
3779 * <p>
3780 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003781 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003782 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003783 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003784 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003785 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003786 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003787 }
3788 } catch (RemoteException e) {
3789 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003790 return true;
3791 }
3792
3793 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003794 * Clears all state - internal and external - associated with an UID.
3795 */
3796 private void onUidDeletedUL(int uid) {
3797 // First cleanup in-memory state synchronously...
3798 mUidRules.delete(uid);
3799 mUidPolicy.delete(uid);
3800 mUidFirewallStandbyRules.delete(uid);
3801 mUidFirewallDozableRules.delete(uid);
3802 mUidFirewallPowerSaveRules.delete(uid);
3803 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3804 mPowerSaveWhitelistAppIds.delete(uid);
3805 mPowerSaveTempWhitelistAppIds.delete(uid);
3806
3807 // ...then update iptables asynchronously.
3808 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3809 }
3810
3811 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003812 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003813 *
Felipe Leme781ba142016-05-09 16:24:48 -07003814 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003815 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003816 * <li>Doze mode
3817 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003818 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003819 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003820 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003821 *
3822 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003823 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003824 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003825 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003826 updateRuleForDeviceIdleUL(uid);
3827 updateRuleForAppIdleUL(uid);
3828 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003829
3830 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003831 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003832
3833 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003834 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003835 }
3836
Felipe Leme70c57c22016-03-29 10:45:13 -07003837 /**
3838 * Applies network rules to bandwidth controllers based on process state and user-defined
3839 * restrictions (blacklist / whitelist).
3840 *
3841 * <p>
3842 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3843 * networks:
3844 * <ul>
3845 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3846 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3847 * also blacklisted.
3848 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3849 * no UIDs other those whitelisted will have access.
3850 * <ul>
3851 *
3852 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3853 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3854 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3855 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003856 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003857 * {@link INetworkManagementService}, but this method should also be called in events (like
3858 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3859 * following rules should also be applied:
3860 *
3861 * <ul>
3862 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3863 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3864 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3865 * {@code bw_penalty_box}.
3866 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3867 * </ul>
3868 *
3869 * <p>For optimization, the rules are only applied on user apps that have internet access
3870 * permission, since there is no need to change the {@code iptables} rule if the app does not
3871 * have permission to use the internet.
3872 *
3873 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003874 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003875 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003876 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003877 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3878 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3879 "updateRulesForDataUsageRestrictionsUL: " + uid);
3880 }
3881 try {
3882 updateRulesForDataUsageRestrictionsULInner(uid);
3883 } finally {
3884 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3885 }
3886 }
3887
3888 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003889 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003890 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003891 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003892 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003893
Dianne Hackborn497175b2014-07-01 12:56:08 -07003894 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003895 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003896 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003897 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003898
Felipe Leme781ba142016-05-09 16:24:48 -07003899 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003900 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003901 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3902 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003903
Felipe Leme70c57c22016-03-29 10:45:13 -07003904 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003905 if (isRestrictedByAdmin) {
3906 newRule = RULE_REJECT_METERED;
3907 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003908 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3909 newRule = RULE_TEMPORARY_ALLOW_METERED;
3910 } else if (isWhitelisted) {
3911 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003912 }
3913 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003914 if (isBlacklisted) {
3915 newRule = RULE_REJECT_METERED;
3916 } else if (mRestrictBackground && isWhitelisted) {
3917 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003918 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003919 }
Felipe Leme781ba142016-05-09 16:24:48 -07003920 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003921
Felipe Lemef28983d2016-03-25 12:18:23 -07003922 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003923 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003924 + ": isForeground=" +isForeground
3925 + ", isBlacklisted=" + isBlacklisted
3926 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003927 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003928 + ", oldRule=" + uidRulesToString(oldRule)
3929 + ", newRule=" + uidRulesToString(newRule)
3930 + ", newUidRules=" + uidRulesToString(newUidRules)
3931 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003932 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003933
Felipe Leme46c4fc32016-05-04 09:21:43 -07003934 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003935 mUidRules.delete(uid);
3936 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003937 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003938 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003939
Felipe Leme70c57c22016-03-29 10:45:13 -07003940 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003941 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003942 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003943 // Temporarily whitelist foreground app, removing from blacklist if necessary
3944 // (since bw_penalty_box prevails over bw_happy_box).
3945
3946 setMeteredNetworkWhitelist(uid, true);
3947 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3948 // but ideally it should be just:
3949 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003950 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003951 setMeteredNetworkBlacklist(uid, false);
3952 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003953 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003954 // Remove temporary whitelist from app that is not on foreground anymore.
3955
3956 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3957 // but ideally they should be just:
3958 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3959 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003960 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003961 setMeteredNetworkWhitelist(uid, false);
3962 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003963 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003964 setMeteredNetworkBlacklist(uid, true);
3965 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003966 } else if (hasRule(newRule, RULE_REJECT_METERED)
3967 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003968 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003969 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003970 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003971 // Since blacklist prevails over whitelist, we need to handle the special case
3972 // where app is whitelisted and blacklisted at the same time (although such
3973 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003974 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003975 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003976 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3977 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003978 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003979 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003980 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003981 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003982 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3983 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003984 + ", whitelisted=" + isWhitelisted
3985 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003986 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003987 + ", newRule=" + uidRulesToString(newUidRules)
3988 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003989 }
Felipe Leme781ba142016-05-09 16:24:48 -07003990
Sudheer Shankac9d94072017-02-22 22:13:55 +00003991 // Dispatch changed rule to existing listeners.
3992 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003993 }
3994 }
3995
3996 /**
3997 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3998 * listeners in case of change.
3999 * <p>
4000 * There are 3 power-related rules that affects whether an app has background access on
4001 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4002 * restriction, it's added to the equivalent firewall chain:
4003 * <ul>
4004 * <li>App is idle: {@code fw_standby} firewall chain.
4005 * <li>Device is idle: {@code fw_dozable} firewall chain.
4006 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4007 * </ul>
4008 * <p>
4009 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4010 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4011 * <p>
4012 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4013 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004014 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004015 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4016
Sudheer Shankac9d94072017-02-22 22:13:55 +00004017 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004018
Sudheer Shankac9d94072017-02-22 22:13:55 +00004019 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004020 mUidRules.delete(uid);
4021 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004022 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004023 }
4024 }
4025
4026 /**
4027 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4028 *
4029 * @param uid the uid of the app to update rules for
4030 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4031 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4032 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004033 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004034 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004035 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004036 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4037 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4038 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4039 + (paroled ? "P" : "-"));
4040 }
4041 try {
4042 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4043 } finally {
4044 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4045 }
4046 }
4047
4048 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004049 if (!isUidValidForBlacklistRules(uid)) {
4050 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004051 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004052 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004053
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004054 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004055 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004056 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004057
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07004058 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004059 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4060 int newRule = RULE_NONE;
4061
4062 // First step: define the new rule based on user restrictions and foreground state.
4063
4064 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4065 // by considering the foreground and non-foreground states.
4066 if (isForeground) {
4067 if (restrictMode) {
4068 newRule = RULE_ALLOW_ALL;
4069 }
4070 } else if (restrictMode) {
4071 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4072 }
4073
4074 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4075
4076 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004077 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004078 + ", isIdle: " + isIdle
4079 + ", mRestrictPower: " + mRestrictPower
4080 + ", mDeviceIdleMode: " + mDeviceIdleMode
4081 + ", isForeground=" + isForeground
4082 + ", isWhitelisted=" + isWhitelisted
4083 + ", oldRule=" + uidRulesToString(oldRule)
4084 + ", newRule=" + uidRulesToString(newRule)
4085 + ", newUidRules=" + uidRulesToString(newUidRules)
4086 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4087 }
4088
Felipe Leme781ba142016-05-09 16:24:48 -07004089 // Second step: notify listeners if state changed.
4090 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004091 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004092 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004093 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004094 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4095 } else {
4096 // All scenarios should have been covered above
4097 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4098 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004099 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004100 + ", newRule=" + uidRulesToString(newUidRules)
4101 + ", oldRule=" + uidRulesToString(oldUidRules));
4102 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004103 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004104 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004105
Sudheer Shankac9d94072017-02-22 22:13:55 +00004106 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004107 }
4108
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004109 private class AppIdleStateChangeListener
4110 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4111
4112 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004113 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4114 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004115 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004116 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4117 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004118 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004119 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004120 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004121 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004122 }
4123 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004124 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004125 }
4126
4127 @Override
4128 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004129 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004130 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004131 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004132 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004133 }
4134 }
4135
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004136 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4137 if (listener != null) {
4138 try {
4139 listener.onUidRulesChanged(uid, uidRules);
4140 } catch (RemoteException ignored) {
4141 }
4142 }
4143 }
4144
4145 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4146 String[] meteredIfaces) {
4147 if (listener != null) {
4148 try {
4149 listener.onMeteredIfacesChanged(meteredIfaces);
4150 } catch (RemoteException ignored) {
4151 }
4152 }
4153 }
4154
4155 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4156 boolean restrictBackground) {
4157 if (listener != null) {
4158 try {
4159 listener.onRestrictBackgroundChanged(restrictBackground);
4160 } catch (RemoteException ignored) {
4161 }
4162 }
4163 }
4164
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004165 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4166 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004167 if (listener != null) {
4168 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004169 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004170 } catch (RemoteException ignored) {
4171 }
4172 }
4173 }
4174
Jeff Sharkey9252b342018-01-19 07:58:35 +09004175 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4176 int overrideMask, int overrideValue) {
4177 if (listener != null) {
4178 try {
4179 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4180 } catch (RemoteException ignored) {
4181 }
4182 }
4183 }
4184
Makoto Onuki8e777332017-03-28 11:25:47 -07004185 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004186 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004187 public boolean handleMessage(Message msg) {
4188 switch (msg.what) {
4189 case MSG_RULES_CHANGED: {
4190 final int uid = msg.arg1;
4191 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004192 final int length = mListeners.beginBroadcast();
4193 for (int i = 0; i < length; i++) {
4194 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4195 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004196 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004197 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004198 return true;
4199 }
4200 case MSG_METERED_IFACES_CHANGED: {
4201 final String[] meteredIfaces = (String[]) msg.obj;
4202 final int length = mListeners.beginBroadcast();
4203 for (int i = 0; i < length; i++) {
4204 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004205 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004206 }
4207 mListeners.finishBroadcast();
4208 return true;
4209 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004210 case MSG_LIMIT_REACHED: {
4211 final String iface = (String) msg.obj;
4212
Felipe Lemef0823852016-06-08 13:43:08 -07004213 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004214 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004215 // force stats update to make sure we have
4216 // numbers that caused alert to trigger.
4217 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004218
Felipe Lemef0823852016-06-08 13:43:08 -07004219 updateNetworkEnabledNL();
4220 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004221 }
4222 }
4223 return true;
4224 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004225 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4226 final boolean restrictBackground = msg.arg1 != 0;
4227 final int length = mListeners.beginBroadcast();
4228 for (int i = 0; i < length; i++) {
4229 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004230 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004231 }
4232 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004233 final Intent intent =
4234 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4235 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4236 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4237 return true;
4238 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004239 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004240 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004241 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004242 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004243 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004244 final int length = mListeners.beginBroadcast();
4245 for (int i = 0; i < length; i++) {
4246 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004247 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004248 }
4249 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004250 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4251 if (notifyApp.booleanValue()) {
4252 broadcastRestrictBackgroundChanged(uid, notifyApp);
4253 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004254 return true;
4255 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004256 case MSG_ADVISE_PERSIST_THRESHOLD: {
4257 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004258 // make sure stats are recorded frequently enough; we aim
4259 // for 2MB threshold for 2GB/month rules.
4260 final long persistThreshold = lowestRule / 1000;
4261 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004262 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004263 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004264 case MSG_UPDATE_INTERFACE_QUOTA: {
4265 removeInterfaceQuota((String) msg.obj);
4266 // int params need to be stitched back into a long
4267 setInterfaceQuota((String) msg.obj,
4268 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4269 return true;
4270 }
4271 case MSG_REMOVE_INTERFACE_QUOTA: {
4272 removeInterfaceQuota((String) msg.obj);
4273 return true;
4274 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004275 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4276 resetUidFirewallRules(msg.arg1);
4277 return true;
4278 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004279 case MSG_SUBSCRIPTION_OVERRIDE: {
4280 final int overrideMask = msg.arg1;
4281 final int overrideValue = msg.arg2;
4282 final int subId = (int) msg.obj;
4283 final int length = mListeners.beginBroadcast();
4284 for (int i = 0; i < length; i++) {
4285 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4286 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4287 }
4288 mListeners.finishBroadcast();
4289 return true;
4290 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004291 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4292 final int userId = msg.arg1;
4293 final Set<String> packageNames = (Set<String>) msg.obj;
4294 setMeteredRestrictedPackagesInternal(packageNames, userId);
4295 return true;
4296 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004297 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4298 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4299 final boolean enabled = msg.arg1 != 0;
4300 setNetworkTemplateEnabledInner(template, enabled);
4301 return true;
4302 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004303 default: {
4304 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004305 }
4306 }
4307 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004308 };
4309
4310 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4311 @Override
4312 public boolean handleMessage(Message msg) {
4313 switch (msg.what) {
4314 case UID_MSG_STATE_CHANGED: {
4315 final int uid = msg.arg1;
4316 final int procState = msg.arg2;
4317 final long procStateSeq = (Long) msg.obj;
4318
4319 handleUidChanged(uid, procState, procStateSeq);
4320 return true;
4321 }
4322 case UID_MSG_GONE: {
4323 final int uid = msg.arg1;
4324 handleUidGone(uid);
4325 return true;
4326 }
4327 default: {
4328 return false;
4329 }
4330 }
4331 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004332
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004333 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004334
Makoto Onuki8e777332017-03-28 11:25:47 -07004335 void handleUidChanged(int uid, int procState, long procStateSeq) {
4336 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4337 try {
4338 synchronized (mUidRulesFirstLock) {
4339 // We received a uid state change callback, add it to the history so that it
4340 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004341 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004342 // Now update the network policy rules as per the updated uid state.
4343 updateUidStateUL(uid, procState);
4344 // Updating the network rules is done, so notify AMS about this.
4345 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4346 }
4347 } finally {
4348 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4349 }
4350 }
4351
4352 void handleUidGone(int uid) {
4353 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4354 try {
4355 synchronized (mUidRulesFirstLock) {
4356 removeUidStateUL(uid);
4357 }
4358 } finally {
4359 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4360 }
4361 }
4362
Felipe Leme57e3d312016-08-23 14:42:52 -07004363 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4364 final PackageManager pm = mContext.getPackageManager();
4365 final String[] packages = pm.getPackagesForUid(uid);
4366 if (packages != null) {
4367 final int userId = UserHandle.getUserId(uid);
4368 for (String packageName : packages) {
4369 final Intent intent =
4370 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4371 intent.setPackage(packageName);
4372 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4373 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4374 }
4375 }
4376 }
4377
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004378 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4379 // long quotaBytes split up into two ints to fit in message
4380 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4381 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4382 }
4383
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004384 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004385 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004386 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004387 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004388 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004389 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004390 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004391 }
4392 }
4393
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004394 private void removeInterfaceQuotaAsync(String iface) {
4395 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4396 }
4397
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004398 private void removeInterfaceQuota(String iface) {
4399 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004400 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004401 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004402 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004403 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004404 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004405 }
4406 }
4407
Felipe Leme70c57c22016-03-29 10:45:13 -07004408 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4409 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004410 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004411 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004412 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004413 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4414 } catch (RemoteException e) {
4415 // ignored; service lives in system_server
4416 }
4417 }
4418
4419 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4420 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4421 try {
4422 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4423 } catch (IllegalStateException e) {
4424 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004425 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004426 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004427 }
4428 }
4429
Felipe Lemebc853dd2016-09-08 13:26:55 -07004430 private static final int CHAIN_TOGGLE_NONE = 0;
4431 private static final int CHAIN_TOGGLE_ENABLE = 1;
4432 private static final int CHAIN_TOGGLE_DISABLE = 2;
4433 @Retention(RetentionPolicy.SOURCE)
4434 @IntDef(flag = false, value = {
4435 CHAIN_TOGGLE_NONE,
4436 CHAIN_TOGGLE_ENABLE,
4437 CHAIN_TOGGLE_DISABLE
4438 })
4439 public @interface ChainToggleType {
4440 }
4441
4442 /**
4443 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004444 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004445 *
4446 * @param chain firewall chain.
4447 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4448 * @param toggle whether the chain should be enabled, disabled, or not changed.
4449 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004450 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004451 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004452 if (uidRules != null) {
4453 setUidFirewallRulesUL(chain, uidRules);
4454 }
4455 if (toggle != CHAIN_TOGGLE_NONE) {
4456 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4457 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004458 }
4459
Amith Yamasani15e472352015-04-24 19:06:07 -07004460 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004461 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4462 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4463 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004464 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004465 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004466 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004467 int size = uidRules.size();
4468 int[] uids = new int[size];
4469 int[] rules = new int[size];
4470 for(int index = size - 1; index >= 0; --index) {
4471 uids[index] = uidRules.keyAt(index);
4472 rules[index] = uidRules.valueAt(index);
4473 }
4474 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004475 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004476 } catch (IllegalStateException e) {
4477 Log.wtf(TAG, "problem setting firewall uid rules", e);
4478 } catch (RemoteException e) {
4479 // ignored; service lives in system_server
4480 }
4481 }
4482
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004483 /**
4484 * Add or remove a uid to the firewall blacklist for all network ifaces.
4485 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004486 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004487 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4488 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4489 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004490 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004491 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004492 if (chain == FIREWALL_CHAIN_DOZABLE) {
4493 mUidFirewallDozableRules.put(uid, rule);
4494 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4495 mUidFirewallStandbyRules.put(uid, rule);
4496 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4497 mUidFirewallPowerSaveRules.put(uid, rule);
4498 }
4499
4500 try {
4501 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004502 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004503 } catch (IllegalStateException e) {
4504 Log.wtf(TAG, "problem setting firewall uid rules", e);
4505 } catch (RemoteException e) {
4506 // ignored; service lives in system_server
4507 }
4508 } finally {
4509 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004510 }
4511 }
4512
4513 /**
4514 * Add or remove a uid to the firewall blacklist for all network ifaces.
4515 */
Felipe Lemef0823852016-06-08 13:43:08 -07004516 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004517 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4518 mFirewallChainStates.get(chain) == enable) {
4519 // All is the same, nothing to do.
4520 return;
4521 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004522 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004523 try {
4524 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004525 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004526 } catch (IllegalStateException e) {
4527 Log.wtf(TAG, "problem enable firewall chain", e);
4528 } catch (RemoteException e) {
4529 // ignored; service lives in system_server
4530 }
4531 }
4532
Felipe Leme03e95e22016-09-09 09:25:31 -07004533 /**
4534 * Resets all firewall rules associated with an UID.
4535 */
4536 private void resetUidFirewallRules(int uid) {
4537 try {
4538 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4539 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4540 mNetworkManager
4541 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4542 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4543 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4544 } catch (IllegalStateException e) {
4545 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4546 } catch (RemoteException e) {
4547 // ignored; service lives in system_server
4548 }
4549 }
4550
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004551 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004552 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004553 return getNetworkTotalBytes(template, start, end);
4554 }
4555
4556 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004557 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004558 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004559 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004560 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004561 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004562 }
4563 }
4564
4565 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4566 try {
4567 return mNetworkStats.getNetworkUidBytes(template, start, end);
4568 } catch (RuntimeException e) {
4569 Slog.w(TAG, "Failed to read network stats: " + e);
4570 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004571 }
4572 }
4573
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004574 private boolean isBandwidthControlEnabled() {
4575 final long token = Binder.clearCallingIdentity();
4576 try {
4577 return mNetworkManager.isBandwidthControlEnabled();
4578 } catch (RemoteException e) {
4579 // ignored; service lives in system_server
4580 return false;
4581 } finally {
4582 Binder.restoreCallingIdentity(token);
4583 }
4584 }
4585
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004586 private static Intent buildAllowBackgroundDataIntent() {
4587 return new Intent(ACTION_ALLOW_BACKGROUND);
4588 }
4589
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004590 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4591 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004592 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4593 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4594 return intent;
4595 }
4596
4597 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4598 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4599 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004600 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4601 return intent;
4602 }
4603
Wei Liu546cb772016-07-21 16:19:01 -07004604 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004605 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004606 intent.setComponent(ComponentName.unflattenFromString(
4607 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004608 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4609 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4610 return intent;
4611 }
4612
Wei Liu546cb772016-07-21 16:19:01 -07004613 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004614 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004615 intent.setComponent(ComponentName.unflattenFromString(
4616 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004617 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4618 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4619 return intent;
4620 }
4621
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004622 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004623 public void addIdleHandler(IdleHandler handler) {
4624 mHandler.getLooper().getQueue().addIdleHandler(handler);
4625 }
4626
jackqdyulei29c82ab2017-03-10 14:09:16 -08004627 @VisibleForTesting
4628 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4629 mRestrictBackgroundPowerState = result;
4630
4631 boolean restrictBackground = result.batterySaverEnabled;
4632 boolean shouldInvokeRestrictBackground;
4633 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4634 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4635
4636 if (result.globalBatterySaverEnabled) {
4637 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4638 // turn it on.
4639 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4640 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4641 localRestrictBgChangedInBsm = false;
4642 } else {
4643 // Try to restore the restrictBackground if it doesn't change in bsm
4644 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4645 restrictBackground = mRestrictBackgroundBeforeBsm;
4646 }
4647
4648 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004649 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004650 }
4651
4652 // Change it at last so setRestrictBackground() won't affect this variable
4653 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4654 }
4655
Jeff Sharkey1b861272011-05-22 00:34:52 -07004656 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4657 final int size = source.size();
4658 for (int i = 0; i < size; i++) {
4659 target.put(source.keyAt(i), true);
4660 }
4661 }
4662
Stuart Scottf1fb3972015-04-02 18:00:02 -07004663 @Override
4664 public void factoryReset(String subscriber) {
4665 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4666
Stuart Scotte3e314d2015-04-20 14:07:45 -07004667 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4668 return;
4669 }
4670
Stuart Scottf1fb3972015-04-02 18:00:02 -07004671 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004672 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004673 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4674 for (NetworkPolicy policy : policies) {
4675 if (policy.template.equals(template)) {
4676 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4677 policy.inferred = false;
4678 policy.clearSnooze();
4679 }
4680 }
4681 setNetworkPolicies(policies);
4682
4683 // Turn restrict background data off
4684 setRestrictBackground(false);
4685
Stuart Scotte3e314d2015-04-20 14:07:45 -07004686 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4687 // Remove app's "restrict background data" flag
4688 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4689 setUidPolicy(uid, POLICY_NONE);
4690 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004691 }
4692 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004693
Sudheer Shankab8f23162017-08-04 13:30:10 -07004694 @Override
4695 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004696 final long startTime = mStatLogger.getTime();
4697
Sudheer Shankab8f23162017-08-04 13:30:10 -07004698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Makoto Onuki49392d32018-04-11 13:51:02 -07004699 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4700
4701 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4702
4703 return ret;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004704 }
4705
4706 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4707 final int uidRules;
4708 final boolean isBackgroundRestricted;
4709 synchronized (mUidRulesFirstLock) {
4710 uidRules = mUidRules.get(uid, RULE_NONE);
4711 isBackgroundRestricted = mRestrictBackground;
4712 }
4713 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004714 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004715 return true;
4716 }
4717 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004718 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004719 return false;
4720 }
4721 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004722 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004723 return true;
4724 }
4725 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004726 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004727 return false;
4728 }
4729 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004730 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004731 return false;
4732 }
4733 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004734 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004735 return true;
4736 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004737 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004738 return false;
4739 }
4740
Felipe Lemed17fda42016-04-29 11:12:45 -07004741 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4742
4743 @Override
4744 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004745 synchronized (mUidRulesFirstLock) {
4746 boolean changed = removeUserStateUL(userId, false);
4747 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004748 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004749 synchronized (mNetworkPoliciesSecondLock) {
4750 writePolicyAL();
4751 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004752 }
4753 }
4754 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004755
4756 /**
4757 * @return true if the given uid is restricted from doing networking on metered networks.
4758 */
4759 @Override
4760 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4761 final int uidRules;
4762 final boolean isBackgroundRestricted;
4763 synchronized (mUidRulesFirstLock) {
4764 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4765 isBackgroundRestricted = mRestrictBackground;
4766 }
4767 return isBackgroundRestricted
4768 && !hasRule(uidRules, RULE_ALLOW_METERED)
4769 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4770 }
4771
4772 /**
4773 * @return true if networking is blocked on the given interface for the given uid according
4774 * to current networking policies.
4775 */
4776 @Override
4777 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004778 final long startTime = mStatLogger.getTime();
4779
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004780 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004781 synchronized (mNetworkPoliciesSecondLock) {
4782 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004783 }
Makoto Onuki49392d32018-04-11 13:51:02 -07004784 final boolean ret = isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4785
4786 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4787
4788 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004789 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004790
4791 @Override
4792 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4793 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004794 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004795 if (added) {
4796 mPowerSaveTempWhitelistAppIds.put(appId, true);
4797 } else {
4798 mPowerSaveTempWhitelistAppIds.delete(appId);
4799 }
4800 updateRulesForTempWhitelistChangeUL(appId);
4801 }
4802 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004803
4804 @Override
4805 public SubscriptionPlan getSubscriptionPlan(Network network) {
4806 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004807 final int subId = getSubIdLocked(network);
4808 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004809 }
4810 }
4811
4812 @Override
4813 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004814 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004815 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004816 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004817 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004818 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004819 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4820 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4821 }
4822
4823 if (quotaType == QUOTA_TYPE_JOBS) {
4824 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4825 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4826 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4827 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4828 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4829 } else {
4830 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4831 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004832 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004833
4834 @Override
4835 public void onAdminDataAvailable() {
4836 mAdminDataAvailableLatch.countDown();
4837 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004838
4839 @Override
4840 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4841 setMeteredRestrictedPackagesInternal(packageNames, userId);
4842 }
4843
4844 @Override
4845 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4846 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4847 userId, 0, packageNames).sendToTarget();
4848 }
4849 }
4850
4851 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4852 synchronized (mUidRulesFirstLock) {
4853 final Set<Integer> newRestrictedUids = new ArraySet<>();
4854 for (String packageName : packageNames) {
4855 final int uid = getUidForPackage(packageName, userId);
4856 if (uid >= 0) {
4857 newRestrictedUids.add(uid);
4858 }
4859 }
4860 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4861 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4862 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4863 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4864 }
4865 }
4866
4867 private int getUidForPackage(String packageName, int userId) {
4868 try {
4869 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4870 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4871 } catch (NameNotFoundException e) {
4872 return -1;
4873 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004874 }
4875
4876 private int parseSubId(NetworkState state) {
4877 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4878 int subId = INVALID_SUBSCRIPTION_ID;
4879 if (state != null && state.networkCapabilities != null
4880 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4881 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4882 if (spec instanceof StringNetworkSpecifier) {
4883 try {
4884 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4885 } catch (NumberFormatException e) {
4886 }
4887 }
4888 }
4889 return subId;
4890 }
4891
Andreas Gampea36dc622018-02-05 17:19:22 -08004892 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004893 private int getSubIdLocked(Network network) {
4894 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004895 }
4896
Andreas Gampea36dc622018-02-05 17:19:22 -08004897 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004898 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4899 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06004900 if (!ArrayUtils.isEmpty(plans)) {
4901 for (SubscriptionPlan plan : plans) {
4902 if (plan.getCycleRule().isRecurring()) {
4903 // Recurring plans will always have an active cycle
4904 return plan;
4905 } else {
4906 // Non-recurring plans need manual test for active cycle
4907 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
4908 if (cycle.contains(ZonedDateTime.now(mClock))) {
4909 return plan;
4910 }
4911 }
4912 }
4913 }
4914 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09004915 }
4916
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004917 /**
4918 * This will only ever be called once - during device boot.
4919 */
4920 private void waitForAdminData() {
4921 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4922 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4923 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4924 }
4925 }
4926
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004927 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4928 Set<Integer> newRestrictedUids) {
4929 if (oldRestrictedUids == null) {
4930 for (int uid : newRestrictedUids) {
4931 updateRulesForDataUsageRestrictionsUL(uid);
4932 }
4933 return;
4934 }
4935 for (int uid : oldRestrictedUids) {
4936 if (!newRestrictedUids.contains(uid)) {
4937 updateRulesForDataUsageRestrictionsUL(uid);
4938 }
4939 }
4940 for (int uid : newRestrictedUids) {
4941 if (!oldRestrictedUids.contains(uid)) {
4942 updateRulesForDataUsageRestrictionsUL(uid);
4943 }
4944 }
4945 }
4946
4947 private boolean isRestrictedByAdminUL(int uid) {
4948 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4949 UserHandle.getUserId(uid));
4950 return restrictedUids != null && restrictedUids.contains(uid);
4951 }
4952
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004953 private static boolean hasRule(int uidRules, int rule) {
4954 return (uidRules & rule) != 0;
4955 }
4956
Jeff Sharkey2e471452018-01-19 18:02:47 +09004957 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4958 return (val != null) ? val : new NetworkState[0];
4959 }
4960
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06004961 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
4962 String key, boolean defaultValue) {
4963 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
4964 }
4965
Chris Wren193ae6b2017-03-31 15:17:11 -04004966 private class NotificationId {
4967 private final String mTag;
4968 private final int mId;
4969
4970 NotificationId(NetworkPolicy policy, int type) {
4971 mTag = buildNotificationTag(policy, type);
4972 mId = type;
4973 }
4974
4975 @Override
4976 public boolean equals(Object o) {
4977 if (this == o) return true;
4978 if (!(o instanceof NotificationId)) return false;
4979 NotificationId that = (NotificationId) o;
4980 return Objects.equals(mTag, that.mTag);
4981 }
4982
4983 @Override
4984 public int hashCode() {
4985 return Objects.hash(mTag);
4986 }
4987
4988 /**
4989 * Build unique tag that identifies an active {@link NetworkPolicy}
4990 * notification of a specific type, like {@link #TYPE_LIMIT}.
4991 */
4992 private String buildNotificationTag(NetworkPolicy policy, int type) {
4993 return TAG + ":" + policy.template.hashCode() + ":" + type;
4994 }
4995
4996 public String getTag() {
4997 return mTag;
4998 }
4999
5000 public int getId() {
5001 return mId;
5002 }
5003 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005004}