blob: 0c6555b94e9a753cac16f698201a57d8488146b6 [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 Sharkey36b414b2018-03-30 11:00:03 -060074import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
75import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
79import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070080import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070081import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060082import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey0a5570d2018-04-10 12:38:29 -060083import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_NOTIFICATION_BOOL;
84import static android.telephony.CarrierConfigManager.KEY_DATA_RAPID_NOTIFICATION_BOOL;
85import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_NOTIFICATION_BOOL;
Jeff Sharkey9252b342018-01-19 07:58:35 +090086import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080087
Jeff Sharkey854b2b12012-04-13 16:03:40 -070088import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070090import static com.android.internal.util.XmlUtils.readBooleanAttribute;
91import static com.android.internal.util.XmlUtils.readIntAttribute;
92import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060093import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070094import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
95import static com.android.internal.util.XmlUtils.writeIntAttribute;
96import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060097import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070098import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070099import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
100import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
102import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
103import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
104import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700106import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600107
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800109import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700111
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700112import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700113import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900114import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700115import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700116import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800117import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700118import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700119import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700120import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700121import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700122import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700123import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700125import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700126import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700127import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600128import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700129import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700130import android.content.Intent;
131import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700132import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700133import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700134import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700135import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700136import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700137import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700138import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600139import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700141import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700142import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700143import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700144import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700145import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600146import android.net.Network;
147import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700148import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600150import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700151import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600152import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900153import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700154import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700155import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700156import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900157import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600158import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700159import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700160import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700161import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700162import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.os.Environment;
164import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700165import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700166import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700167import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700168import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700169import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700170import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700171import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700172import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700173import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600174import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800175import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700176import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700177import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600178import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700179import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700180import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700181import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600182import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700183import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700184import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700185import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700186import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100187import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700188import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600189import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800190import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600191import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700192import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400193import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700194import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700195import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700196import android.util.ArrayMap;
197import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700198import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900199import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700200import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700201import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600202import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600203import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700204import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600205import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700206import android.util.SparseBooleanArray;
207import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900208import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210
Jeff Sharkey497e4432011-06-14 17:27:29 -0700211import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700212import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800213import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400214import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500215import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700216import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800217import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800218import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600219import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700221import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600222import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700223import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700224import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700225import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800226import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600227
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600228import libcore.io.IoUtils;
229
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231import org.xmlpull.v1.XmlSerializer;
232
233import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700234import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235import java.io.FileInputStream;
236import java.io.FileNotFoundException;
237import java.io.FileOutputStream;
238import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700239import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700240import java.lang.annotation.Retention;
241import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100242import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700243import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900244import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600245import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700246import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600247import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900248import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700249import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700250import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600251import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400252import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800253import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700256
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700257/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700258 * Service that maintains low-level network policy rules, using
259 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700260 * <p>
261 * Derives active rules by combining a given policy with other system status,
262 * and delivers to listeners, such as {@link ConnectivityManager}, for
263 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700264 *
265 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000266 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700267 * <ul>
268 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
269 * rules).
270 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
271 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000272 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
273 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700274 * </ul>
275 *
276 * <p>
277 * As such, methods that require synchronization have the following prefixes:
278 * <ul>
279 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
280 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000281 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
282 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700283 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700284 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700285public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700286 static final String TAG = NetworkPolicyLogger.TAG;
287 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
288 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900290 /**
291 * No opportunistic quota could be calculated from user data plan or data settings.
292 */
293 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
294
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700295 private static final int VERSION_INIT = 1;
296 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700297 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800298 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800299 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800300 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700301 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700302 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700303 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700304 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600305 private static final int VERSION_ADDED_CYCLE = 11;
306 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800308 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400309 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800310 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400311 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800312 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400313 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900314 @VisibleForTesting
315 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700316
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 private static final String TAG_POLICY_LIST = "policy-list";
318 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600319 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700321 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800322 private static final String TAG_WHITELIST = "whitelist";
323 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800324 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325
326 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700327 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700328 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
329 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700330 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600331 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
332 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
333 private static final String ATTR_CYCLE_START = "cycleStart";
334 private static final String ATTR_CYCLE_END = "cycleEnd";
335 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700336 private static final String ATTR_WARNING_BYTES = "warningBytes";
337 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700338 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800339 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
340 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800341 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700342 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700343 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700344 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600346 private static final String ATTR_SUB_ID = "subId";
347 private static final String ATTR_TITLE = "title";
348 private static final String ATTR_SUMMARY = "summary";
349 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
350 private static final String ATTR_USAGE_BYTES = "usageBytes";
351 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600352 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800354 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800355 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800356 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800357 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700358 private static final String ACTION_SNOOZE_RAPID =
359 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700360
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800361 /**
362 * Indicates the maximum wait time for admin data to be available;
363 */
364 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
365
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600366 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
367 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
368 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
369 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
370
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700371 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700372 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800373 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800374 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700375 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700376 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
377 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700378 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700379 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900380 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800381 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700382 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700383
Makoto Onuki8e777332017-03-28 11:25:47 -0700384 private static final int UID_MSG_STATE_CHANGED = 100;
385 private static final int UID_MSG_GONE = 101;
386
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600387 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
388
Jeff Sharkey75279902011-05-24 18:39:45 -0700389 private final Context mContext;
390 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700391 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700392 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700393 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700394 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700395 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700396 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397
398 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700399 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700400 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800401 @GuardedBy("mUidRulesFirstLock")
402 private PowerSaveState mRestrictBackgroundPowerState;
403
404 // Store the status of restrict background before turning on battery saver.
405 // Used to restore mRestrictBackground when battery saver is turned off.
406 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700407
Sudheer Shanka543339f2017-07-28 15:18:07 -0700408 // Denotes the status of restrict background read from disk.
409 private boolean mLoadedRestrictBackground;
410
Felipe Lemef0823852016-06-08 13:43:08 -0700411 // See main javadoc for instructions on how to use these locks.
412 final Object mUidRulesFirstLock = new Object();
413 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700414
Felipe Lemef0823852016-06-08 13:43:08 -0700415 @GuardedBy("allLocks") volatile boolean mSystemReady;
416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
418 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
419 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800420 // Store whether user flipped restrict background in battery saver mode
421 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700422
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700423 private final boolean mSuppressDefaultPolicy;
424
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800425 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
426
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700427 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600428 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800429 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700430
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600431 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600432 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600433 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600434 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600435 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600436 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600437
Jeff Sharkey9252b342018-01-19 07:58:35 +0900438 /** Map from subId to daily opportunistic quota. */
439 @GuardedBy("mNetworkPoliciesSecondLock")
440 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
441
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700442 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700443 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700444 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700445 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700446
Felipe Lemef0823852016-06-08 13:43:08 -0700447 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700448 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700449 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700450 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700451 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800452 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700453
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700454 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700456 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
457
Jeff Sharkey32566012014-12-02 18:30:14 -0800458 /**
459 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700460 * in power save mode, except device idle (doze) still applies.
461 * TODO: An int array might be sufficient
462 */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700464 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
465
466 /**
467 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800468 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700469 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800470 */
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700472 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700473
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700475 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
476
Felipe Lemeb85a6372016-01-14 16:16:16 -0800477 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800478 * UIDs that have been initially white-listed by system to avoid restricted background.
479 */
Felipe Lemef0823852016-06-08 13:43:08 -0700480 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800481 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
482 new SparseBooleanArray();
483
484 /**
485 * UIDs that have been initially white-listed by system to avoid restricted background,
486 * but later revoked by user.
487 */
Felipe Lemef0823852016-06-08 13:43:08 -0700488 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800489 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
490 new SparseBooleanArray();
491
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700492 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700493 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800494 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700495 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700496 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800497 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700498
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700499 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700500 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400501 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700502
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700503 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700504 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800505 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700506
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600507 /** Map from network ID to last observed meteredness state */
508 @GuardedBy("mNetworkPoliciesSecondLock")
509 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
510
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900511 /** Map from network ID to last observed roaming state */
512 @GuardedBy("mNetworkPoliciesSecondLock")
513 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
514
Jeff Sharkey9252b342018-01-19 07:58:35 +0900515 /** Map from netId to subId as of last update */
516 @GuardedBy("mNetworkPoliciesSecondLock")
517 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
518
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800519 /**
520 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
521 * userId to restricted uids which belong to that user.
522 */
523 @GuardedBy("mUidRulesFirstLock")
524 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
525
Jeff Sharkey32566012014-12-02 18:30:14 -0800526 private final RemoteCallbackList<INetworkPolicyListener>
527 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700528
Dianne Hackborn497175b2014-07-01 12:56:08 -0700529 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700530 @VisibleForTesting
531 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700532
533 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700534
Felipe Lemef0823852016-06-08 13:43:08 -0700535 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700536 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700537
Svet Ganov16a16892015-04-16 10:32:04 -0700538 private final AppOpsManager mAppOps;
539
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800540 private final IPackageManager mIPm;
541
Sudheer Shankae7361852017-03-07 11:51:46 -0800542 private ActivityManagerInternal mActivityManagerInternal;
543
Sudheer Shanka352dc572017-09-22 17:09:38 -0700544 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800545
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700546 // TODO: keep whitelist of system-critical services that should never have
547 // rules enforced, such as system, phone, and radio UIDs.
548
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700549 // TODO: migrate notifications to SystemUI
550
Jeff Sharkey75279902011-05-24 18:39:45 -0700551 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700552 INetworkManagementService networkManagement) {
553 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
554 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700555 }
556
Jeff Sharkey9911a282018-02-14 22:29:11 -0700557 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700558 return new File(Environment.getDataDirectory(), "system");
559 }
560
Jeff Sharkey9911a282018-02-14 22:29:11 -0700561 private static @NonNull Clock getDefaultClock() {
562 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
563 Clock.systemUTC());
564 }
565
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700566 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700567 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
568 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700569 mContext = checkNotNull(context, "missing context");
570 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700571 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700572 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700573 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700574 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700575 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700576 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700577 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700578
Amith Yamasani450a16b2013-09-18 16:28:50 -0700579 HandlerThread thread = new HandlerThread(TAG);
580 thread.start();
581 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700582
Makoto Onuki8e777332017-03-28 11:25:47 -0700583 // We create another thread for the UID events, which are more time-critical.
584 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
585 /*allowIo=*/ false);
586 mUidEventThread.start();
587 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
588
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700589 mSuppressDefaultPolicy = suppressDefaultPolicy;
590
Dianne Hackborne17b4452018-01-10 13:15:40 -0800591 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700592
593 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800594
Felipe Lemed17fda42016-04-29 11:12:45 -0700595 // Expose private service for system components to use.
596 LocalServices.addService(NetworkPolicyManagerInternal.class,
597 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700598 }
599
600 public void bindConnectivityManager(IConnectivityManager connManager) {
601 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700602 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700603
Felipe Lemef0823852016-06-08 13:43:08 -0700604 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700605 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700606 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
607 mPowerSaveWhitelistExceptIdleAppIds.clear();
608 if (whitelist != null) {
609 for (int uid : whitelist) {
610 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
611 }
612 }
613 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700614 mPowerSaveWhitelistAppIds.clear();
615 if (whitelist != null) {
616 for (int uid : whitelist) {
617 mPowerSaveWhitelistAppIds.put(uid, true);
618 }
619 }
620 } catch (RemoteException e) {
621 }
622 }
623
Felipe Lemea9505cc2016-02-26 10:28:41 -0800624 /**
625 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
626 * revoke the whitelist.
627 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700628 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800629 */
Felipe Lemef0823852016-06-08 13:43:08 -0700630 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800631 final List<UserInfo> users = mUserManager.getUsers();
632 final int numberUsers = users.size();
633
Felipe Lemea110eec2016-04-29 09:58:06 -0700634 boolean changed = false;
635 for (int i = 0; i < numberUsers; i++) {
636 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700637 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700638 }
639 return changed;
640 }
641
Felipe Lemef0823852016-06-08 13:43:08 -0700642 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700643 final SystemConfig sysConfig = SystemConfig.getInstance();
644 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800645 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
646 boolean changed = false;
647 for (int i = 0; i < allowDataUsage.size(); i++) {
648 final String pkg = allowDataUsage.valueAt(i);
649 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700650 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
651 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800652 final ApplicationInfo app;
653 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700654 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800655 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700656 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
657 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800658 continue;
659 }
660 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700661 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
662 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800663 continue;
664 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700665 final int uid = UserHandle.getUid(userId, app.uid);
666 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
667 if (LOGD)
668 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
669 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800670 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700671 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700672 if (LOGD)
673 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
674 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700675 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700676 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800677 }
678 }
679 return changed;
680 }
681
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800682 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700683 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800684 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700685 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800686 // Boost thread's priority during system server init
687 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700688 if (!isBandwidthControlEnabled()) {
689 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
690 return;
691 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700692
Felipe Leme873a83a2016-09-07 11:34:10 -0700693 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700694 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700695
Felipe Leme873a83a2016-09-07 11:34:10 -0700696 synchronized (mUidRulesFirstLock) {
697 synchronized (mNetworkPoliciesSecondLock) {
698 updatePowerSaveWhitelistUL();
699 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
700 mPowerManagerInternal.registerLowPowerModeObserver(
701 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800702 @Override
703 public int getServiceType() {
704 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700705 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800706
707 @Override
708 public void onLowPowerModeChanged(PowerSaveState result) {
709 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800710 if (LOGD) {
711 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
712 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800713 synchronized (mUidRulesFirstLock) {
714 if (mRestrictPower != enabled) {
715 mRestrictPower = enabled;
716 updateRulesForRestrictPowerUL();
717 }
718 }
719 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800720 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800721 mRestrictPower = mPowerManagerInternal.getLowPowerState(
722 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700723
724 mSystemReady = true;
725
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800726 waitForAdminData();
727
Felipe Leme873a83a2016-09-07 11:34:10 -0700728 // read policy from disk
729 readPolicyAL();
730
jackqdyulei29c82ab2017-03-10 14:09:16 -0800731 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700732 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800733 mRestrictBackgroundPowerState = mPowerManagerInternal
734 .getLowPowerState(ServiceType.DATA_SAVER);
735 final boolean localRestrictBackground =
736 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700737 if (localRestrictBackground && !mLoadedRestrictBackground) {
738 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800739 }
740 mPowerManagerInternal.registerLowPowerModeObserver(
741 new PowerManagerInternal.LowPowerModeListener() {
742 @Override
743 public int getServiceType() {
744 return ServiceType.DATA_SAVER;
745 }
746
747 @Override
748 public void onLowPowerModeChanged(PowerSaveState result) {
749 synchronized (mUidRulesFirstLock) {
750 updateRestrictBackgroundByLowPowerModeUL(result);
751 }
752 }
753 });
754
Felipe Leme873a83a2016-09-07 11:34:10 -0700755 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
756 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700757 }
Felipe Lemef0823852016-06-08 13:43:08 -0700758
Sudheer Shanka543339f2017-07-28 15:18:07 -0700759 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700760 updateRulesForGlobalChangeAL(false);
761 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700762 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800763 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700764
Sudheer Shankae7361852017-03-07 11:51:46 -0800765 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700766 try {
767 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000768 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800769 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700770 mNetworkManager.registerObserver(mAlertObserver);
771 } catch (RemoteException e) {
772 // ignored; both services live in system_server
773 }
774
775 // listen for changes to power save whitelist
776 final IntentFilter whitelistFilter = new IntentFilter(
777 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
778 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
779
Felipe Leme873a83a2016-09-07 11:34:10 -0700780 // watch for network interfaces to be claimed
781 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
782 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
783
784 // listen for package changes to update policy
785 final IntentFilter packageFilter = new IntentFilter();
786 packageFilter.addAction(ACTION_PACKAGE_ADDED);
787 packageFilter.addDataScheme("package");
788 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
789
790 // listen for UID changes to update policy
791 mContext.registerReceiver(
792 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
793
794 // listen for user changes to update policy
795 final IntentFilter userFilter = new IntentFilter();
796 userFilter.addAction(ACTION_USER_ADDED);
797 userFilter.addAction(ACTION_USER_REMOVED);
798 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
799
800 // listen for stats update events
801 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
802 mContext.registerReceiver(
803 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
804
805 // listen for restrict background changes from notifications
806 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
807 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
808
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700809 // Listen for snooze from notifications
810 mContext.registerReceiver(mSnoozeReceiver,
811 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
812 mContext.registerReceiver(mSnoozeReceiver,
813 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700814
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600815 // listen for configured wifi networks to be loaded
816 final IntentFilter wifiFilter =
817 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
818 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700819
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700820 // listen for carrier config changes to update data cycle information
821 final IntentFilter carrierConfigFilter = new IntentFilter(
822 ACTION_CARRIER_CONFIG_CHANGED);
823 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
824
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600825 // listen for meteredness changes
826 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
827 new NetworkRequest.Builder().build(), mNetworkCallback);
828
Felipe Leme873a83a2016-09-07 11:34:10 -0700829 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800830 // tell systemReady() that the service has been initialized
831 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700832 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800833 // Restore the default priority after init is done
834 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700835 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700836 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700837 }
838
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800839 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
840 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
841 mHandler.post(() -> initService(initCompleteSignal));
842 return initCompleteSignal;
843 }
844
845 public void systemReady(CountDownLatch initCompleteSignal) {
846 // wait for initService to complete
847 try {
848 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
849 throw new IllegalStateException("Service " + TAG +" init timeout");
850 }
851 } catch (InterruptedException e) {
852 Thread.currentThread().interrupt();
853 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
854 }
855 }
856
Sudheer Shankac9d94072017-02-22 22:13:55 +0000857 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700858 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700859 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
860 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700861 }
862
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700863 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700864 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700865 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700866
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700867 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700868 }
869
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700870 @Override public void onUidIdle(int uid, boolean disabled) {
871 }
872
873 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700874 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700875 };
876
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700877 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700878 @Override
879 public void onReceive(Context context, Intent intent) {
880 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700881 synchronized (mUidRulesFirstLock) {
882 updatePowerSaveWhitelistUL();
883 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700884 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700885 }
886 }
887 };
888
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700889 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700890 @Override
891 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700892 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700893
894 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700895 final int uid = intent.getIntExtra(EXTRA_UID, -1);
896 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700897
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700898 if (ACTION_PACKAGE_ADDED.equals(action)) {
899 // update rules for UID, since it might be subject to
900 // global background data policy
901 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700902 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700903 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700904 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700905 }
906 }
907 };
908
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700909 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700910 @Override
911 public void onReceive(Context context, Intent intent) {
912 // on background handler thread, and UID_REMOVED is protected
913
914 final int uid = intent.getIntExtra(EXTRA_UID, -1);
915 if (uid == -1) return;
916
917 // remove any policy and update rules to clean up
918 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700919 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700920 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700921 synchronized (mNetworkPoliciesSecondLock) {
922 writePolicyAL();
923 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700924 }
925 }
926 };
927
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700928 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700929 @Override
930 public void onReceive(Context context, Intent intent) {
931 // on background handler thread, and USER_ADDED and USER_REMOVED
932 // broadcasts are protected
933
934 final String action = intent.getAction();
935 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
936 if (userId == -1) return;
937
Amith Yamasani15e472352015-04-24 19:06:07 -0700938 switch (action) {
939 case ACTION_USER_REMOVED:
940 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700941 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800942 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700943 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700944 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800945 // Removing outside removeUserStateUL since that can also be called when
946 // user resets app preferences.
947 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700948 if (action == ACTION_USER_ADDED) {
949 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700950 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700951 }
952 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700953 synchronized (mNetworkPoliciesSecondLock) {
954 updateRulesForGlobalChangeAL(true);
955 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700956 }
957 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700958 }
959 }
960 };
961
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700962 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 * Receiver that watches for {@link INetworkStatsService} updates, which we
964 * use to check against {@link NetworkPolicy#warningBytes}.
965 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700966 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700967 @Override
968 public void onReceive(Context context, Intent intent) {
969 // on background handler thread, and verified
970 // READ_NETWORK_USAGE_HISTORY permission above.
971
Felipe Lemef0823852016-06-08 13:43:08 -0700972 synchronized (mNetworkPoliciesSecondLock) {
973 updateNetworkEnabledNL();
974 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700975 }
976 }
977 };
978
979 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700980 * Receiver that watches for {@link Notification} control of
981 * {@link #mRestrictBackground}.
982 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700983 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700984 @Override
985 public void onReceive(Context context, Intent intent) {
986 // on background handler thread, and verified MANAGE_NETWORK_POLICY
987 // permission above.
988
989 setRestrictBackground(false);
990 }
991 };
992
993 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800994 * Receiver that watches for {@link Notification} control of
995 * {@link NetworkPolicy#lastWarningSnooze}.
996 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700997 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800998 @Override
999 public void onReceive(Context context, Intent intent) {
1000 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1001 // permission above.
1002
1003 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001004 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1005 performSnooze(template, TYPE_WARNING);
1006 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1007 performSnooze(template, TYPE_RAPID);
1008 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001009 }
1010 };
1011
1012 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001013 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001014 * we can perform upgrade logic. After initial upgrade logic, it updates
1015 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001016 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001017 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001018 @Override
1019 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001020 synchronized (mUidRulesFirstLock) {
1021 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001022 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001023 }
1024 }
1025 // Only need to perform upgrade logic once
1026 mContext.unregisterReceiver(this);
1027 }
1028 };
1029
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001030 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1031 Network network) {
1032 final boolean lastValue = lastValues.get(network.netId, false);
1033 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1034 if (changed) {
1035 lastValues.put(network.netId, newValue);
1036 }
1037 return changed;
1038 }
1039
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001040 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1041 @Override
1042 public void onCapabilitiesChanged(Network network,
1043 NetworkCapabilities networkCapabilities) {
1044 if (network == null || networkCapabilities == null) return;
1045
1046 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001047 final boolean newMetered = !networkCapabilities
1048 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001049 final boolean meteredChanged = updateCapabilityChange(
1050 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001051
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001052 final boolean newRoaming = !networkCapabilities
1053 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1054 final boolean roamingChanged = updateCapabilityChange(
1055 mNetworkRoaming, newRoaming, network);
1056
1057 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001058 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001059 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001060 }
1061 }
1062 }
1063 };
1064
1065 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 * Observer that watches for {@link INetworkManagementService} alerts.
1067 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001068 final private INetworkManagementEventObserver mAlertObserver
1069 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 @Override
1071 public void limitReached(String limitName, String iface) {
1072 // only someone like NMS should be calling us
1073 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1074
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001075 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1076 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 }
1078 }
1079 };
1080
1081 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1083 * to show visible notifications as needed.
1084 */
Felipe Lemef0823852016-06-08 13:43:08 -07001085 void updateNotificationsNL() {
1086 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001088 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001089 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001090 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001091
1092 // TODO: when switching to kernel notifications, compute next future
1093 // cycle boundary to recompute notifications.
1094
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001095 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001096 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001097 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1098 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001099 final int subId = findRelevantSubId(policy.template);
1100
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001101 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001102 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001103 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001104
Jeff Sharkey53313d72017-07-13 16:47:32 -06001105 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1106 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001107 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1108 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1109 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001110
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001111 // Carrier might want to manage notifications themselves
1112 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1113 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1114 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1115 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1116 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1117 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1118 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1119
1120 // Notify when data usage is over warning
1121 if (notifyWarning) {
1122 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1123 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1124 if (!snoozedThisCycle) {
1125 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1126 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001128 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001130 // Notify when data usage is over limit
1131 if (notifyLimit) {
1132 if (policy.isOverLimit(totalBytes)) {
1133 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1134 if (snoozedThisCycle) {
1135 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1136 } else {
1137 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1138 notifyOverLimitNL(policy.template);
1139 }
1140 } else {
1141 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142 }
1143 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001144
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001145 // Warn if average usage over last 4 days is on track to blow pretty
1146 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001147 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001148 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001149 final long recentStart = now - recentDuration;
1150 final long recentEnd = now;
1151 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001152
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001153 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001154 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001155 final long alertBytes = (policy.limitBytes * 3) / 2;
1156
1157 if (LOGD) {
1158 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1159 + projectedBytes + " alert " + alertBytes);
1160 }
1161
1162 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1163 - DateUtils.DAY_IN_MILLIS;
1164 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001165 enqueueNotification(policy, TYPE_RAPID, 0,
1166 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001167 }
1168 }
1169 }
1170
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001171 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001172 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001173 final NotificationId notificationId = beforeNotifs.valueAt(i);
1174 if (!mActiveNotifs.contains(notificationId)) {
1175 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001176 }
1177 }
1178 }
1179
1180 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001181 * Attempt to find a specific app to blame for rapid data usage during the
1182 * given time period.
1183 */
1184 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1185 long start, long end) {
1186 long totalBytes = 0;
1187 long maxBytes = 0;
1188 int maxUid = 0;
1189
1190 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1191 NetworkStats.Entry entry = null;
1192 for (int i = 0; i < stats.size(); i++) {
1193 entry = stats.getValues(i, entry);
1194 final long bytes = entry.rxBytes + entry.txBytes;
1195 totalBytes += bytes;
1196 if (bytes > maxBytes) {
1197 maxBytes = bytes;
1198 maxUid = entry.uid;
1199 }
1200 }
1201
1202 // Only point blame if the majority of usage was done by a single app.
1203 // TODO: support shared UIDs
1204 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1205 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001206 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001207 try {
1208 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1209 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1210 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1211 } catch (NameNotFoundException ignored) {
1212 }
1213 }
1214 }
1215
1216 return null;
1217 }
1218
1219 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001220 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001221 * current device state, such as when
1222 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1223 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001224 *
1225 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1226 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227 */
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001228 private int findRelevantSubId(NetworkTemplate template) {
1229 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1230 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001231
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001232 // Mobile template is relevant when any active subscriber matches
1233 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
1234 for (int subId : subIds) {
1235 final String subscriberId = tele.getSubscriberId(subId);
1236 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1237 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1238 true);
1239 if (template.matches(probeIdent)) {
1240 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001241 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001242 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001243 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001244 }
1245
1246 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001247 * Notify that given {@link NetworkTemplate} is over
1248 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1249 */
Felipe Lemef0823852016-06-08 13:43:08 -07001250 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001251 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001252 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001253 mOverLimitNotified.add(template);
1254 }
1255 }
1256
Felipe Lemef0823852016-06-08 13:43:08 -07001257 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001258 mOverLimitNotified.remove(template);
1259 }
1260
1261 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001262 * Show notification for combined {@link NetworkPolicy} and specific type,
1263 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1264 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001265 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1266 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001267 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001268 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001269 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001270 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001271 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001272 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001273 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001274
1275 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001276 final CharSequence title;
1277 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001278 switch (type) {
1279 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001280 title = res.getText(R.string.data_usage_warning_title);
1281 body = res.getString(R.string.data_usage_warning_body,
1282 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001283
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001284 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001285
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001286 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1287 builder.setDeleteIntent(PendingIntent.getBroadcast(
1288 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1289
Wei Liu546cb772016-07-21 16:19:01 -07001290 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001291 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001292 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1293
Jeff Sharkey497e4432011-06-14 17:27:29 -07001294 break;
1295 }
1296 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001297 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001298 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001299 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001300 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001301 case MATCH_WIFI:
1302 title = res.getText(R.string.data_usage_wifi_limit_title);
1303 break;
1304 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001305 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001306 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001307 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001308
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001309 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001310 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001311
Wei Liu546cb772016-07-21 16:19:01 -07001312 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001313 builder.setContentIntent(PendingIntent.getActivity(
1314 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1315 break;
1316 }
1317 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001318 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001319 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001320 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1321 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001322 case MATCH_WIFI:
1323 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1324 break;
1325 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001326 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001327 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001328 final long overBytes = totalBytes - policy.limitBytes;
1329 body = res.getString(R.string.data_usage_limit_snoozed_body,
1330 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001331
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001332 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001333 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001334 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001335
Wei Liu546cb772016-07-21 16:19:01 -07001336 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001337 builder.setContentIntent(PendingIntent.getActivity(
1338 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001339 break;
1340 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001341 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001342 title = res.getText(R.string.data_usage_rapid_title);
1343 if (rapidBlame != null) {
1344 body = res.getString(R.string.data_usage_rapid_app_body,
1345 rapidBlame.loadLabel(mContext.getPackageManager()));
1346 } else {
1347 body = res.getString(R.string.data_usage_rapid_body);
1348 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001349
Jeff Sharkey2e471452018-01-19 18:02:47 +09001350 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001351
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001352 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1353 builder.setDeleteIntent(PendingIntent.getBroadcast(
1354 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1355
1356 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001357 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001358 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001359 break;
1360 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001361 default: {
1362 return;
1363 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001364 }
1365
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001366 builder.setTicker(title);
1367 builder.setContentTitle(title);
1368 builder.setContentText(body);
1369 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001370
1371 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1372 notificationId.getId(), builder.build(), UserHandle.ALL);
1373 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001374 }
1375
Chris Wren193ae6b2017-03-31 15:17:11 -04001376 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001377 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1378 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001379 }
1380
1381 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001382 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001383 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001384 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001385 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001386 @Override
1387 public void onReceive(Context context, Intent intent) {
1388 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1389 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001390
Hugo Benichi446c9c92017-04-10 09:41:10 +09001391 synchronized (mUidRulesFirstLock) {
1392 synchronized (mNetworkPoliciesSecondLock) {
1393 ensureActiveMobilePolicyAL();
1394 normalizePoliciesNL();
1395 updateNetworkEnabledNL();
1396 updateNetworkRulesNL();
1397 updateNotificationsNL();
1398 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399 }
1400 }
1401 };
1402
Jeff Sharkey2e471452018-01-19 18:02:47 +09001403 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001404 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001405 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001406 final CountDownLatch latch = new CountDownLatch(1);
1407 mHandler.post(() -> {
1408 latch.countDown();
1409 });
1410 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001411 }
1412
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001413 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001414 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1415 * if necessary.
1416 *
1417 * @param subId that has its associated NetworkPolicy updated if necessary
1418 * @return if any policies were updated
1419 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001420 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1421 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001422
1423 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001424 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1425 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001426
1427 // find and update the mobile NetworkPolicy for this subscriber id
1428 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001429 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001430 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1431 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1432 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001433 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1434 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001435 }
1436 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001437 return policyUpdated;
1438 }
1439
1440 /**
1441 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1442 *
1443 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1444 * to do so, it returns the fallback value.
1445 *
1446 * @param config The CarrierConfig to read the value from.
1447 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1448 * @return cycleDay to use in the mobile NetworkPolicy.
1449 */
1450 @VisibleForTesting
1451 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1452 int fallbackCycleDay) {
1453 if (config == null) {
1454 return fallbackCycleDay;
1455 }
1456 int cycleDay =
1457 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1458 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1459 return fallbackCycleDay;
1460 }
1461 // validate cycleDay value
1462 final Calendar cal = Calendar.getInstance();
1463 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1464 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1465 Slog.e(TAG, "Invalid date in "
1466 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1467 return fallbackCycleDay;
1468 }
1469 return cycleDay;
1470 }
1471
1472 /**
1473 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1474 *
1475 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1476 * to do so, it returns the fallback value.
1477 *
1478 * @param config The CarrierConfig to read the value from.
1479 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1480 * @return warningBytes to use in the mobile NetworkPolicy.
1481 */
1482 @VisibleForTesting
1483 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1484 long fallbackWarningBytes) {
1485 if (config == null) {
1486 return fallbackWarningBytes;
1487 }
1488 long warningBytes =
1489 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1490
1491 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1492 return WARNING_DISABLED;
1493 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1494 return getPlatformDefaultWarningBytes();
1495 } else if (warningBytes < 0) {
1496 Slog.e(TAG, "Invalid value in "
1497 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1498 + "non-negative value but got: " + warningBytes);
1499 return fallbackWarningBytes;
1500 }
1501
1502 return warningBytes;
1503 }
1504
1505 /**
1506 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1507 *
1508 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1509 * to do so, it returns the fallback value.
1510 *
1511 * @param config The CarrierConfig to read the value from.
1512 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1513 * @return limitBytes to use in the mobile NetworkPolicy.
1514 */
1515 @VisibleForTesting
1516 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1517 long fallbackLimitBytes) {
1518 if (config == null) {
1519 return fallbackLimitBytes;
1520 }
1521 long limitBytes =
1522 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1523
1524 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1525 return LIMIT_DISABLED;
1526 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1527 return getPlatformDefaultLimitBytes();
1528 } else if (limitBytes < 0) {
1529 Slog.e(TAG, "Invalid value in "
1530 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1531 + "non-negative value but got: " + limitBytes);
1532 return fallbackLimitBytes;
1533 }
1534 return limitBytes;
1535 }
1536
1537 /**
1538 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1539 */
1540 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1541 @Override
1542 public void onReceive(Context context, Intent intent) {
1543 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1544 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1545
1546 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1547 return;
1548 }
1549 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001550 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001551 final String subscriberId = tele.getSubscriberId(subId);
1552
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001553 synchronized (mUidRulesFirstLock) {
1554 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001555 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001556 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001557 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001558 if (!updated) return;
1559 // update network and notification rules, as the data cycle changed and it's
1560 // possible that we should be triggering warnings/limits now
1561 handleNetworkPoliciesUpdateAL(true);
1562 }
1563 }
1564 }
1565 };
1566
1567 /**
1568 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1569 * one has been updated.
1570 *
1571 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1572 * update.
1573 */
1574 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1575 if (shouldNormalizePolicies) {
1576 normalizePoliciesNL();
1577 }
1578 updateNetworkEnabledNL();
1579 updateNetworkRulesNL();
1580 updateNotificationsNL();
1581 writePolicyAL();
1582 }
1583
1584 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001585 * Proactively control network data connections when they exceed
1586 * {@link NetworkPolicy#limitBytes}.
1587 */
Felipe Lemef0823852016-06-08 13:43:08 -07001588 void updateNetworkEnabledNL() {
1589 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001590
1591 // TODO: reset any policy-disabled networks when any policy is removed
1592 // completely, which is currently rare case.
1593
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001594 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1595 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001596 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001597 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001598 setNetworkTemplateEnabled(policy.template, true);
1599 continue;
1600 }
1601
Jeff Sharkey53313d72017-07-13 16:47:32 -06001602 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1603 .cycleIterator(policy).next();
1604 final long start = cycle.first.toInstant().toEpochMilli();
1605 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001606 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001607
1608 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001609 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1610 && policy.lastLimitSnooze < start;
1611 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001612
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001613 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001614 }
1615 }
1616
1617 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001618 * Proactively disable networks that match the given
1619 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001620 */
1621 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001622 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1623 // held. Call it via the handler.
1624 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1625 .sendToTarget();
1626 }
1627
1628 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001629 // TODO: reach into ConnectivityManager to proactively disable bringing
1630 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001631
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001632 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001633 // If mobile data usage hits the limit or if the user resumes the data, we need to
1634 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001635 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1636 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001637
Jeff Sharkey2e471452018-01-19 18:02:47 +09001638 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001639 for (int subId : subIds) {
1640 final String subscriberId = tm.getSubscriberId(subId);
1641 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001642 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1643 true);
Jack Yu8781b682016-07-08 14:28:51 -07001644 // Template is matched when subscriber id matches.
1645 if (template.matches(probeIdent)) {
1646 tm.setPolicyDataEnabled(enabled, subId);
1647 }
1648 }
1649 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001650 }
1651
1652 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001653 * Collect all ifaces from a {@link NetworkState} into the given set.
1654 */
1655 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1656 final String baseIface = state.linkProperties.getInterfaceName();
1657 if (baseIface != null) {
1658 ifaces.add(baseIface);
1659 }
1660 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1661 final String stackedIface = stackedLink.getInterfaceName();
1662 if (stackedIface != null) {
1663 ifaces.add(stackedIface);
1664 }
1665 }
1666 }
1667
1668 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 * Examine all connected {@link NetworkState}, looking for
1670 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1671 * remaining quota based on usage cycle and historical stats.
1672 */
Felipe Lemef0823852016-06-08 13:43:08 -07001673 void updateNetworkRulesNL() {
1674 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001675
1676 final NetworkState[] states;
1677 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001678 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001679 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001680 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001681 return;
1682 }
1683
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001684 // First, generate identities of all connected networks so we can
1685 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001686 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001687 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001688 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001689 if (state.network != null) {
1690 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1691 }
Wei Liub8eaf452016-01-25 10:32:27 -08001692 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001693 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1694 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001695 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001696 }
1697 }
1698
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001699 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001700 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001701
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001702 // For every well-defined policy, compute remaining data based on
1703 // current cycle and historical stats, and push to kernel.
1704 final ArraySet<String> matchingIfaces = new ArraySet<>();
1705 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1706 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1707
1708 // Collect all ifaces that match this policy
1709 matchingIfaces.clear();
1710 for (int j = identified.size() - 1; j >= 0; j--) {
1711 if (policy.template.matches(identified.valueAt(j))) {
1712 collectIfaces(matchingIfaces, identified.keyAt(j));
1713 }
1714 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001715
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001717 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001718 }
1719
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001720 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001721 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001722 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001723 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001724 if (hasLimit && policy.hasCycle()) {
1725 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1726 .cycleIterator(policy).next();
1727 final long start = cycle.first.toInstant().toEpochMilli();
1728 final long end = cycle.second.toInstant().toEpochMilli();
1729 final long totalBytes = getTotalBytes(policy.template, start, end);
1730
1731 if (policy.lastLimitSnooze >= start) {
1732 // snoozing past quota, but we still need to restrict apps,
1733 // so push really high quota.
1734 quotaBytes = Long.MAX_VALUE;
1735 } else {
1736 // remaining "quota" bytes are based on total usage in
1737 // current cycle. kernel doesn't like 0-byte rules, so we
1738 // set 1-byte quota and disable the radio later.
1739 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1740 }
1741 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001742 // metered network, but no policy limit; we still need to
1743 // restrict apps, so push really high quota.
1744 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001745 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001746
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001747 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001748 // TODO: switch to shared quota once NMS supports
1749 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001750 }
1751
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001752 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1753 final String iface = matchingIfaces.valueAt(j);
1754 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001755 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001756 }
1757 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001758
1759 // keep track of lowest warning or limit of active policies
1760 if (hasWarning && policy.warningBytes < lowestRule) {
1761 lowestRule = policy.warningBytes;
1762 }
1763 if (hasLimit && policy.limitBytes < lowestRule) {
1764 lowestRule = policy.limitBytes;
1765 }
1766 }
1767
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001768 // One final pass to catch any metered ifaces that don't have explicitly
1769 // defined policies; typically Wi-Fi networks.
1770 for (NetworkState state : states) {
1771 if (state.networkInfo != null && state.networkInfo.isConnected()
1772 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1773 matchingIfaces.clear();
1774 collectIfaces(matchingIfaces, state);
1775 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1776 final String iface = matchingIfaces.valueAt(j);
1777 if (!newMeteredIfaces.contains(iface)) {
1778 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1779 newMeteredIfaces.add(iface);
1780 }
1781 }
1782 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001783 }
1784
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001785 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001786 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1787 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001788 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001789 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001790 }
1791 }
1792 mMeteredIfaces = newMeteredIfaces;
1793
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001794 final ContentResolver cr = mContext.getContentResolver();
1795 final boolean quotaEnabled = Settings.Global.getInt(cr,
1796 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1797 final long quotaUnlimited = Settings.Global.getLong(cr,
1798 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1799 final float quotaLimited = Settings.Global.getFloat(cr,
1800 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1801
Jeff Sharkey9252b342018-01-19 07:58:35 +09001802 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001803 mSubscriptionOpportunisticQuota.clear();
1804 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001805 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001806 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001807 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001808 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001809 if (plan == null) continue;
1810
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001811 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001812 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001813 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1814 // Clamp to 0 when roaming
1815 quotaBytes = 0;
1816 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001817 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001818 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001819 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001820 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001821 } else {
1822 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001823 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1824 final long start = cycle.getLower().toInstant().toEpochMilli();
1825 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001826 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001827 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001828 .truncatedTo(ChronoUnit.DAYS)
1829 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001830 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001831 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1832 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001833 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001834 // Number of remaining days including current day
1835 final long remainingDays =
1836 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001837
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001838 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001839 }
1840
1841 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1842 }
1843
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001844 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001845 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001846
1847 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001848 }
1849
1850 /**
1851 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1852 * have at least a default mobile policy defined.
1853 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001854 private void ensureActiveMobilePolicyAL() {
1855 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001856 if (mSuppressDefaultPolicy) return;
1857
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001858 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1859 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001860
Jeff Sharkey2e471452018-01-19 18:02:47 +09001861 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001862 for (int subId : subIds) {
1863 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001864 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001865 }
1866 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001867
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001868 /**
1869 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1870 * have at least a default mobile policy defined.
1871 *
1872 * @param subId to build a default policy for
1873 * @param subscriberId that we check for an existing policy
1874 * @return true if a mobile network policy was added, or false one already existed.
1875 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001876 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001877 // Poke around to see if we already have a policy
1878 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001879 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001880 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1881 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1882 if (template.matches(probeIdent)) {
1883 if (LOGD) {
1884 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1885 + NetworkIdentity.scrubSubscriberId(subscriberId));
1886 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001887 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001888 }
1889 }
1890
Jeff Sharkey32566012014-12-02 18:30:14 -08001891 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1892 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001893 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001894 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001895 return true;
1896 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001897
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001898 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001899 final int dataWarningConfig = mContext.getResources().getInteger(
1900 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001901 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001902 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001903 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001904 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001905 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001906 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001907
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001908 private long getPlatformDefaultLimitBytes() {
1909 return LIMIT_DISABLED;
1910 }
1911
1912 @VisibleForTesting
1913 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001914 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001915 final RecurrenceRule cycleRule = NetworkPolicy
1916 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001917 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001918 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1919 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1920 synchronized (mUidRulesFirstLock) {
1921 synchronized (mNetworkPoliciesSecondLock) {
1922 updateDefaultMobilePolicyAL(subId, policy);
1923 }
1924 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001925 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001926 }
1927
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001928 /**
1929 * Update the given {@link NetworkPolicy} based on any carrier-provided
1930 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1931 * Leaves policy untouched if the user has modified it.
1932 *
1933 * @return if the policy was modified
1934 */
1935 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1936 if (!policy.inferred) {
1937 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1938 return false;
1939 }
1940
1941 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1942 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1943 policy.lastLimitSnooze, policy.metered, policy.inferred);
1944
1945 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1946 if (!ArrayUtils.isEmpty(plans)) {
1947 final SubscriptionPlan plan = plans[0];
1948 policy.cycleRule = plan.getCycleRule();
1949 final long planLimitBytes = plan.getDataLimitBytes();
1950 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1951 policy.warningBytes = getPlatformDefaultWarningBytes();
1952 policy.limitBytes = getPlatformDefaultLimitBytes();
1953 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1954 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1955 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1956 } else {
1957 policy.warningBytes = (planLimitBytes * 9) / 10;
1958 switch (plan.getDataLimitBehavior()) {
1959 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1960 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1961 policy.limitBytes = planLimitBytes;
1962 break;
1963 default:
1964 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1965 break;
1966 }
1967 }
1968 } else {
1969 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1970 final int currentCycleDay;
1971 if (policy.cycleRule.isMonthly()) {
1972 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1973 } else {
1974 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1975 }
1976 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1977 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1978 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1979 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1980 }
1981
1982 if (policy.equals(original)) {
1983 return false;
1984 } else {
1985 Slog.d(TAG, "Updated " + original + " to " + policy);
1986 return true;
1987 }
1988 }
1989
Felipe Lemef0823852016-06-08 13:43:08 -07001990 private void readPolicyAL() {
1991 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001992
1993 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001994 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001995 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001996 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001997 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998
1999 FileInputStream fis = null;
2000 try {
2001 fis = mPolicyFile.openRead();
2002 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002003 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002004
Felipe Leme46b451f2016-08-19 08:46:17 -07002005 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2006 // to skip UIDs that were explicitly blacklisted.
2007 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2008
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002009 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002010 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002011 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002012 while ((type = in.next()) != END_DOCUMENT) {
2013 final String tag = in.getName();
2014 if (type == START_TAG) {
2015 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002016 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002017 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002018 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2019 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2021 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2022 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002023 final String networkId;
2024 if (version >= VERSION_ADDED_NETWORK_ID) {
2025 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2026 } else {
2027 networkId = null;
2028 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002029 final RecurrenceRule cycleRule;
2030 if (version >= VERSION_ADDED_CYCLE) {
2031 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2032 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2033 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2034 cycleRule = new RecurrenceRule(
2035 RecurrenceRule.convertZonedDateTime(start),
2036 RecurrenceRule.convertZonedDateTime(end),
2037 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002038 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002039 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2040 final String cycleTimezone;
2041 if (version >= VERSION_ADDED_TIMEZONE) {
2042 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2043 } else {
2044 cycleTimezone = "UTC";
2045 }
2046 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002047 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2049 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002050 final long lastLimitSnooze;
2051 if (version >= VERSION_SPLIT_SNOOZE) {
2052 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2053 } else if (version >= VERSION_ADDED_SNOOZE) {
2054 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002055 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002056 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002057 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002058 final boolean metered;
2059 if (version >= VERSION_ADDED_METERED) {
2060 metered = readBooleanAttribute(in, ATTR_METERED);
2061 } else {
2062 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002063 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002064 metered = true;
2065 break;
2066 default:
2067 metered = false;
2068 }
2069 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002070 final long lastWarningSnooze;
2071 if (version >= VERSION_SPLIT_SNOOZE) {
2072 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2073 } else {
2074 lastWarningSnooze = SNOOZE_NEVER;
2075 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002076 final boolean inferred;
2077 if (version >= VERSION_ADDED_INFERRED) {
2078 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2079 } else {
2080 inferred = false;
2081 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002082
Jeff Sharkey32566012014-12-02 18:30:14 -08002083 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2084 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002085 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002086 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2087 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002088 lastLimitSnooze, metered, inferred));
2089 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002090
2091 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2092 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2093 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2094 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2095 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2096 RecurrenceRule.convertZonedDateTime(start),
2097 RecurrenceRule.convertZonedDateTime(end),
2098 RecurrenceRule.convertPeriod(period));
2099 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2100 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2101
2102 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2103 SubscriptionPlan.BYTES_UNKNOWN);
2104 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2105 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2106 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2107 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2108 builder.setDataLimit(limitBytes, limitBehavior);
2109 }
2110
2111 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2112 SubscriptionPlan.BYTES_UNKNOWN);
2113 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2114 SubscriptionPlan.TIME_UNKNOWN);
2115 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2116 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2117 builder.setDataUsage(usageBytes, usageTime);
2118 }
2119
2120 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2121 final SubscriptionPlan plan = builder.build();
2122 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2123 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2124
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002125 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2126 mSubscriptionPlansOwner.put(subId, ownerPackage);
2127
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002128 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002129 final int uid = readIntAttribute(in, ATTR_UID);
2130 final int policy = readIntAttribute(in, ATTR_POLICY);
2131
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002132 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002133 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002134 } else {
2135 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2136 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002137 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002138 final int appId = readIntAttribute(in, ATTR_APP_ID);
2139 final int policy = readIntAttribute(in, ATTR_POLICY);
2140
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002141 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002142 // app policy is deprecated so this is only used in pre system user split.
2143 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002144 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002145 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002146 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002147 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002148 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002149 } else if (TAG_WHITELIST.equals(tag)) {
2150 insideWhitelist = true;
2151 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2152 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002153 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002154 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2155 final int uid = readIntAttribute(in, ATTR_UID);
2156 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002157 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002158 } else if (type == END_TAG) {
2159 if (TAG_WHITELIST.equals(tag)) {
2160 insideWhitelist = false;
2161 }
2162
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002163 }
2164 }
2165
Felipe Leme46b451f2016-08-19 08:46:17 -07002166 final int size = whitelistedRestrictBackground.size();
2167 for (int i = 0; i < size; i++) {
2168 final int uid = whitelistedRestrictBackground.keyAt(i);
2169 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2170 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2171 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2172 + " because its policy is " + uidPoliciesToString(policy));
2173 continue;
2174 }
2175 if (UserHandle.isApp(uid)) {
2176 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2177 if (LOGV)
2178 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2179 setUidPolicyUncheckedUL(uid, newPolicy, false);
2180 } else {
2181 Slog.w(TAG, "unable to update policy on UID " + uid);
2182 }
2183 }
2184
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002185 } catch (FileNotFoundException e) {
2186 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002187 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002188 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002189 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002190 } finally {
2191 IoUtils.closeQuietly(fis);
2192 }
2193 }
2194
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002195 /**
2196 * Upgrade legacy background data flags, notifying listeners of one last
2197 * change to always-true.
2198 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002199 private void upgradeDefaultBackgroundDataUL() {
2200 // This method is only called when we're unable to find the network policy flag, which
2201 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002202
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002203 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002204 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002205 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2206
2207 // NOTE: We used to read the legacy setting here :
2208 //
2209 // final int legacyFlagValue = Settings.Secure.getInt(
2210 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2211 //
2212 // This is no longer necessary because we will never upgrade directly from Gingerbread
2213 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2214 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002215 }
2216
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002217 /**
2218 * Perform upgrade step of moving any user-defined meterness overrides over
2219 * into {@link WifiConfiguration}.
2220 */
2221 private void upgradeWifiMeteredOverrideAL() {
2222 boolean modified = false;
2223 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2224 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2225 for (int i = 0; i < mNetworkPolicy.size(); ) {
2226 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2227 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2228 && !policy.inferred) {
2229 mNetworkPolicy.removeAt(i);
2230 modified = true;
2231
2232 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2233 for (WifiConfiguration config : configs) {
2234 if (Objects.equals(resolveNetworkId(config), networkId)) {
2235 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2236 config.meteredOverride = policy.metered
2237 ? WifiConfiguration.METERED_OVERRIDE_METERED
2238 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2239 wm.updateNetwork(config);
2240 }
2241 }
2242 } else {
2243 i++;
2244 }
2245 }
2246 if (modified) {
2247 writePolicyAL();
2248 }
2249 }
2250
Felipe Lemef0823852016-06-08 13:43:08 -07002251 void writePolicyAL() {
2252 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002253
2254 FileOutputStream fos = null;
2255 try {
2256 fos = mPolicyFile.startWrite();
2257
2258 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002259 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002260 out.startDocument(null, true);
2261
2262 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002263 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002264 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002265
2266 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002267 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2268 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002269 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002270 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002271
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002272 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002273 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2274 final String subscriberId = template.getSubscriberId();
2275 if (subscriberId != null) {
2276 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002277 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002278 final String networkId = template.getNetworkId();
2279 if (networkId != null) {
2280 out.attribute(null, ATTR_NETWORK_ID, networkId);
2281 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002282 writeStringAttribute(out, ATTR_CYCLE_START,
2283 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2284 writeStringAttribute(out, ATTR_CYCLE_END,
2285 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2286 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2287 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002288 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2289 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002290 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2291 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002292 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002293 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002294 out.endTag(null, TAG_NETWORK_POLICY);
2295 }
2296
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002297 // write all known subscription plans
2298 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2299 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002300 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002301 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2302 if (ArrayUtils.isEmpty(plans)) continue;
2303
2304 for (SubscriptionPlan plan : plans) {
2305 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2306 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002307 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002308 final RecurrenceRule cycleRule = plan.getCycleRule();
2309 writeStringAttribute(out, ATTR_CYCLE_START,
2310 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2311 writeStringAttribute(out, ATTR_CYCLE_END,
2312 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2313 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2314 RecurrenceRule.convertPeriod(cycleRule.period));
2315 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2316 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2317 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2318 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2319 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2320 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2321 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2322 }
2323 }
2324
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002325 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002326 for (int i = 0; i < mUidPolicy.size(); i++) {
2327 final int uid = mUidPolicy.keyAt(i);
2328 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002329
Jeff Sharkey497e4432011-06-14 17:27:29 -07002330 // skip writing empty policies
2331 if (policy == POLICY_NONE) continue;
2332
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002333 out.startTag(null, TAG_UID_POLICY);
2334 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002335 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002336 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002337 }
2338
2339 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002340
2341 // write all whitelists
2342 out.startTag(null, TAG_WHITELIST);
2343
Felipe Lemea9505cc2016-02-26 10:28:41 -08002344 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002345 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002346 for (int i = 0; i < size; i++) {
2347 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2348 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2349 writeIntAttribute(out, ATTR_UID, uid);
2350 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2351 }
2352
Felipe Lemeb85a6372016-01-14 16:16:16 -08002353 out.endTag(null, TAG_WHITELIST);
2354
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002355 out.endDocument();
2356
2357 mPolicyFile.finishWrite(fos);
2358 } catch (IOException e) {
2359 if (fos != null) {
2360 mPolicyFile.failWrite(fos);
2361 }
2362 }
2363 }
2364
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002365 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002366 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002367 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002368
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002369 if (!UserHandle.isApp(uid)) {
2370 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002371 }
Felipe Lemef0823852016-06-08 13:43:08 -07002372 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002373 final long token = Binder.clearCallingIdentity();
2374 try {
2375 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2376 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002377 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002378 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002379 }
2380 } finally {
2381 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002382 }
2383 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002384 }
2385
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002386 @Override
2387 public void addUidPolicy(int uid, int policy) {
2388 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002389
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002390 if (!UserHandle.isApp(uid)) {
2391 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2392 }
2393
Felipe Lemef0823852016-06-08 13:43:08 -07002394 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002395 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2396 policy |= oldPolicy;
2397 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002398 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002399 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002400 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002401 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002402 }
2403
2404 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002405 public void removeUidPolicy(int uid, int policy) {
2406 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2407
2408 if (!UserHandle.isApp(uid)) {
2409 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2410 }
2411
Felipe Lemef0823852016-06-08 13:43:08 -07002412 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002413 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2414 policy = oldPolicy & ~policy;
2415 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002416 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002417 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002418 }
2419 }
2420 }
2421
Felipe Lemef0823852016-06-08 13:43:08 -07002422 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002423 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002424
Felipe Leme57e3d312016-08-23 14:42:52 -07002425 final boolean notifyApp;
2426 if (!isUidValidForWhitelistRules(uid)) {
2427 notifyApp = false;
2428 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002429 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2430 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2431 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2432 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002433 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2434 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002435 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2436 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2437 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2438 if (LOGD)
2439 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2440 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2441 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002442 notifyApp = wasBlocked != isBlocked;
2443 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002444 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2445 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002446 if (persist) {
2447 synchronized (mNetworkPoliciesSecondLock) {
2448 writePolicyAL();
2449 }
2450 }
Felipe Leme923845f2016-03-02 13:42:48 -08002451 }
2452
Felipe Lemef0823852016-06-08 13:43:08 -07002453 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002454 if (policy == POLICY_NONE) {
2455 mUidPolicy.delete(uid);
2456 } else {
2457 mUidPolicy.put(uid, policy);
2458 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002459
2460 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002461 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002462 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002463 synchronized (mNetworkPoliciesSecondLock) {
2464 writePolicyAL();
2465 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002466 }
2467 }
2468
2469 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002470 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002471 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2472
Felipe Lemef0823852016-06-08 13:43:08 -07002473 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002474 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002475 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002476 }
2477
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002478 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002479 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002480 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2481
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002482 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002483 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002484 for (int i = 0; i < mUidPolicy.size(); i++) {
2485 final int uid = mUidPolicy.keyAt(i);
2486 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002487 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2488 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002489 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002490 }
2491 }
2492 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002493 return uids;
2494 }
2495
2496 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002497 * Removes any persistable state associated with given {@link UserHandle}, persisting
2498 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002499 */
Felipe Lemef0823852016-06-08 13:43:08 -07002500 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002501
Sudheer Shanka352dc572017-09-22 17:09:38 -07002502 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002503 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002504
Felipe Lemea110eec2016-04-29 09:58:06 -07002505 // Remove entries from revoked default restricted background UID whitelist
2506 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2507 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2508 if (UserHandle.getUserId(uid) == userId) {
2509 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002510 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002511 }
2512 }
2513
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002514 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002515 int[] uids = new int[0];
2516 for (int i = 0; i < mUidPolicy.size(); i++) {
2517 final int uid = mUidPolicy.keyAt(i);
2518 if (UserHandle.getUserId(uid) == userId) {
2519 uids = appendInt(uids, uid);
2520 }
2521 }
2522
2523 if (uids.length > 0) {
2524 for (int uid : uids) {
2525 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002526 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002527 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002528 }
Felipe Lemef0823852016-06-08 13:43:08 -07002529 synchronized (mNetworkPoliciesSecondLock) {
2530 updateRulesForGlobalChangeAL(true);
2531 if (writePolicy && changed) {
2532 writePolicyAL();
2533 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002534 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002535 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002536 }
2537
2538 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002539 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002540 // TODO: create permission for observing network policy
2541 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002542 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002543 }
2544
2545 @Override
2546 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002547 // TODO: create permission for observing network policy
2548 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002549 mListeners.unregister(listener);
2550 }
2551
Jeff Sharkey1b861272011-05-22 00:34:52 -07002552 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002553 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002554 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2555
Felipe Leme6a05eee2016-02-19 14:43:51 -08002556 final long token = Binder.clearCallingIdentity();
2557 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002558 synchronized (mUidRulesFirstLock) {
2559 synchronized (mNetworkPoliciesSecondLock) {
2560 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002561 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002562 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002563 }
2564 } finally {
2565 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002566 }
2567 }
2568
Hugo Benichi446c9c92017-04-10 09:41:10 +09002569 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002570 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002571 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2572 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002573 }
2574
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002575 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002576 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002577 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002578 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002579 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2580 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2581 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002582 } catch (SecurityException e) {
2583 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002584
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002585 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2586 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2587 return new NetworkPolicy[0];
2588 }
Svet Ganov16a16892015-04-16 10:32:04 -07002589 }
2590
Felipe Lemef0823852016-06-08 13:43:08 -07002591 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002592 final int size = mNetworkPolicy.size();
2593 final NetworkPolicy[] policies = new NetworkPolicy[size];
2594 for (int i = 0; i < size; i++) {
2595 policies[i] = mNetworkPolicy.valueAt(i);
2596 }
2597 return policies;
2598 }
2599 }
2600
Felipe Lemef0823852016-06-08 13:43:08 -07002601 private void normalizePoliciesNL() {
2602 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002603 }
2604
Felipe Lemef0823852016-06-08 13:43:08 -07002605 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002606 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002607 final String[] merged = tele.getMergedSubscriberIds();
2608
2609 mNetworkPolicy.clear();
2610 for (NetworkPolicy policy : policies) {
2611 // When two normalized templates conflict, prefer the most
2612 // restrictive policy
2613 policy.template = NetworkTemplate.normalize(policy.template, merged);
2614 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2615 if (existing == null || existing.compareTo(policy) > 0) {
2616 if (existing != null) {
2617 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2618 }
2619 mNetworkPolicy.put(policy.template, policy);
2620 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002621 }
2622 }
2623
2624 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002625 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002626 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002627
2628 final long token = Binder.clearCallingIdentity();
2629 try {
2630 performSnooze(template, TYPE_LIMIT);
2631 } finally {
2632 Binder.restoreCallingIdentity(token);
2633 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002634 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002635
Dianne Hackborn497175b2014-07-01 12:56:08 -07002636 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002637 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002638 synchronized (mUidRulesFirstLock) {
2639 synchronized (mNetworkPoliciesSecondLock) {
2640 // find and snooze local policy that matches
2641 final NetworkPolicy policy = mNetworkPolicy.get(template);
2642 if (policy == null) {
2643 throw new IllegalArgumentException("unable to find policy for " + template);
2644 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002645
Felipe Lemef0823852016-06-08 13:43:08 -07002646 switch (type) {
2647 case TYPE_WARNING:
2648 policy.lastWarningSnooze = currentTime;
2649 break;
2650 case TYPE_LIMIT:
2651 policy.lastLimitSnooze = currentTime;
2652 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002653 case TYPE_RAPID:
2654 policy.lastRapidSnooze = currentTime;
2655 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002656 default:
2657 throw new IllegalArgumentException("unexpected type");
2658 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002659
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002660 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002661 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002662 }
2663 }
2664
2665 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002666 public void onTetheringChanged(String iface, boolean tethering) {
2667 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002668 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002669 if (mRestrictBackground && tethering) {
2670 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2671 setRestrictBackground(false);
2672 }
2673 }
2674 }
2675
2676 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002677 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002678 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002679 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002680 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2681 final long token = Binder.clearCallingIdentity();
2682 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002683 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002684 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002685 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002686 } finally {
2687 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002688 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002689 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002690 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002691 }
2692 }
2693
Felipe Lemef0823852016-06-08 13:43:08 -07002694 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002695 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002696 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002697 if (restrictBackground == mRestrictBackground) {
2698 // Ideally, UI should never allow this scenario...
2699 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002700 return;
2701 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002702 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2703 final boolean oldRestrictBackground = mRestrictBackground;
2704 mRestrictBackground = restrictBackground;
2705 // Must whitelist foreground apps before turning data saver mode on.
2706 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2707 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2708 updateRulesForRestrictBackgroundUL();
2709 try {
2710 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2711 Slog.e(TAG,
2712 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2713 mRestrictBackground = oldRestrictBackground;
2714 // TODO: if it knew the foreground apps (see TODO above), it could call
2715 // updateRulesForRestrictBackgroundUL() again to restore state.
2716 return;
2717 }
2718 } catch (RemoteException e) {
2719 // ignored; service lives in system_server
2720 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002721
Sudheer Shanka543339f2017-07-28 15:18:07 -07002722 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002723 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002724
2725 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2726 mRestrictBackgroundChangedInBsm = true;
2727 }
2728 synchronized (mNetworkPoliciesSecondLock) {
2729 updateNotificationsNL();
2730 writePolicyAL();
2731 }
2732 } finally {
2733 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002734 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002735 }
2736
2737 private void sendRestrictBackgroundChangedMsg() {
2738 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2739 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2740 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002741 }
2742
Felipe Lemeb85a6372016-01-14 16:16:16 -08002743 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002744 public int getRestrictBackgroundByCaller() {
2745 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2746 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002747
Felipe Lemef0823852016-06-08 13:43:08 -07002748 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002749 // Must clear identity because getUidPolicy() is restricted to system.
2750 final long token = Binder.clearCallingIdentity();
2751 final int policy;
2752 try {
2753 policy = getUidPolicy(uid);
2754 } finally {
2755 Binder.restoreCallingIdentity(token);
2756 }
2757 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2758 // App is blacklisted.
2759 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2760 }
Felipe Leme1b103232016-01-22 09:44:57 -08002761 if (!mRestrictBackground) {
2762 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2763 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002764 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002765 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2766 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2767 }
2768 }
2769
2770 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002771 public boolean getRestrictBackground() {
2772 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2773
Felipe Lemef0823852016-06-08 13:43:08 -07002774 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002775 return mRestrictBackground;
2776 }
2777 }
2778
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002779 @Override
2780 public void setDeviceIdleMode(boolean enabled) {
2781 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002782 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2783 try {
2784 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002785 if (mDeviceIdleMode == enabled) {
2786 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002787 }
Felipe Lemeea014392016-09-06 13:59:54 -07002788 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002789 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002790 if (mSystemReady) {
2791 // Device idle change means we need to rebuild rules for all
2792 // known apps, so do a global refresh.
2793 updateRulesForRestrictPowerUL();
2794 }
2795 }
2796 if (enabled) {
2797 EventLogTags.writeDeviceIdleOnPhase("net");
2798 } else {
2799 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002800 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002801 } finally {
2802 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002803 }
2804 }
2805
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002806 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002807 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2808 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002809 final long token = Binder.clearCallingIdentity();
2810 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002811 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2812 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2813 for (WifiConfiguration config : configs) {
2814 if (Objects.equals(resolveNetworkId(config), networkId)) {
2815 config.meteredOverride = meteredOverride;
2816 wm.updateNetwork(config);
2817 }
2818 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002819 } finally {
2820 Binder.restoreCallingIdentity(token);
2821 }
2822 }
2823
Jeff Sharkey46645002011-07-27 21:11:21 -07002824 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002825 @Deprecated
2826 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2827 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2828 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2829 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002830 }
2831
Jeff Sharkey53313d72017-07-13 16:47:32 -06002832 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2833 // Verify they're not lying about package name
2834 mAppOps.checkPackage(callingUid, callingPackage);
2835
Jeff Sharkey53313d72017-07-13 16:47:32 -06002836 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002837 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002838 final long token = Binder.clearCallingIdentity();
2839 try {
2840 si = mContext.getSystemService(SubscriptionManager.class)
2841 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002842 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002843 } finally {
2844 Binder.restoreCallingIdentity(token);
2845 }
2846
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002847 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002848 if (si != null) {
2849 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2850 return;
2851 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002852 }
2853
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002854 // Second check: has the CarrierService delegated access?
2855 if (config != null) {
2856 final String overridePackage = config
2857 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2858 if (!TextUtils.isEmpty(overridePackage)
2859 && Objects.equals(overridePackage, callingPackage)) {
2860 return;
2861 }
2862 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002863
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002864 // Third check: is caller the fallback/default CarrierService?
2865 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2866 if (!TextUtils.isEmpty(defaultPackage)
2867 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002868 return;
2869 }
2870
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002871 // Fourth check: is caller a testing app?
2872 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2873 if (!TextUtils.isEmpty(testPackage)
2874 && Objects.equals(testPackage, callingPackage)) {
2875 return;
2876 }
2877
2878 // Fifth check: is caller a legacy testing app?
2879 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2880 if (!TextUtils.isEmpty(legacyTestPackage)
2881 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002882 return;
2883 }
2884
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002885 // Final check: does the caller hold a permission?
2886 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002887 }
2888
2889 @Override
2890 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2891 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2892
Jeff Sharkey53313d72017-07-13 16:47:32 -06002893 final String fake = SystemProperties.get("fw.fake_plan");
2894 if (!TextUtils.isEmpty(fake)) {
2895 final List<SubscriptionPlan> plans = new ArrayList<>();
2896 if ("month_hard".equals(fake)) {
2897 plans.add(SubscriptionPlan.Builder
2898 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2899 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002900 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2901 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2902 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2903 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2904 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002905 plans.add(SubscriptionPlan.Builder
2906 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2907 .setTitle("G-Mobile Happy")
2908 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2909 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2910 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2911 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2912 .build());
2913 plans.add(SubscriptionPlan.Builder
2914 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2915 .setTitle("G-Mobile, Charged after limit")
2916 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2917 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2918 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2919 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2920 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002921 } else if ("month_soft".equals(fake)) {
2922 plans.add(SubscriptionPlan.Builder
2923 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2924 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2925 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2926 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002927 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2928 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2929 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2930 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2931 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002932 plans.add(SubscriptionPlan.Builder
2933 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2934 .setTitle("G-Mobile, Throttled after limit")
2935 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2936 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2937 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2938 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2939 .build());
2940 plans.add(SubscriptionPlan.Builder
2941 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2942 .setTitle("G-Mobile, No data connection after limit")
2943 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2944 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2945 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2946 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2947 .build());
2948
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002949 } else if ("month_over".equals(fake)) {
2950 plans.add(SubscriptionPlan.Builder
2951 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2952 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2953 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2954 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2955 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2956 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2957 .build());
2958 plans.add(SubscriptionPlan.Builder
2959 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2960 .setTitle("G-Mobile, Throttled after limit")
2961 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2962 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2963 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2964 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2965 .build());
2966 plans.add(SubscriptionPlan.Builder
2967 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2968 .setTitle("G-Mobile, No data connection after limit")
2969 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2970 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2971 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2972 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2973 .build());
2974
Jeff Sharkey53313d72017-07-13 16:47:32 -06002975 } else if ("month_none".equals(fake)) {
2976 plans.add(SubscriptionPlan.Builder
2977 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2978 .setTitle("G-Mobile")
2979 .build());
2980 } else if ("prepaid".equals(fake)) {
2981 plans.add(SubscriptionPlan.Builder
2982 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2983 ZonedDateTime.now().plusDays(10))
2984 .setTitle("G-Mobile")
2985 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2986 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2987 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2988 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2989 .build());
2990 } else if ("prepaid_crazy".equals(fake)) {
2991 plans.add(SubscriptionPlan.Builder
2992 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2993 ZonedDateTime.now().plusDays(10))
2994 .setTitle("G-Mobile Anytime")
2995 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2996 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2997 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2998 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2999 .build());
3000 plans.add(SubscriptionPlan.Builder
3001 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3002 ZonedDateTime.now().plusDays(20))
3003 .setTitle("G-Mobile Nickel Nights")
3004 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003005 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3006 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003007 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3008 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3009 .build());
3010 plans.add(SubscriptionPlan.Builder
3011 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3012 ZonedDateTime.now().plusDays(20))
3013 .setTitle("G-Mobile Bonus 3G")
3014 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003015 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003016 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3017 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3018 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3019 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003020 } else if ("unlimited".equals(fake)) {
3021 plans.add(SubscriptionPlan.Builder
3022 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3023 ZonedDateTime.now().plusDays(10))
3024 .setTitle("G-Mobile Awesome")
3025 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3026 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3027 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3028 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3029 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003030 }
3031 return plans.toArray(new SubscriptionPlan[plans.size()]);
3032 }
3033
Jeff Sharkey4635f102017-09-01 11:27:13 -06003034 synchronized (mNetworkPoliciesSecondLock) {
3035 // Only give out plan details to the package that defined them,
3036 // so that we don't risk leaking plans between apps. We always
3037 // let in core system components (like the Settings app).
3038 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3039 if (Objects.equals(ownerPackage, callingPackage)
3040 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3041 return mSubscriptionPlans.get(subId);
3042 } else {
3043 Log.w(TAG, "Not returning plans because caller " + callingPackage
3044 + " doesn't match owner " + ownerPackage);
3045 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003046 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003047 }
3048 }
3049
3050 @Override
3051 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3052 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3053
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003054 for (SubscriptionPlan plan : plans) {
3055 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003056 }
3057
3058 final long token = Binder.clearCallingIdentity();
3059 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003060 synchronized (mUidRulesFirstLock) {
3061 synchronized (mNetworkPoliciesSecondLock) {
3062 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003063 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003064
3065 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
3066 .getSubscriberId(subId);
3067 ensureActiveMobilePolicyAL(subId, subscriberId);
3068 maybeUpdateMobilePolicyCycleAL(subId);
3069 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003070 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003071 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003072
3073 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3074 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3075 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3076 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003077 } finally {
3078 Binder.restoreCallingIdentity(token);
3079 }
3080 }
3081
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003082 /**
3083 * Only visible for testing purposes. This doesn't give any access to
3084 * existing plans; it simply lets the debug package define new plans.
3085 */
3086 void setSubscriptionPlansOwner(int subId, String packageName) {
3087 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3088 }
3089
Jeff Sharkey53313d72017-07-13 16:47:32 -06003090 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003091 public String getSubscriptionPlansOwner(int subId) {
3092 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3093 throw new SecurityException();
3094 }
3095
3096 synchronized (mNetworkPoliciesSecondLock) {
3097 return mSubscriptionPlansOwner.get(subId);
3098 }
3099 }
3100
3101 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003102 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3103 long timeoutMillis, String callingPackage) {
3104 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3105
3106 // We can only override when carrier told us about plans
3107 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003108 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3109 if (plan == null
3110 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003111 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003112 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003113 }
3114 }
3115
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003116 // Only allow overrides when feature is enabled. However, we always
3117 // allow disabling of overrides for safety reasons.
3118 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3119 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3120 if (overrideEnabled || overrideValue == 0) {
3121 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3122 overrideMask, overrideValue, subId));
3123 if (timeoutMillis > 0) {
3124 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3125 overrideMask, 0, subId), timeoutMillis);
3126 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003127 }
3128 }
3129
3130 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003131 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003132 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003133
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003134 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3135
Dianne Hackborn497175b2014-07-01 12:56:08 -07003136 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003137 for (String arg : args) {
3138 argSet.add(arg);
3139 }
3140
Felipe Lemef0823852016-06-08 13:43:08 -07003141 synchronized (mUidRulesFirstLock) {
3142 synchronized (mNetworkPoliciesSecondLock) {
3143 if (argSet.contains("--unsnooze")) {
3144 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3145 mNetworkPolicy.valueAt(i).clearSnooze();
3146 }
3147
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003148 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003149
3150 fout.println("Cleared snooze timestamps");
3151 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003152 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003153
Felipe Lemef0823852016-06-08 13:43:08 -07003154 fout.print("System ready: "); fout.println(mSystemReady);
3155 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3156 fout.print("Restrict power: "); fout.println(mRestrictPower);
3157 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003158 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3159
3160 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003161 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003162 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003163 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3164 fout.println(mNetworkPolicy.valueAt(i).toString());
3165 }
3166 fout.decreaseIndent();
3167
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003168 fout.println();
3169 fout.println("Subscription plans:");
3170 fout.increaseIndent();
3171 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3172 final int subId = mSubscriptionPlans.keyAt(i);
3173 fout.println("Subscriber ID " + subId + ":");
3174 fout.increaseIndent();
3175 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3176 if (!ArrayUtils.isEmpty(plans)) {
3177 for (SubscriptionPlan plan : plans) {
3178 fout.println(plan);
3179 }
3180 }
3181 fout.decreaseIndent();
3182 }
3183 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003184
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003185 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003186 fout.println("Policy for UIDs:");
3187 fout.increaseIndent();
3188 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003189 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003190 final int uid = mUidPolicy.keyAt(i);
3191 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003192 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003193 fout.print(uid);
3194 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003195 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003196 fout.println();
3197 }
3198 fout.decreaseIndent();
3199
3200 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3201 if (size > 0) {
3202 fout.println("Power save whitelist (except idle) app ids:");
3203 fout.increaseIndent();
3204 for (int i = 0; i < size; i++) {
3205 fout.print("UID=");
3206 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3207 fout.print(": ");
3208 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3209 fout.println();
3210 }
3211 fout.decreaseIndent();
3212 }
3213
3214 size = mPowerSaveWhitelistAppIds.size();
3215 if (size > 0) {
3216 fout.println("Power save whitelist app ids:");
3217 fout.increaseIndent();
3218 for (int i = 0; i < size; i++) {
3219 fout.print("UID=");
3220 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3221 fout.print(": ");
3222 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3223 fout.println();
3224 }
3225 fout.decreaseIndent();
3226 }
3227
Felipe Lemef0823852016-06-08 13:43:08 -07003228 size = mDefaultRestrictBackgroundWhitelistUids.size();
3229 if (size > 0) {
3230 fout.println("Default restrict background whitelist uids:");
3231 fout.increaseIndent();
3232 for (int i = 0; i < size; i++) {
3233 fout.print("UID=");
3234 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3235 fout.println();
3236 }
3237 fout.decreaseIndent();
3238 }
3239
3240 size = mRestrictBackgroundWhitelistRevokedUids.size();
3241 if (size > 0) {
3242 fout.println("Default restrict background whitelist uids revoked by users:");
3243 fout.increaseIndent();
3244 for (int i = 0; i < size; i++) {
3245 fout.print("UID=");
3246 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3247 fout.println();
3248 }
3249 fout.decreaseIndent();
3250 }
3251
3252 final SparseBooleanArray knownUids = new SparseBooleanArray();
3253 collectKeys(mUidState, knownUids);
3254 collectKeys(mUidRules, knownUids);
3255
3256 fout.println("Status for all known UIDs:");
3257 fout.increaseIndent();
3258 size = knownUids.size();
3259 for (int i = 0; i < size; i++) {
3260 final int uid = knownUids.keyAt(i);
3261 fout.print("UID=");
3262 fout.print(uid);
3263
3264 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3265 fout.print(" state=");
3266 fout.print(state);
3267 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3268 fout.print(" (fg)");
3269 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003270 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003271 ? " (fg svc)" : " (bg)");
3272 }
3273
3274 final int uidRules = mUidRules.get(uid, RULE_NONE);
3275 fout.print(" rules=");
3276 fout.print(uidRulesToString(uidRules));
3277 fout.println();
3278 }
3279 fout.decreaseIndent();
3280
3281 fout.println("Status for just UIDs with rules:");
3282 fout.increaseIndent();
3283 size = mUidRules.size();
3284 for (int i = 0; i < size; i++) {
3285 final int uid = mUidRules.keyAt(i);
3286 fout.print("UID=");
3287 fout.print(uid);
3288 final int uidRules = mUidRules.get(uid, RULE_NONE);
3289 fout.print(" rules=");
3290 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003291 fout.println();
3292 }
3293 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003294
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003295 fout.println("Admin restricted uids for metered data:");
3296 fout.increaseIndent();
3297 size = mMeteredRestrictedUids.size();
3298 for (int i = 0; i < size; ++i) {
3299 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3300 fout.println(mMeteredRestrictedUids.valueAt(i));
3301 }
3302 fout.decreaseIndent();
3303
Sudheer Shanka352dc572017-09-22 17:09:38 -07003304 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003305 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003306 }
3307 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003308
3309 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003310 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003311 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003312 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003313 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003314 }
3315
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003316 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003317 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003318 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003319 return isUidStateForeground(
3320 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003321 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003322 }
3323
Felipe Lemef0823852016-06-08 13:43:08 -07003324 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003325 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003326 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003327 }
3328
Felipe Lemef0823852016-06-08 13:43:08 -07003329 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003330 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3331 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3332 }
3333
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003334 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003335 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003336 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003337 }
3338
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003339 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003340 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003341 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3342 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003343 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003344 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003345 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3346 try {
3347 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3348 if (oldUidState != uidState) {
3349 // state changed, push updated rules
3350 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003351 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3352 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3353 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003354 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003355 if (mDeviceIdleMode) {
3356 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003357 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003358 if (mRestrictPower) {
3359 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003360 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003361 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003362 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003363 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003364 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003365 } finally {
3366 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003367 }
3368 }
3369
Felipe Lemef0823852016-06-08 13:43:08 -07003370 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003371 final int index = mUidState.indexOfKey(uid);
3372 if (index >= 0) {
3373 final int oldUidState = mUidState.valueAt(index);
3374 mUidState.removeAt(index);
3375 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003376 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003377 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003378 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003379 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003380 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003381 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003382 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003383 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003384 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003385 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003386 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003387 }
3388 }
3389
Felipe Lemef28983d2016-03-25 12:18:23 -07003390 // adjust stats accounting based on foreground status
3391 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003392 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3393 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3394 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3395 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003396 try {
3397 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003398 } finally {
3399 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003400 }
3401 }
3402
Sudheer Shankac9d94072017-02-22 22:13:55 +00003403 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3404 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003405 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003406 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003407 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003408 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003409 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003410 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003411 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003412 }
3413
Felipe Lemef0823852016-06-08 13:43:08 -07003414 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003415 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3416 try {
3417 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3418 mUidFirewallPowerSaveRules);
3419 } finally {
3420 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3421 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003422 }
3423
Felipe Lemef0823852016-06-08 13:43:08 -07003424 void updateRuleForRestrictPowerUL(int uid) {
3425 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003426 }
3427
Felipe Lemef0823852016-06-08 13:43:08 -07003428 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003429 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3430 try {
3431 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3432 mUidFirewallDozableRules);
3433 } finally {
3434 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3435 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003436 }
3437
Felipe Lemef0823852016-06-08 13:43:08 -07003438 void updateRuleForDeviceIdleUL(int uid) {
3439 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003440 }
3441
Felipe Lemef28983d2016-03-25 12:18:23 -07003442 // NOTE: since both fw_dozable and fw_powersave uses the same map
3443 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003444 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003445 SparseIntArray rules) {
3446 if (enabled) {
3447 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003448 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003449 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003450 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003451 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003452 for (int ui = users.size() - 1; ui >= 0; ui--) {
3453 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003454 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3455 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3456 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3457 updateRulesForWhitelistedAppIds(uidRules,
3458 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003459 }
3460 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003461 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003462 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003463 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3464 }
3465 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003466 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003467 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003468 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003469 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003470 }
3471
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003472 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3473 final SparseBooleanArray whitelistedAppIds, int userId) {
3474 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3475 if (whitelistedAppIds.valueAt(i)) {
3476 final int appId = whitelistedAppIds.keyAt(i);
3477 final int uid = UserHandle.getUid(userId, appId);
3478 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3479 }
3480 }
3481 }
3482
3483 /**
3484 * @param deviceIdleMode if true then we don't consider
3485 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3486 * whitelisted.
3487 */
3488 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003489 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003490 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3491 || mPowerSaveWhitelistAppIds.get(appId);
3492 if (!deviceIdleMode) {
3493 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3494 }
3495 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003496 }
3497
Felipe Lemef28983d2016-03-25 12:18:23 -07003498 // NOTE: since both fw_dozable and fw_powersave uses the same map
3499 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003500 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003501 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003502 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3503 chain == FIREWALL_CHAIN_DOZABLE);
3504 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003505 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003506 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003507 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003508 }
3509 }
3510 }
3511
Felipe Lemef0823852016-06-08 13:43:08 -07003512 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003513 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3514 try {
3515 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3516 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003517
Felipe Leme873a83a2016-09-07 11:34:10 -07003518 // Fully update the app idle firewall chain.
3519 final List<UserInfo> users = mUserManager.getUsers();
3520 for (int ui = users.size() - 1; ui >= 0; ui--) {
3521 UserInfo user = users.get(ui);
3522 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3523 for (int uid : idleUids) {
3524 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3525 // quick check: if this uid doesn't have INTERNET permission, it
3526 // doesn't have network access anyway, so it is a waste to mess
3527 // with it here.
3528 if (hasInternetPermissions(uid)) {
3529 uidRules.put(uid, FIREWALL_RULE_DENY);
3530 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003531 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003532 }
3533 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003534
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003535 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003536 } finally {
3537 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3538 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003539 }
3540
Felipe Lemef0823852016-06-08 13:43:08 -07003541 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003542 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003543
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003544 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3545 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3546 }
3547 try {
3548 int appId = UserHandle.getAppId(uid);
3549 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3550 && !isUidForegroundOnRestrictPowerUL(uid)) {
3551 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3552 } else {
3553 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3554 }
3555 } finally {
3556 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003557 }
3558 }
3559
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003560 /**
3561 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3562 * changed.
3563 */
Felipe Lemef0823852016-06-08 13:43:08 -07003564 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003565 boolean paroled = mUsageStats.isAppIdleParoleOn();
3566 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003567 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003568
3569 int ruleCount = mUidFirewallStandbyRules.size();
3570 for (int i = 0; i < ruleCount; i++) {
3571 int uid = mUidFirewallStandbyRules.keyAt(i);
3572 int oldRules = mUidRules.get(uid);
3573 if (enableChain) {
3574 // Chain wasn't enabled before and the other power-related
3575 // chains are whitelists, so we can clear the
3576 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3577 // the effective rules result in blocking network access.
3578 oldRules &= MASK_METERED_NETWORKS;
3579 } else {
3580 // Skip if it had no restrictions to begin with
3581 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3582 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003583 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3584 if (newUidRules == RULE_NONE) {
3585 mUidRules.delete(uid);
3586 } else {
3587 mUidRules.put(uid, newUidRules);
3588 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003589 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003590 }
3591
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003592 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003593 * Update rules that might be changed by {@link #mRestrictBackground},
3594 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003595 */
Felipe Lemef0823852016-06-08 13:43:08 -07003596 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003597 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3598 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3599 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3600 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003601 try {
Felipe Leme09700462016-09-08 09:33:48 -07003602 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003603 updateRulesForRestrictPowerUL();
3604 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003605
Felipe Leme873a83a2016-09-07 11:34:10 -07003606 // If the set of restricted networks may have changed, re-evaluate those.
3607 if (restrictedNetworksChanged) {
3608 normalizePoliciesNL();
3609 updateNetworkRulesNL();
3610 }
3611 } finally {
3612 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003613 }
3614 }
3615
Felipe Leme09700462016-09-08 09:33:48 -07003616 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003617 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003618 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3619 try {
3620 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003621 updateRulesForPowerSaveUL();
3622 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3623 } finally {
3624 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3625 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003626 }
3627
Felipe Lemef0823852016-06-08 13:43:08 -07003628 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003629 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3630 try {
3631 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3632 } finally {
3633 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3634 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003635 }
3636
3637 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3638 private static final int TYPE_RESTRICT_POWER = 2;
3639 @Retention(RetentionPolicy.SOURCE)
3640 @IntDef(flag = false, value = {
3641 TYPE_RESTRICT_BACKGROUND,
3642 TYPE_RESTRICT_POWER,
3643 })
3644 public @interface RestrictType {
3645 }
3646
3647 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003648 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003649 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3650 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3651 }
3652 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003653 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003654
3655 final PackageManager pm = mContext.getPackageManager();
3656 final List<UserInfo> users;
3657 final List<ApplicationInfo> apps;
3658
3659 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3660 try {
3661 users = mUserManager.getUsers();
3662 } finally {
3663 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3664 }
3665 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3666 try {
3667 apps = pm.getInstalledApplications(
3668 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3669 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3670 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3671 } finally {
3672 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3673 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003674
Felipe Leme873a83a2016-09-07 11:34:10 -07003675 final int usersSize = users.size();
3676 final int appsSize = apps.size();
3677 for (int i = 0; i < usersSize; i++) {
3678 final UserInfo user = users.get(i);
3679 for (int j = 0; j < appsSize; j++) {
3680 final ApplicationInfo app = apps.get(j);
3681 final int uid = UserHandle.getUid(user.id, app.uid);
3682 switch (type) {
3683 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003684 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003685 break;
3686 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003687 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003688 break;
3689 default:
3690 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3691 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003692 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003693 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003694 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003695 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003696 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003697 }
3698
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003699 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003700 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003701 final int numUsers = users.size();
3702 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003703 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003704 int uid = UserHandle.getUid(user.id, appId);
3705 // Update external firewall rules.
3706 updateRuleForAppIdleUL(uid);
3707 updateRuleForDeviceIdleUL(uid);
3708 updateRuleForRestrictPowerUL(uid);
3709 // Update internal rules.
3710 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003711 }
3712 }
3713
Felipe Leme70c57c22016-03-29 10:45:13 -07003714 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3715 // methods below could be merged into a isUidValidForRules() method.
3716 private boolean isUidValidForBlacklistRules(int uid) {
3717 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003718 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003719 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003720 return true;
3721 }
3722
3723 return false;
3724 }
3725
Felipe Leme70c57c22016-03-29 10:45:13 -07003726 private boolean isUidValidForWhitelistRules(int uid) {
3727 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3728 }
3729
Amith Yamasani15e472352015-04-24 19:06:07 -07003730 private boolean isUidIdle(int uid) {
3731 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3732 final int userId = UserHandle.getUserId(uid);
3733
songjinshi0655edd2016-05-18 19:55:32 +08003734 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003735 for (String packageName : packages) {
3736 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3737 return false;
3738 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003739 }
3740 }
3741 return true;
3742 }
3743
3744 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003745 * Checks if an uid has INTERNET permissions.
3746 * <p>
3747 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003748 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003749 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003750 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003751 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003752 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003753 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003754 }
3755 } catch (RemoteException e) {
3756 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003757 return true;
3758 }
3759
3760 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003761 * Clears all state - internal and external - associated with an UID.
3762 */
3763 private void onUidDeletedUL(int uid) {
3764 // First cleanup in-memory state synchronously...
3765 mUidRules.delete(uid);
3766 mUidPolicy.delete(uid);
3767 mUidFirewallStandbyRules.delete(uid);
3768 mUidFirewallDozableRules.delete(uid);
3769 mUidFirewallPowerSaveRules.delete(uid);
3770 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3771 mPowerSaveWhitelistAppIds.delete(uid);
3772 mPowerSaveTempWhitelistAppIds.delete(uid);
3773
3774 // ...then update iptables asynchronously.
3775 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3776 }
3777
3778 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003779 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003780 *
Felipe Leme781ba142016-05-09 16:24:48 -07003781 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003782 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003783 * <li>Doze mode
3784 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003785 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003786 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003787 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003788 *
3789 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003790 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003791 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003792 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003793 updateRuleForDeviceIdleUL(uid);
3794 updateRuleForAppIdleUL(uid);
3795 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003796
3797 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003798 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003799
3800 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003801 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003802 }
3803
Felipe Leme70c57c22016-03-29 10:45:13 -07003804 /**
3805 * Applies network rules to bandwidth controllers based on process state and user-defined
3806 * restrictions (blacklist / whitelist).
3807 *
3808 * <p>
3809 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3810 * networks:
3811 * <ul>
3812 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3813 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3814 * also blacklisted.
3815 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3816 * no UIDs other those whitelisted will have access.
3817 * <ul>
3818 *
3819 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3820 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3821 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3822 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003823 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003824 * {@link INetworkManagementService}, but this method should also be called in events (like
3825 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3826 * following rules should also be applied:
3827 *
3828 * <ul>
3829 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3830 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3831 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3832 * {@code bw_penalty_box}.
3833 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3834 * </ul>
3835 *
3836 * <p>For optimization, the rules are only applied on user apps that have internet access
3837 * permission, since there is no need to change the {@code iptables} rule if the app does not
3838 * have permission to use the internet.
3839 *
3840 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003841 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003842 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003843 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003844 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3845 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3846 "updateRulesForDataUsageRestrictionsUL: " + uid);
3847 }
3848 try {
3849 updateRulesForDataUsageRestrictionsULInner(uid);
3850 } finally {
3851 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3852 }
3853 }
3854
3855 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003856 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003857 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003858 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003859 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003860
Dianne Hackborn497175b2014-07-01 12:56:08 -07003861 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003862 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003863 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003864 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003865
Felipe Leme781ba142016-05-09 16:24:48 -07003866 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003867 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003868 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3869 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003870
Felipe Leme70c57c22016-03-29 10:45:13 -07003871 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003872 if (isRestrictedByAdmin) {
3873 newRule = RULE_REJECT_METERED;
3874 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003875 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3876 newRule = RULE_TEMPORARY_ALLOW_METERED;
3877 } else if (isWhitelisted) {
3878 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003879 }
3880 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003881 if (isBlacklisted) {
3882 newRule = RULE_REJECT_METERED;
3883 } else if (mRestrictBackground && isWhitelisted) {
3884 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003885 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003886 }
Felipe Leme781ba142016-05-09 16:24:48 -07003887 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003888
Felipe Lemef28983d2016-03-25 12:18:23 -07003889 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003890 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003891 + ": isForeground=" +isForeground
3892 + ", isBlacklisted=" + isBlacklisted
3893 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003894 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003895 + ", oldRule=" + uidRulesToString(oldRule)
3896 + ", newRule=" + uidRulesToString(newRule)
3897 + ", newUidRules=" + uidRulesToString(newUidRules)
3898 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003899 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003900
Felipe Leme46c4fc32016-05-04 09:21:43 -07003901 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003902 mUidRules.delete(uid);
3903 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003904 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003905 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003906
Felipe Leme70c57c22016-03-29 10:45:13 -07003907 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003908 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003909 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003910 // Temporarily whitelist foreground app, removing from blacklist if necessary
3911 // (since bw_penalty_box prevails over bw_happy_box).
3912
3913 setMeteredNetworkWhitelist(uid, true);
3914 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3915 // but ideally it should be just:
3916 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003917 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003918 setMeteredNetworkBlacklist(uid, false);
3919 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003920 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003921 // Remove temporary whitelist from app that is not on foreground anymore.
3922
3923 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3924 // but ideally they should be just:
3925 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3926 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003927 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003928 setMeteredNetworkWhitelist(uid, false);
3929 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003930 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003931 setMeteredNetworkBlacklist(uid, true);
3932 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003933 } else if (hasRule(newRule, RULE_REJECT_METERED)
3934 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003935 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003936 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003937 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003938 // Since blacklist prevails over whitelist, we need to handle the special case
3939 // where app is whitelisted and blacklisted at the same time (although such
3940 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003941 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003942 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003943 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3944 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003945 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003946 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003947 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003948 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003949 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3950 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003951 + ", whitelisted=" + isWhitelisted
3952 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003953 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003954 + ", newRule=" + uidRulesToString(newUidRules)
3955 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003956 }
Felipe Leme781ba142016-05-09 16:24:48 -07003957
Sudheer Shankac9d94072017-02-22 22:13:55 +00003958 // Dispatch changed rule to existing listeners.
3959 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003960 }
3961 }
3962
3963 /**
3964 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3965 * listeners in case of change.
3966 * <p>
3967 * There are 3 power-related rules that affects whether an app has background access on
3968 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3969 * restriction, it's added to the equivalent firewall chain:
3970 * <ul>
3971 * <li>App is idle: {@code fw_standby} firewall chain.
3972 * <li>Device is idle: {@code fw_dozable} firewall chain.
3973 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3974 * </ul>
3975 * <p>
3976 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3977 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3978 * <p>
3979 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3980 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003981 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003982 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3983
Sudheer Shankac9d94072017-02-22 22:13:55 +00003984 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003985
Sudheer Shankac9d94072017-02-22 22:13:55 +00003986 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003987 mUidRules.delete(uid);
3988 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003989 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003990 }
3991 }
3992
3993 /**
3994 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3995 *
3996 * @param uid the uid of the app to update rules for
3997 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3998 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3999 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004000 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004001 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004002 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004003 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4004 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4005 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4006 + (paroled ? "P" : "-"));
4007 }
4008 try {
4009 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4010 } finally {
4011 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4012 }
4013 }
4014
4015 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004016 if (!isUidValidForBlacklistRules(uid)) {
4017 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004018 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004019 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004020
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004021 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004022 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004023 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004024
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07004025 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004026 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4027 int newRule = RULE_NONE;
4028
4029 // First step: define the new rule based on user restrictions and foreground state.
4030
4031 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4032 // by considering the foreground and non-foreground states.
4033 if (isForeground) {
4034 if (restrictMode) {
4035 newRule = RULE_ALLOW_ALL;
4036 }
4037 } else if (restrictMode) {
4038 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4039 }
4040
4041 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4042
4043 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004044 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004045 + ", isIdle: " + isIdle
4046 + ", mRestrictPower: " + mRestrictPower
4047 + ", mDeviceIdleMode: " + mDeviceIdleMode
4048 + ", isForeground=" + isForeground
4049 + ", isWhitelisted=" + isWhitelisted
4050 + ", oldRule=" + uidRulesToString(oldRule)
4051 + ", newRule=" + uidRulesToString(newRule)
4052 + ", newUidRules=" + uidRulesToString(newUidRules)
4053 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4054 }
4055
Felipe Leme781ba142016-05-09 16:24:48 -07004056 // Second step: notify listeners if state changed.
4057 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004058 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004059 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004060 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004061 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4062 } else {
4063 // All scenarios should have been covered above
4064 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4065 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004066 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004067 + ", newRule=" + uidRulesToString(newUidRules)
4068 + ", oldRule=" + uidRulesToString(oldUidRules));
4069 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004070 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004071 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004072
Sudheer Shankac9d94072017-02-22 22:13:55 +00004073 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004074 }
4075
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004076 private class AppIdleStateChangeListener
4077 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4078
4079 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004080 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4081 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004082 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004083 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4084 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004085 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004086 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004087 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004088 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004089 }
4090 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004091 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004092 }
4093
4094 @Override
4095 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004096 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004097 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004098 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004099 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004100 }
4101 }
4102
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004103 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4104 if (listener != null) {
4105 try {
4106 listener.onUidRulesChanged(uid, uidRules);
4107 } catch (RemoteException ignored) {
4108 }
4109 }
4110 }
4111
4112 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4113 String[] meteredIfaces) {
4114 if (listener != null) {
4115 try {
4116 listener.onMeteredIfacesChanged(meteredIfaces);
4117 } catch (RemoteException ignored) {
4118 }
4119 }
4120 }
4121
4122 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4123 boolean restrictBackground) {
4124 if (listener != null) {
4125 try {
4126 listener.onRestrictBackgroundChanged(restrictBackground);
4127 } catch (RemoteException ignored) {
4128 }
4129 }
4130 }
4131
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004132 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4133 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004134 if (listener != null) {
4135 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004136 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004137 } catch (RemoteException ignored) {
4138 }
4139 }
4140 }
4141
Jeff Sharkey9252b342018-01-19 07:58:35 +09004142 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4143 int overrideMask, int overrideValue) {
4144 if (listener != null) {
4145 try {
4146 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4147 } catch (RemoteException ignored) {
4148 }
4149 }
4150 }
4151
Makoto Onuki8e777332017-03-28 11:25:47 -07004152 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004153 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004154 public boolean handleMessage(Message msg) {
4155 switch (msg.what) {
4156 case MSG_RULES_CHANGED: {
4157 final int uid = msg.arg1;
4158 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004159 final int length = mListeners.beginBroadcast();
4160 for (int i = 0; i < length; i++) {
4161 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4162 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004163 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004164 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004165 return true;
4166 }
4167 case MSG_METERED_IFACES_CHANGED: {
4168 final String[] meteredIfaces = (String[]) msg.obj;
4169 final int length = mListeners.beginBroadcast();
4170 for (int i = 0; i < length; i++) {
4171 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004172 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004173 }
4174 mListeners.finishBroadcast();
4175 return true;
4176 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004177 case MSG_LIMIT_REACHED: {
4178 final String iface = (String) msg.obj;
4179
Felipe Lemef0823852016-06-08 13:43:08 -07004180 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004181 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004182 // force stats update to make sure we have
4183 // numbers that caused alert to trigger.
4184 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004185
Felipe Lemef0823852016-06-08 13:43:08 -07004186 updateNetworkEnabledNL();
4187 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004188 }
4189 }
4190 return true;
4191 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004192 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4193 final boolean restrictBackground = msg.arg1 != 0;
4194 final int length = mListeners.beginBroadcast();
4195 for (int i = 0; i < length; i++) {
4196 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004197 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004198 }
4199 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004200 final Intent intent =
4201 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4202 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4203 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4204 return true;
4205 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004206 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004207 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004208 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004209 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004210 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004211 final int length = mListeners.beginBroadcast();
4212 for (int i = 0; i < length; i++) {
4213 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004214 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004215 }
4216 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004217 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4218 if (notifyApp.booleanValue()) {
4219 broadcastRestrictBackgroundChanged(uid, notifyApp);
4220 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004221 return true;
4222 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004223 case MSG_ADVISE_PERSIST_THRESHOLD: {
4224 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004225 // make sure stats are recorded frequently enough; we aim
4226 // for 2MB threshold for 2GB/month rules.
4227 final long persistThreshold = lowestRule / 1000;
4228 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004229 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004230 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004231 case MSG_UPDATE_INTERFACE_QUOTA: {
4232 removeInterfaceQuota((String) msg.obj);
4233 // int params need to be stitched back into a long
4234 setInterfaceQuota((String) msg.obj,
4235 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4236 return true;
4237 }
4238 case MSG_REMOVE_INTERFACE_QUOTA: {
4239 removeInterfaceQuota((String) msg.obj);
4240 return true;
4241 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004242 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4243 resetUidFirewallRules(msg.arg1);
4244 return true;
4245 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004246 case MSG_SUBSCRIPTION_OVERRIDE: {
4247 final int overrideMask = msg.arg1;
4248 final int overrideValue = msg.arg2;
4249 final int subId = (int) msg.obj;
4250 final int length = mListeners.beginBroadcast();
4251 for (int i = 0; i < length; i++) {
4252 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4253 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4254 }
4255 mListeners.finishBroadcast();
4256 return true;
4257 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004258 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4259 final int userId = msg.arg1;
4260 final Set<String> packageNames = (Set<String>) msg.obj;
4261 setMeteredRestrictedPackagesInternal(packageNames, userId);
4262 return true;
4263 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004264 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4265 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4266 final boolean enabled = msg.arg1 != 0;
4267 setNetworkTemplateEnabledInner(template, enabled);
4268 return true;
4269 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004270 default: {
4271 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004272 }
4273 }
4274 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004275 };
4276
4277 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4278 @Override
4279 public boolean handleMessage(Message msg) {
4280 switch (msg.what) {
4281 case UID_MSG_STATE_CHANGED: {
4282 final int uid = msg.arg1;
4283 final int procState = msg.arg2;
4284 final long procStateSeq = (Long) msg.obj;
4285
4286 handleUidChanged(uid, procState, procStateSeq);
4287 return true;
4288 }
4289 case UID_MSG_GONE: {
4290 final int uid = msg.arg1;
4291 handleUidGone(uid);
4292 return true;
4293 }
4294 default: {
4295 return false;
4296 }
4297 }
4298 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004299
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004300 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004301
Makoto Onuki8e777332017-03-28 11:25:47 -07004302 void handleUidChanged(int uid, int procState, long procStateSeq) {
4303 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4304 try {
4305 synchronized (mUidRulesFirstLock) {
4306 // We received a uid state change callback, add it to the history so that it
4307 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004308 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004309 // Now update the network policy rules as per the updated uid state.
4310 updateUidStateUL(uid, procState);
4311 // Updating the network rules is done, so notify AMS about this.
4312 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4313 }
4314 } finally {
4315 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4316 }
4317 }
4318
4319 void handleUidGone(int uid) {
4320 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4321 try {
4322 synchronized (mUidRulesFirstLock) {
4323 removeUidStateUL(uid);
4324 }
4325 } finally {
4326 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4327 }
4328 }
4329
Felipe Leme57e3d312016-08-23 14:42:52 -07004330 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4331 final PackageManager pm = mContext.getPackageManager();
4332 final String[] packages = pm.getPackagesForUid(uid);
4333 if (packages != null) {
4334 final int userId = UserHandle.getUserId(uid);
4335 for (String packageName : packages) {
4336 final Intent intent =
4337 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4338 intent.setPackage(packageName);
4339 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4340 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4341 }
4342 }
4343 }
4344
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004345 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4346 // long quotaBytes split up into two ints to fit in message
4347 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4348 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4349 }
4350
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004351 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004352 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004353 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004354 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004355 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004356 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004357 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004358 }
4359 }
4360
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004361 private void removeInterfaceQuotaAsync(String iface) {
4362 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4363 }
4364
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004365 private void removeInterfaceQuota(String iface) {
4366 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004367 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004368 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004369 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004370 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004371 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004372 }
4373 }
4374
Felipe Leme70c57c22016-03-29 10:45:13 -07004375 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4376 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004377 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004378 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004379 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004380 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4381 } catch (RemoteException e) {
4382 // ignored; service lives in system_server
4383 }
4384 }
4385
4386 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4387 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4388 try {
4389 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4390 } catch (IllegalStateException e) {
4391 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004392 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004393 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004394 }
4395 }
4396
Felipe Lemebc853dd2016-09-08 13:26:55 -07004397 private static final int CHAIN_TOGGLE_NONE = 0;
4398 private static final int CHAIN_TOGGLE_ENABLE = 1;
4399 private static final int CHAIN_TOGGLE_DISABLE = 2;
4400 @Retention(RetentionPolicy.SOURCE)
4401 @IntDef(flag = false, value = {
4402 CHAIN_TOGGLE_NONE,
4403 CHAIN_TOGGLE_ENABLE,
4404 CHAIN_TOGGLE_DISABLE
4405 })
4406 public @interface ChainToggleType {
4407 }
4408
4409 /**
4410 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004411 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004412 *
4413 * @param chain firewall chain.
4414 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4415 * @param toggle whether the chain should be enabled, disabled, or not changed.
4416 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004417 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004418 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004419 if (uidRules != null) {
4420 setUidFirewallRulesUL(chain, uidRules);
4421 }
4422 if (toggle != CHAIN_TOGGLE_NONE) {
4423 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4424 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004425 }
4426
Amith Yamasani15e472352015-04-24 19:06:07 -07004427 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004428 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4429 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4430 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004431 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004432 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004433 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004434 int size = uidRules.size();
4435 int[] uids = new int[size];
4436 int[] rules = new int[size];
4437 for(int index = size - 1; index >= 0; --index) {
4438 uids[index] = uidRules.keyAt(index);
4439 rules[index] = uidRules.valueAt(index);
4440 }
4441 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004442 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004443 } catch (IllegalStateException e) {
4444 Log.wtf(TAG, "problem setting firewall uid rules", e);
4445 } catch (RemoteException e) {
4446 // ignored; service lives in system_server
4447 }
4448 }
4449
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004450 /**
4451 * Add or remove a uid to the firewall blacklist for all network ifaces.
4452 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004453 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004454 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4455 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4456 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004457 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004458 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004459 if (chain == FIREWALL_CHAIN_DOZABLE) {
4460 mUidFirewallDozableRules.put(uid, rule);
4461 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4462 mUidFirewallStandbyRules.put(uid, rule);
4463 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4464 mUidFirewallPowerSaveRules.put(uid, rule);
4465 }
4466
4467 try {
4468 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004469 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004470 } catch (IllegalStateException e) {
4471 Log.wtf(TAG, "problem setting firewall uid rules", e);
4472 } catch (RemoteException e) {
4473 // ignored; service lives in system_server
4474 }
4475 } finally {
4476 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004477 }
4478 }
4479
4480 /**
4481 * Add or remove a uid to the firewall blacklist for all network ifaces.
4482 */
Felipe Lemef0823852016-06-08 13:43:08 -07004483 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004484 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4485 mFirewallChainStates.get(chain) == enable) {
4486 // All is the same, nothing to do.
4487 return;
4488 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004489 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004490 try {
4491 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004492 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004493 } catch (IllegalStateException e) {
4494 Log.wtf(TAG, "problem enable firewall chain", e);
4495 } catch (RemoteException e) {
4496 // ignored; service lives in system_server
4497 }
4498 }
4499
Felipe Leme03e95e22016-09-09 09:25:31 -07004500 /**
4501 * Resets all firewall rules associated with an UID.
4502 */
4503 private void resetUidFirewallRules(int uid) {
4504 try {
4505 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4506 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4507 mNetworkManager
4508 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4509 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4510 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4511 } catch (IllegalStateException e) {
4512 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4513 } catch (RemoteException e) {
4514 // ignored; service lives in system_server
4515 }
4516 }
4517
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004518 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004519 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004520 return getNetworkTotalBytes(template, start, end);
4521 }
4522
4523 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004524 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004525 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004526 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004527 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004528 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004529 }
4530 }
4531
4532 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4533 try {
4534 return mNetworkStats.getNetworkUidBytes(template, start, end);
4535 } catch (RuntimeException e) {
4536 Slog.w(TAG, "Failed to read network stats: " + e);
4537 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004538 }
4539 }
4540
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004541 private boolean isBandwidthControlEnabled() {
4542 final long token = Binder.clearCallingIdentity();
4543 try {
4544 return mNetworkManager.isBandwidthControlEnabled();
4545 } catch (RemoteException e) {
4546 // ignored; service lives in system_server
4547 return false;
4548 } finally {
4549 Binder.restoreCallingIdentity(token);
4550 }
4551 }
4552
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004553 private static Intent buildAllowBackgroundDataIntent() {
4554 return new Intent(ACTION_ALLOW_BACKGROUND);
4555 }
4556
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004557 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4558 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004559 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4560 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4561 return intent;
4562 }
4563
4564 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4565 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4566 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004567 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4568 return intent;
4569 }
4570
Wei Liu546cb772016-07-21 16:19:01 -07004571 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004572 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004573 intent.setComponent(ComponentName.unflattenFromString(
4574 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004575 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4576 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4577 return intent;
4578 }
4579
Wei Liu546cb772016-07-21 16:19:01 -07004580 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004581 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004582 intent.setComponent(ComponentName.unflattenFromString(
4583 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004584 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4585 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4586 return intent;
4587 }
4588
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004589 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004590 public void addIdleHandler(IdleHandler handler) {
4591 mHandler.getLooper().getQueue().addIdleHandler(handler);
4592 }
4593
jackqdyulei29c82ab2017-03-10 14:09:16 -08004594 @VisibleForTesting
4595 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4596 mRestrictBackgroundPowerState = result;
4597
4598 boolean restrictBackground = result.batterySaverEnabled;
4599 boolean shouldInvokeRestrictBackground;
4600 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4601 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4602
4603 if (result.globalBatterySaverEnabled) {
4604 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4605 // turn it on.
4606 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4607 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4608 localRestrictBgChangedInBsm = false;
4609 } else {
4610 // Try to restore the restrictBackground if it doesn't change in bsm
4611 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4612 restrictBackground = mRestrictBackgroundBeforeBsm;
4613 }
4614
4615 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004616 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004617 }
4618
4619 // Change it at last so setRestrictBackground() won't affect this variable
4620 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4621 }
4622
Jeff Sharkey1b861272011-05-22 00:34:52 -07004623 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4624 final int size = source.size();
4625 for (int i = 0; i < size; i++) {
4626 target.put(source.keyAt(i), true);
4627 }
4628 }
4629
Stuart Scottf1fb3972015-04-02 18:00:02 -07004630 @Override
4631 public void factoryReset(String subscriber) {
4632 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4633
Stuart Scotte3e314d2015-04-20 14:07:45 -07004634 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4635 return;
4636 }
4637
Stuart Scottf1fb3972015-04-02 18:00:02 -07004638 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004639 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004640 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4641 for (NetworkPolicy policy : policies) {
4642 if (policy.template.equals(template)) {
4643 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4644 policy.inferred = false;
4645 policy.clearSnooze();
4646 }
4647 }
4648 setNetworkPolicies(policies);
4649
4650 // Turn restrict background data off
4651 setRestrictBackground(false);
4652
Stuart Scotte3e314d2015-04-20 14:07:45 -07004653 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4654 // Remove app's "restrict background data" flag
4655 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4656 setUidPolicy(uid, POLICY_NONE);
4657 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004658 }
4659 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004660
Sudheer Shankab8f23162017-08-04 13:30:10 -07004661 @Override
4662 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4663 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4664 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4665 }
4666
4667 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4668 final int uidRules;
4669 final boolean isBackgroundRestricted;
4670 synchronized (mUidRulesFirstLock) {
4671 uidRules = mUidRules.get(uid, RULE_NONE);
4672 isBackgroundRestricted = mRestrictBackground;
4673 }
4674 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004675 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004676 return true;
4677 }
4678 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004679 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004680 return false;
4681 }
4682 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004683 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004684 return true;
4685 }
4686 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004687 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004688 return false;
4689 }
4690 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004691 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004692 return false;
4693 }
4694 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004695 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004696 return true;
4697 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004698 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004699 return false;
4700 }
4701
Felipe Lemed17fda42016-04-29 11:12:45 -07004702 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4703
4704 @Override
4705 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004706 synchronized (mUidRulesFirstLock) {
4707 boolean changed = removeUserStateUL(userId, false);
4708 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004709 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004710 synchronized (mNetworkPoliciesSecondLock) {
4711 writePolicyAL();
4712 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004713 }
4714 }
4715 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004716
4717 /**
4718 * @return true if the given uid is restricted from doing networking on metered networks.
4719 */
4720 @Override
4721 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4722 final int uidRules;
4723 final boolean isBackgroundRestricted;
4724 synchronized (mUidRulesFirstLock) {
4725 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4726 isBackgroundRestricted = mRestrictBackground;
4727 }
4728 return isBackgroundRestricted
4729 && !hasRule(uidRules, RULE_ALLOW_METERED)
4730 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4731 }
4732
4733 /**
4734 * @return true if networking is blocked on the given interface for the given uid according
4735 * to current networking policies.
4736 */
4737 @Override
4738 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004739 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004740 synchronized (mNetworkPoliciesSecondLock) {
4741 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004742 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004743 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004744 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004745
4746 @Override
4747 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4748 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004749 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004750 if (added) {
4751 mPowerSaveTempWhitelistAppIds.put(appId, true);
4752 } else {
4753 mPowerSaveTempWhitelistAppIds.delete(appId);
4754 }
4755 updateRulesForTempWhitelistChangeUL(appId);
4756 }
4757 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004758
4759 @Override
4760 public SubscriptionPlan getSubscriptionPlan(Network network) {
4761 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004762 final int subId = getSubIdLocked(network);
4763 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004764 }
4765 }
4766
4767 @Override
4768 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004769 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004770 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004771 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004772 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004773 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004774 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4775 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4776 }
4777
4778 if (quotaType == QUOTA_TYPE_JOBS) {
4779 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4780 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4781 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4782 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4783 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4784 } else {
4785 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4786 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004787 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004788
4789 @Override
4790 public void onAdminDataAvailable() {
4791 mAdminDataAvailableLatch.countDown();
4792 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004793
4794 @Override
4795 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4796 setMeteredRestrictedPackagesInternal(packageNames, userId);
4797 }
4798
4799 @Override
4800 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4801 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4802 userId, 0, packageNames).sendToTarget();
4803 }
4804 }
4805
4806 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4807 synchronized (mUidRulesFirstLock) {
4808 final Set<Integer> newRestrictedUids = new ArraySet<>();
4809 for (String packageName : packageNames) {
4810 final int uid = getUidForPackage(packageName, userId);
4811 if (uid >= 0) {
4812 newRestrictedUids.add(uid);
4813 }
4814 }
4815 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4816 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4817 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4818 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4819 }
4820 }
4821
4822 private int getUidForPackage(String packageName, int userId) {
4823 try {
4824 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4825 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4826 } catch (NameNotFoundException e) {
4827 return -1;
4828 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004829 }
4830
4831 private int parseSubId(NetworkState state) {
4832 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4833 int subId = INVALID_SUBSCRIPTION_ID;
4834 if (state != null && state.networkCapabilities != null
4835 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4836 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4837 if (spec instanceof StringNetworkSpecifier) {
4838 try {
4839 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4840 } catch (NumberFormatException e) {
4841 }
4842 }
4843 }
4844 return subId;
4845 }
4846
Andreas Gampea36dc622018-02-05 17:19:22 -08004847 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004848 private int getSubIdLocked(Network network) {
4849 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004850 }
4851
Andreas Gampea36dc622018-02-05 17:19:22 -08004852 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004853 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4854 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06004855 if (!ArrayUtils.isEmpty(plans)) {
4856 for (SubscriptionPlan plan : plans) {
4857 if (plan.getCycleRule().isRecurring()) {
4858 // Recurring plans will always have an active cycle
4859 return plan;
4860 } else {
4861 // Non-recurring plans need manual test for active cycle
4862 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
4863 if (cycle.contains(ZonedDateTime.now(mClock))) {
4864 return plan;
4865 }
4866 }
4867 }
4868 }
4869 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09004870 }
4871
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004872 /**
4873 * This will only ever be called once - during device boot.
4874 */
4875 private void waitForAdminData() {
4876 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4877 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4878 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4879 }
4880 }
4881
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004882 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4883 Set<Integer> newRestrictedUids) {
4884 if (oldRestrictedUids == null) {
4885 for (int uid : newRestrictedUids) {
4886 updateRulesForDataUsageRestrictionsUL(uid);
4887 }
4888 return;
4889 }
4890 for (int uid : oldRestrictedUids) {
4891 if (!newRestrictedUids.contains(uid)) {
4892 updateRulesForDataUsageRestrictionsUL(uid);
4893 }
4894 }
4895 for (int uid : newRestrictedUids) {
4896 if (!oldRestrictedUids.contains(uid)) {
4897 updateRulesForDataUsageRestrictionsUL(uid);
4898 }
4899 }
4900 }
4901
4902 private boolean isRestrictedByAdminUL(int uid) {
4903 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4904 UserHandle.getUserId(uid));
4905 return restrictedUids != null && restrictedUids.contains(uid);
4906 }
4907
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004908 private static boolean hasRule(int uidRules, int rule) {
4909 return (uidRules & rule) != 0;
4910 }
4911
Jeff Sharkey2e471452018-01-19 18:02:47 +09004912 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4913 return (val != null) ? val : new NetworkState[0];
4914 }
4915
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06004916 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
4917 String key, boolean defaultValue) {
4918 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
4919 }
4920
Chris Wren193ae6b2017-03-31 15:17:11 -04004921 private class NotificationId {
4922 private final String mTag;
4923 private final int mId;
4924
4925 NotificationId(NetworkPolicy policy, int type) {
4926 mTag = buildNotificationTag(policy, type);
4927 mId = type;
4928 }
4929
4930 @Override
4931 public boolean equals(Object o) {
4932 if (this == o) return true;
4933 if (!(o instanceof NotificationId)) return false;
4934 NotificationId that = (NotificationId) o;
4935 return Objects.equals(mTag, that.mTag);
4936 }
4937
4938 @Override
4939 public int hashCode() {
4940 return Objects.hash(mTag);
4941 }
4942
4943 /**
4944 * Build unique tag that identifies an active {@link NetworkPolicy}
4945 * notification of a specific type, like {@link #TYPE_LIMIT}.
4946 */
4947 private String buildNotificationTag(NetworkPolicy policy, int type) {
4948 return TAG + ":" + policy.template.hashCode() + ":" + type;
4949 }
4950
4951 public String getTag() {
4952 return mTag;
4953 }
4954
4955 public int getId() {
4956 return mId;
4957 }
4958 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004959}