blob: efe2e039f40598a783da9a66917cf6d5b7a0cc3d [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;
Jeff Sharkey9252b342018-01-19 07:58:35 +090042import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070043import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070044import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070045import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070046import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070047import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080048import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070049import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
50import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070051import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070052import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060053import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070055import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070056import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070058import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070061import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070063import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080064import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
65import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060066import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070067import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070068import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070069import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070070import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070071import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080072import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060073import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
74import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
75import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070079import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070080import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060081import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090082import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080083
Jeff Sharkey854b2b12012-04-13 16:03:40 -070084import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070086import static com.android.internal.util.XmlUtils.readBooleanAttribute;
87import static com.android.internal.util.XmlUtils.readIntAttribute;
88import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060089import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070090import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
91import static com.android.internal.util.XmlUtils.writeIntAttribute;
92import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060093import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070094import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070095import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
96import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
97import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
98import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
99import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
100import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700102import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600103
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700104import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800105import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700106import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700107
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700109import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900110import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700111import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700112import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800113import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700114import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700115import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700116import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700117import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700118import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700119import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700120import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700121import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700123import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600124import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700125import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700126import android.content.Intent;
127import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700128import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700129import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700130import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700131import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700132import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700133import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700134import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600135import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700137import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700138import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700139import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700140import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700141import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600142import android.net.Network;
143import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700144import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600146import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700147import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600148import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900149import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700151import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700152import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900153import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600154import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700155import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700156import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700157import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700158import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700159import android.os.Environment;
160import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700161import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700162import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700163import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700164import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700165import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700166import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700167import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700168import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700169import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600170import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800171import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700172import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700173import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600174import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700175import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700176import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700177import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600178import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700179import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700180import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700182import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100183import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700184import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600185import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800186import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600187import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700188import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400189import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700190import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700191import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700192import android.util.ArrayMap;
193import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700194import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900195import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700196import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700197import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600198import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700199import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600200import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700201import android.util.SparseBooleanArray;
202import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900203import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700205
Jeff Sharkey497e4432011-06-14 17:27:29 -0700206import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700207import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800208import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400209import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500210import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700211import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800212import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800213import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600214import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700216import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600217import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700218import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700219import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700220import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800221import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600222
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600223import libcore.io.IoUtils;
224
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700225import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700226import org.xmlpull.v1.XmlSerializer;
227
228import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700229import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230import java.io.FileInputStream;
231import java.io.FileNotFoundException;
232import java.io.FileOutputStream;
233import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700234import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700235import java.lang.annotation.Retention;
236import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100237import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700238import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900239import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600240import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700241import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600242import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900243import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700245import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600246import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400247import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800248import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800249import java.util.concurrent.CountDownLatch;
250import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700252/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700253 * Service that maintains low-level network policy rules, using
254 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700255 * <p>
256 * Derives active rules by combining a given policy with other system status,
257 * and delivers to listeners, such as {@link ConnectivityManager}, for
258 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700259 *
260 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000261 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700262 * <ul>
263 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
264 * rules).
265 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
266 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000267 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
268 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700269 * </ul>
270 *
271 * <p>
272 * As such, methods that require synchronization have the following prefixes:
273 * <ul>
274 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
275 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000276 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
277 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700278 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700279 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700280public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700281 static final String TAG = NetworkPolicyLogger.TAG;
282 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
283 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700284
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900285 /**
286 * No opportunistic quota could be calculated from user data plan or data settings.
287 */
288 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
289
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700290 private static final int VERSION_INIT = 1;
291 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700292 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800293 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800294 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800295 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700296 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700297 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700298 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700299 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600300 private static final int VERSION_ADDED_CYCLE = 11;
301 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800303 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400304 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800305 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400306 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800307 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400308 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900309 @VisibleForTesting
310 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700311
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312 private static final String TAG_POLICY_LIST = "policy-list";
313 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600314 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700316 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800317 private static final String TAG_WHITELIST = "whitelist";
318 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800319 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320
321 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700322 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
324 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700325 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600326 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
327 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
328 private static final String ATTR_CYCLE_START = "cycleStart";
329 private static final String ATTR_CYCLE_END = "cycleEnd";
330 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331 private static final String ATTR_WARNING_BYTES = "warningBytes";
332 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700333 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800334 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
335 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800336 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700337 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700338 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700339 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600341 private static final String ATTR_SUB_ID = "subId";
342 private static final String ATTR_TITLE = "title";
343 private static final String ATTR_SUMMARY = "summary";
344 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
345 private static final String ATTR_USAGE_BYTES = "usageBytes";
346 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600347 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800349 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800350 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800351 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800352 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700353 private static final String ACTION_SNOOZE_RAPID =
354 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700355
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800356 /**
357 * Indicates the maximum wait time for admin data to be available;
358 */
359 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
360
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600361 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
362 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
363 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
364 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
365
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700366 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700367 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800368 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800369 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700370 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700371 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
372 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700373 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700374 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900375 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800376 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700377
Makoto Onuki8e777332017-03-28 11:25:47 -0700378 private static final int UID_MSG_STATE_CHANGED = 100;
379 private static final int UID_MSG_GONE = 101;
380
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600381 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
382
Jeff Sharkey75279902011-05-24 18:39:45 -0700383 private final Context mContext;
384 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700385 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700386 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700387 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700388 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700389 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700390 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700391
392 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700393 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700394 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800395 @GuardedBy("mUidRulesFirstLock")
396 private PowerSaveState mRestrictBackgroundPowerState;
397
398 // Store the status of restrict background before turning on battery saver.
399 // Used to restore mRestrictBackground when battery saver is turned off.
400 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700401
Sudheer Shanka543339f2017-07-28 15:18:07 -0700402 // Denotes the status of restrict background read from disk.
403 private boolean mLoadedRestrictBackground;
404
Felipe Lemef0823852016-06-08 13:43:08 -0700405 // See main javadoc for instructions on how to use these locks.
406 final Object mUidRulesFirstLock = new Object();
407 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700408
Felipe Lemef0823852016-06-08 13:43:08 -0700409 @GuardedBy("allLocks") volatile boolean mSystemReady;
410
Felipe Lemef0823852016-06-08 13:43:08 -0700411 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
412 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
413 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800414 // Store whether user flipped restrict background in battery saver mode
415 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700416
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700417 private final boolean mSuppressDefaultPolicy;
418
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800419 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
420
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700421 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600422 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800423 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700424
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600425 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600426 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600427 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600428 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600429 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600430 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600431
Jeff Sharkey9252b342018-01-19 07:58:35 +0900432 /** Map from subId to daily opportunistic quota. */
433 @GuardedBy("mNetworkPoliciesSecondLock")
434 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
435
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700436 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700437 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700438 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700439 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700440
Felipe Lemef0823852016-06-08 13:43:08 -0700441 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700442 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700443 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700444 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700445 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800446 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700447
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700448 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700449 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700450 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
451
Jeff Sharkey32566012014-12-02 18:30:14 -0800452 /**
453 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700454 * in power save mode, except device idle (doze) still applies.
455 * TODO: An int array might be sufficient
456 */
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700458 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
459
460 /**
461 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800462 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700463 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800464 */
Felipe Lemef0823852016-06-08 13:43:08 -0700465 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700466 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700467
Felipe Lemef0823852016-06-08 13:43:08 -0700468 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700469 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
470
Felipe Lemeb85a6372016-01-14 16:16:16 -0800471 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800472 * UIDs that have been initially white-listed by system to avoid restricted background.
473 */
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800475 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
476 new SparseBooleanArray();
477
478 /**
479 * UIDs that have been initially white-listed by system to avoid restricted background,
480 * but later revoked by user.
481 */
Felipe Lemef0823852016-06-08 13:43:08 -0700482 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800483 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
484 new SparseBooleanArray();
485
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700486 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700487 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800488 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700489 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700490 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800491 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700492
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700493 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700494 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400495 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700496
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700497 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700498 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800499 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700500
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600501 /** Map from network ID to last observed meteredness state */
502 @GuardedBy("mNetworkPoliciesSecondLock")
503 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
504
Jeff Sharkey9252b342018-01-19 07:58:35 +0900505 /** Map from netId to subId as of last update */
506 @GuardedBy("mNetworkPoliciesSecondLock")
507 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
508
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800509 /**
510 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
511 * userId to restricted uids which belong to that user.
512 */
513 @GuardedBy("mUidRulesFirstLock")
514 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
515
Jeff Sharkey32566012014-12-02 18:30:14 -0800516 private final RemoteCallbackList<INetworkPolicyListener>
517 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700518
Dianne Hackborn497175b2014-07-01 12:56:08 -0700519 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700520 @VisibleForTesting
521 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700522
523 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700524
Felipe Lemef0823852016-06-08 13:43:08 -0700525 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700526 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700527
Svet Ganov16a16892015-04-16 10:32:04 -0700528 private final AppOpsManager mAppOps;
529
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800530 private final IPackageManager mIPm;
531
Sudheer Shankae7361852017-03-07 11:51:46 -0800532 private ActivityManagerInternal mActivityManagerInternal;
533
Sudheer Shanka352dc572017-09-22 17:09:38 -0700534 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800535
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700536 // TODO: keep whitelist of system-critical services that should never have
537 // rules enforced, such as system, phone, and radio UIDs.
538
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700539 // TODO: migrate notifications to SystemUI
540
Jeff Sharkey75279902011-05-24 18:39:45 -0700541 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700542 INetworkManagementService networkManagement) {
543 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
544 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700545 }
546
Jeff Sharkey9911a282018-02-14 22:29:11 -0700547 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700548 return new File(Environment.getDataDirectory(), "system");
549 }
550
Jeff Sharkey9911a282018-02-14 22:29:11 -0700551 private static @NonNull Clock getDefaultClock() {
552 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
553 Clock.systemUTC());
554 }
555
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700556 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700557 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
558 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700559 mContext = checkNotNull(context, "missing context");
560 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700561 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700562 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700563 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700564 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700565 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700566 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700567 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700568
Amith Yamasani450a16b2013-09-18 16:28:50 -0700569 HandlerThread thread = new HandlerThread(TAG);
570 thread.start();
571 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700572
Makoto Onuki8e777332017-03-28 11:25:47 -0700573 // We create another thread for the UID events, which are more time-critical.
574 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
575 /*allowIo=*/ false);
576 mUidEventThread.start();
577 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
578
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700579 mSuppressDefaultPolicy = suppressDefaultPolicy;
580
Dianne Hackborne17b4452018-01-10 13:15:40 -0800581 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700582
583 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800584
Felipe Lemed17fda42016-04-29 11:12:45 -0700585 // Expose private service for system components to use.
586 LocalServices.addService(NetworkPolicyManagerInternal.class,
587 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700588 }
589
590 public void bindConnectivityManager(IConnectivityManager connManager) {
591 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700592 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700593
Felipe Lemef0823852016-06-08 13:43:08 -0700594 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700595 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700596 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
597 mPowerSaveWhitelistExceptIdleAppIds.clear();
598 if (whitelist != null) {
599 for (int uid : whitelist) {
600 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
601 }
602 }
603 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700604 mPowerSaveWhitelistAppIds.clear();
605 if (whitelist != null) {
606 for (int uid : whitelist) {
607 mPowerSaveWhitelistAppIds.put(uid, true);
608 }
609 }
610 } catch (RemoteException e) {
611 }
612 }
613
Felipe Lemea9505cc2016-02-26 10:28:41 -0800614 /**
615 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
616 * revoke the whitelist.
617 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700618 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 */
Felipe Lemef0823852016-06-08 13:43:08 -0700620 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800621 final List<UserInfo> users = mUserManager.getUsers();
622 final int numberUsers = users.size();
623
Felipe Lemea110eec2016-04-29 09:58:06 -0700624 boolean changed = false;
625 for (int i = 0; i < numberUsers; i++) {
626 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700627 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700628 }
629 return changed;
630 }
631
Felipe Lemef0823852016-06-08 13:43:08 -0700632 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700633 final SystemConfig sysConfig = SystemConfig.getInstance();
634 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800635 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
636 boolean changed = false;
637 for (int i = 0; i < allowDataUsage.size(); i++) {
638 final String pkg = allowDataUsage.valueAt(i);
639 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700640 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
641 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800642 final ApplicationInfo app;
643 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700644 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800645 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700646 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
647 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800648 continue;
649 }
650 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700651 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
652 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800653 continue;
654 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700655 final int uid = UserHandle.getUid(userId, app.uid);
656 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
657 if (LOGD)
658 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
659 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800660 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700661 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700662 if (LOGD)
663 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
664 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700665 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700666 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800667 }
668 }
669 return changed;
670 }
671
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800672 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700673 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800674 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700675 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800676 // Boost thread's priority during system server init
677 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700678 if (!isBandwidthControlEnabled()) {
679 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
680 return;
681 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700682
Felipe Leme873a83a2016-09-07 11:34:10 -0700683 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700684 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700685
Felipe Leme873a83a2016-09-07 11:34:10 -0700686 synchronized (mUidRulesFirstLock) {
687 synchronized (mNetworkPoliciesSecondLock) {
688 updatePowerSaveWhitelistUL();
689 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
690 mPowerManagerInternal.registerLowPowerModeObserver(
691 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800692 @Override
693 public int getServiceType() {
694 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700695 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800696
697 @Override
698 public void onLowPowerModeChanged(PowerSaveState result) {
699 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800700 if (LOGD) {
701 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
702 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800703 synchronized (mUidRulesFirstLock) {
704 if (mRestrictPower != enabled) {
705 mRestrictPower = enabled;
706 updateRulesForRestrictPowerUL();
707 }
708 }
709 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800710 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800711 mRestrictPower = mPowerManagerInternal.getLowPowerState(
712 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700713
714 mSystemReady = true;
715
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800716 waitForAdminData();
717
Felipe Leme873a83a2016-09-07 11:34:10 -0700718 // read policy from disk
719 readPolicyAL();
720
jackqdyulei29c82ab2017-03-10 14:09:16 -0800721 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700722 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800723 mRestrictBackgroundPowerState = mPowerManagerInternal
724 .getLowPowerState(ServiceType.DATA_SAVER);
725 final boolean localRestrictBackground =
726 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700727 if (localRestrictBackground && !mLoadedRestrictBackground) {
728 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800729 }
730 mPowerManagerInternal.registerLowPowerModeObserver(
731 new PowerManagerInternal.LowPowerModeListener() {
732 @Override
733 public int getServiceType() {
734 return ServiceType.DATA_SAVER;
735 }
736
737 @Override
738 public void onLowPowerModeChanged(PowerSaveState result) {
739 synchronized (mUidRulesFirstLock) {
740 updateRestrictBackgroundByLowPowerModeUL(result);
741 }
742 }
743 });
744
Felipe Leme873a83a2016-09-07 11:34:10 -0700745 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
746 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700747 }
Felipe Lemef0823852016-06-08 13:43:08 -0700748
Sudheer Shanka543339f2017-07-28 15:18:07 -0700749 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700750 updateRulesForGlobalChangeAL(false);
751 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700752 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800753 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700754
Sudheer Shankae7361852017-03-07 11:51:46 -0800755 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700756 try {
757 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000758 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800759 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700760 mNetworkManager.registerObserver(mAlertObserver);
761 } catch (RemoteException e) {
762 // ignored; both services live in system_server
763 }
764
765 // listen for changes to power save whitelist
766 final IntentFilter whitelistFilter = new IntentFilter(
767 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
768 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
769
Felipe Leme873a83a2016-09-07 11:34:10 -0700770 // watch for network interfaces to be claimed
771 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
772 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
773
774 // listen for package changes to update policy
775 final IntentFilter packageFilter = new IntentFilter();
776 packageFilter.addAction(ACTION_PACKAGE_ADDED);
777 packageFilter.addDataScheme("package");
778 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
779
780 // listen for UID changes to update policy
781 mContext.registerReceiver(
782 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
783
784 // listen for user changes to update policy
785 final IntentFilter userFilter = new IntentFilter();
786 userFilter.addAction(ACTION_USER_ADDED);
787 userFilter.addAction(ACTION_USER_REMOVED);
788 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
789
790 // listen for stats update events
791 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
792 mContext.registerReceiver(
793 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
794
795 // listen for restrict background changes from notifications
796 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
797 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
798
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700799 // Listen for snooze from notifications
800 mContext.registerReceiver(mSnoozeReceiver,
801 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
802 mContext.registerReceiver(mSnoozeReceiver,
803 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700804
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600805 // listen for configured wifi networks to be loaded
806 final IntentFilter wifiFilter =
807 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
808 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700809
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700810 // listen for carrier config changes to update data cycle information
811 final IntentFilter carrierConfigFilter = new IntentFilter(
812 ACTION_CARRIER_CONFIG_CHANGED);
813 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
814
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600815 // listen for meteredness changes
816 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
817 new NetworkRequest.Builder().build(), mNetworkCallback);
818
Felipe Leme873a83a2016-09-07 11:34:10 -0700819 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800820 // tell systemReady() that the service has been initialized
821 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700822 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800823 // Restore the default priority after init is done
824 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700825 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700826 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700827 }
828
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800829 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
830 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
831 mHandler.post(() -> initService(initCompleteSignal));
832 return initCompleteSignal;
833 }
834
835 public void systemReady(CountDownLatch initCompleteSignal) {
836 // wait for initService to complete
837 try {
838 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
839 throw new IllegalStateException("Service " + TAG +" init timeout");
840 }
841 } catch (InterruptedException e) {
842 Thread.currentThread().interrupt();
843 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
844 }
845 }
846
Sudheer Shankac9d94072017-02-22 22:13:55 +0000847 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700848 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700849 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
850 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700851 }
852
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700853 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700854 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700855 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700856
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700857 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700858 }
859
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700860 @Override public void onUidIdle(int uid, boolean disabled) {
861 }
862
863 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700864 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700865 };
866
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700867 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700868 @Override
869 public void onReceive(Context context, Intent intent) {
870 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700871 synchronized (mUidRulesFirstLock) {
872 updatePowerSaveWhitelistUL();
873 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700874 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700875 }
876 }
877 };
878
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700879 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700880 @Override
881 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700882 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700883
884 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700885 final int uid = intent.getIntExtra(EXTRA_UID, -1);
886 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700887
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700888 if (ACTION_PACKAGE_ADDED.equals(action)) {
889 // update rules for UID, since it might be subject to
890 // global background data policy
891 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700892 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700893 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700894 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700895 }
896 }
897 };
898
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700899 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700900 @Override
901 public void onReceive(Context context, Intent intent) {
902 // on background handler thread, and UID_REMOVED is protected
903
904 final int uid = intent.getIntExtra(EXTRA_UID, -1);
905 if (uid == -1) return;
906
907 // remove any policy and update rules to clean up
908 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700909 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700910 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700911 synchronized (mNetworkPoliciesSecondLock) {
912 writePolicyAL();
913 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700914 }
915 }
916 };
917
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700918 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700919 @Override
920 public void onReceive(Context context, Intent intent) {
921 // on background handler thread, and USER_ADDED and USER_REMOVED
922 // broadcasts are protected
923
924 final String action = intent.getAction();
925 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
926 if (userId == -1) return;
927
Amith Yamasani15e472352015-04-24 19:06:07 -0700928 switch (action) {
929 case ACTION_USER_REMOVED:
930 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700931 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800932 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700933 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700934 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800935 // Removing outside removeUserStateUL since that can also be called when
936 // user resets app preferences.
937 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700938 if (action == ACTION_USER_ADDED) {
939 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700940 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700941 }
942 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700943 synchronized (mNetworkPoliciesSecondLock) {
944 updateRulesForGlobalChangeAL(true);
945 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700946 }
947 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700948 }
949 }
950 };
951
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700952 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700953 * Receiver that watches for {@link INetworkStatsService} updates, which we
954 * use to check against {@link NetworkPolicy#warningBytes}.
955 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700956 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700957 @Override
958 public void onReceive(Context context, Intent intent) {
959 // on background handler thread, and verified
960 // READ_NETWORK_USAGE_HISTORY permission above.
961
Felipe Lemef0823852016-06-08 13:43:08 -0700962 synchronized (mNetworkPoliciesSecondLock) {
963 updateNetworkEnabledNL();
964 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700965 }
966 }
967 };
968
969 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700970 * Receiver that watches for {@link Notification} control of
971 * {@link #mRestrictBackground}.
972 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700973 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700974 @Override
975 public void onReceive(Context context, Intent intent) {
976 // on background handler thread, and verified MANAGE_NETWORK_POLICY
977 // permission above.
978
979 setRestrictBackground(false);
980 }
981 };
982
983 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800984 * Receiver that watches for {@link Notification} control of
985 * {@link NetworkPolicy#lastWarningSnooze}.
986 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700987 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800988 @Override
989 public void onReceive(Context context, Intent intent) {
990 // on background handler thread, and verified MANAGE_NETWORK_POLICY
991 // permission above.
992
993 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700994 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
995 performSnooze(template, TYPE_WARNING);
996 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
997 performSnooze(template, TYPE_RAPID);
998 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800999 }
1000 };
1001
1002 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001003 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001004 * we can perform upgrade logic. After initial upgrade logic, it updates
1005 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001006 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001007 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001008 @Override
1009 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001010 synchronized (mUidRulesFirstLock) {
1011 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001012 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001013 }
1014 }
1015 // Only need to perform upgrade logic once
1016 mContext.unregisterReceiver(this);
1017 }
1018 };
1019
1020 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1021 @Override
1022 public void onCapabilitiesChanged(Network network,
1023 NetworkCapabilities networkCapabilities) {
1024 if (network == null || networkCapabilities == null) return;
1025
1026 synchronized (mNetworkPoliciesSecondLock) {
1027 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1028 final boolean newMetered = !networkCapabilities
1029 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1030
1031 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001032 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001033 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001034 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001035 }
1036 }
1037 }
1038 };
1039
1040 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 * Observer that watches for {@link INetworkManagementService} alerts.
1042 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001043 final private INetworkManagementEventObserver mAlertObserver
1044 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 @Override
1046 public void limitReached(String limitName, String iface) {
1047 // only someone like NMS should be calling us
1048 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1049
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001050 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1051 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001052 }
1053 }
1054 };
1055
1056 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1058 * to show visible notifications as needed.
1059 */
Felipe Lemef0823852016-06-08 13:43:08 -07001060 void updateNotificationsNL() {
1061 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001062
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001064 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001065 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001066
1067 // TODO: when switching to kernel notifications, compute next future
1068 // cycle boundary to recompute notifications.
1069
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001070 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001071 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001072 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1073 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001074 // ignore policies that aren't relevant to user
1075 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001076 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001077
Jeff Sharkey53313d72017-07-13 16:47:32 -06001078 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1079 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001080 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1081 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1082 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001084 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001085 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001086 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1087 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001088 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001090 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001091 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001092 }
1093
Jeff Sharkey497e4432011-06-14 17:27:29 -07001094 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001095 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001097 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1098 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001099 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001100 }
1101 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001102
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001103 // Warn if average usage over last 4 days is on track to blow pretty
1104 // far past the plan limits.
1105 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001106 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001107 final long recentStart = now - recentDuration;
1108 final long recentEnd = now;
1109 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001110
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001111 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001112 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001113 final long alertBytes = (policy.limitBytes * 3) / 2;
1114
1115 if (LOGD) {
1116 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1117 + projectedBytes + " alert " + alertBytes);
1118 }
1119
1120 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1121 - DateUtils.DAY_IN_MILLIS;
1122 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001123 enqueueNotification(policy, TYPE_RAPID, 0,
1124 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001125 }
1126 }
1127 }
1128
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001130 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001131 final NotificationId notificationId = beforeNotifs.valueAt(i);
1132 if (!mActiveNotifs.contains(notificationId)) {
1133 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 }
1135 }
1136 }
1137
1138 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001139 * Attempt to find a specific app to blame for rapid data usage during the
1140 * given time period.
1141 */
1142 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1143 long start, long end) {
1144 long totalBytes = 0;
1145 long maxBytes = 0;
1146 int maxUid = 0;
1147
1148 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1149 NetworkStats.Entry entry = null;
1150 for (int i = 0; i < stats.size(); i++) {
1151 entry = stats.getValues(i, entry);
1152 final long bytes = entry.rxBytes + entry.txBytes;
1153 totalBytes += bytes;
1154 if (bytes > maxBytes) {
1155 maxBytes = bytes;
1156 maxUid = entry.uid;
1157 }
1158 }
1159
1160 // Only point blame if the majority of usage was done by a single app.
1161 // TODO: support shared UIDs
1162 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1163 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001164 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001165 try {
1166 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1167 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1168 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1169 } catch (NameNotFoundException ignored) {
1170 }
1171 }
1172 }
1173
1174 return null;
1175 }
1176
1177 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001178 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001179 * current device state, such as when
1180 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1181 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001182 */
1183 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001184 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001185 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1186 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001187
Jeff Sharkey32566012014-12-02 18:30:14 -08001188 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001189 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001190 for (int subId : subIds) {
1191 final String subscriberId = tele.getSubscriberId(subId);
1192 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001193 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1194 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001195 if (template.matches(probeIdent)) {
1196 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001197 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001198 }
1199 return false;
1200 } else {
1201 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001202 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001203 }
1204
1205 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001206 * Notify that given {@link NetworkTemplate} is over
1207 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1208 */
Felipe Lemef0823852016-06-08 13:43:08 -07001209 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001210 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001211 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001212 mOverLimitNotified.add(template);
1213 }
1214 }
1215
Felipe Lemef0823852016-06-08 13:43:08 -07001216 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001217 mOverLimitNotified.remove(template);
1218 }
1219
1220 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001221 * Show notification for combined {@link NetworkPolicy} and specific type,
1222 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1223 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001224 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1225 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001226 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001227 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001228 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001229 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001230 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001231 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001232 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001233
1234 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001235 final CharSequence title;
1236 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001237 switch (type) {
1238 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001239 title = res.getText(R.string.data_usage_warning_title);
1240 body = res.getString(R.string.data_usage_warning_body,
1241 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001242
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001243 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001244
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001245 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1246 builder.setDeleteIntent(PendingIntent.getBroadcast(
1247 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1248
Wei Liu546cb772016-07-21 16:19:01 -07001249 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001250 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001251 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1252
Jeff Sharkey497e4432011-06-14 17:27:29 -07001253 break;
1254 }
1255 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001256 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001257 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001258 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001259 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001260 case MATCH_WIFI:
1261 title = res.getText(R.string.data_usage_wifi_limit_title);
1262 break;
1263 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001264 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001265 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001266 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001267
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001268 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001269 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001270
Wei Liu546cb772016-07-21 16:19:01 -07001271 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001272 builder.setContentIntent(PendingIntent.getActivity(
1273 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1274 break;
1275 }
1276 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001277 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001278 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001279 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1280 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001281 case MATCH_WIFI:
1282 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1283 break;
1284 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001285 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001286 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001287 final long overBytes = totalBytes - policy.limitBytes;
1288 body = res.getString(R.string.data_usage_limit_snoozed_body,
1289 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001290
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001291 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001292 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001293 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001294
Wei Liu546cb772016-07-21 16:19:01 -07001295 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001296 builder.setContentIntent(PendingIntent.getActivity(
1297 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001298 break;
1299 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001300 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001301 title = res.getText(R.string.data_usage_rapid_title);
1302 if (rapidBlame != null) {
1303 body = res.getString(R.string.data_usage_rapid_app_body,
1304 rapidBlame.loadLabel(mContext.getPackageManager()));
1305 } else {
1306 body = res.getString(R.string.data_usage_rapid_body);
1307 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001308
Jeff Sharkey2e471452018-01-19 18:02:47 +09001309 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001310
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001311 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1312 builder.setDeleteIntent(PendingIntent.getBroadcast(
1313 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1314
1315 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001316 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001317 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001318 break;
1319 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001320 default: {
1321 return;
1322 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001323 }
1324
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001325 builder.setTicker(title);
1326 builder.setContentTitle(title);
1327 builder.setContentText(body);
1328 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001329
1330 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1331 notificationId.getId(), builder.build(), UserHandle.ALL);
1332 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001333 }
1334
Chris Wren193ae6b2017-03-31 15:17:11 -04001335 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001336 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1337 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001338 }
1339
1340 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001341 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001342 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001343 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001344 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 @Override
1346 public void onReceive(Context context, Intent intent) {
1347 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1348 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001349
Hugo Benichi446c9c92017-04-10 09:41:10 +09001350 synchronized (mUidRulesFirstLock) {
1351 synchronized (mNetworkPoliciesSecondLock) {
1352 ensureActiveMobilePolicyAL();
1353 normalizePoliciesNL();
1354 updateNetworkEnabledNL();
1355 updateNetworkRulesNL();
1356 updateNotificationsNL();
1357 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358 }
1359 }
1360 };
1361
Jeff Sharkey2e471452018-01-19 18:02:47 +09001362 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001363 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001364 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001365 final CountDownLatch latch = new CountDownLatch(1);
1366 mHandler.post(() -> {
1367 latch.countDown();
1368 });
1369 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001370 }
1371
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001372 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001373 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1374 * if necessary.
1375 *
1376 * @param subId that has its associated NetworkPolicy updated if necessary
1377 * @return if any policies were updated
1378 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001379 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1380 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001381
1382 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001383 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1384 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001385
1386 // find and update the mobile NetworkPolicy for this subscriber id
1387 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001388 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001389 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1390 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1391 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001392 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1393 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001394 }
1395 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001396 return policyUpdated;
1397 }
1398
1399 /**
1400 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1401 *
1402 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1403 * to do so, it returns the fallback value.
1404 *
1405 * @param config The CarrierConfig to read the value from.
1406 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1407 * @return cycleDay to use in the mobile NetworkPolicy.
1408 */
1409 @VisibleForTesting
1410 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1411 int fallbackCycleDay) {
1412 if (config == null) {
1413 return fallbackCycleDay;
1414 }
1415 int cycleDay =
1416 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1417 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1418 return fallbackCycleDay;
1419 }
1420 // validate cycleDay value
1421 final Calendar cal = Calendar.getInstance();
1422 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1423 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1424 Slog.e(TAG, "Invalid date in "
1425 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1426 return fallbackCycleDay;
1427 }
1428 return cycleDay;
1429 }
1430
1431 /**
1432 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1433 *
1434 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1435 * to do so, it returns the fallback value.
1436 *
1437 * @param config The CarrierConfig to read the value from.
1438 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1439 * @return warningBytes to use in the mobile NetworkPolicy.
1440 */
1441 @VisibleForTesting
1442 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1443 long fallbackWarningBytes) {
1444 if (config == null) {
1445 return fallbackWarningBytes;
1446 }
1447 long warningBytes =
1448 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1449
1450 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1451 return WARNING_DISABLED;
1452 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1453 return getPlatformDefaultWarningBytes();
1454 } else if (warningBytes < 0) {
1455 Slog.e(TAG, "Invalid value in "
1456 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1457 + "non-negative value but got: " + warningBytes);
1458 return fallbackWarningBytes;
1459 }
1460
1461 return warningBytes;
1462 }
1463
1464 /**
1465 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1466 *
1467 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1468 * to do so, it returns the fallback value.
1469 *
1470 * @param config The CarrierConfig to read the value from.
1471 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1472 * @return limitBytes to use in the mobile NetworkPolicy.
1473 */
1474 @VisibleForTesting
1475 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1476 long fallbackLimitBytes) {
1477 if (config == null) {
1478 return fallbackLimitBytes;
1479 }
1480 long limitBytes =
1481 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1482
1483 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1484 return LIMIT_DISABLED;
1485 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1486 return getPlatformDefaultLimitBytes();
1487 } else if (limitBytes < 0) {
1488 Slog.e(TAG, "Invalid value in "
1489 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1490 + "non-negative value but got: " + limitBytes);
1491 return fallbackLimitBytes;
1492 }
1493 return limitBytes;
1494 }
1495
1496 /**
1497 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1498 */
1499 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1500 @Override
1501 public void onReceive(Context context, Intent intent) {
1502 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1503 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1504
1505 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1506 return;
1507 }
1508 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001509 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001510 final String subscriberId = tele.getSubscriberId(subId);
1511
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001512 synchronized (mUidRulesFirstLock) {
1513 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001514 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001515 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001516 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001517 if (!updated) return;
1518 // update network and notification rules, as the data cycle changed and it's
1519 // possible that we should be triggering warnings/limits now
1520 handleNetworkPoliciesUpdateAL(true);
1521 }
1522 }
1523 }
1524 };
1525
1526 /**
1527 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1528 * one has been updated.
1529 *
1530 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1531 * update.
1532 */
1533 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1534 if (shouldNormalizePolicies) {
1535 normalizePoliciesNL();
1536 }
1537 updateNetworkEnabledNL();
1538 updateNetworkRulesNL();
1539 updateNotificationsNL();
1540 writePolicyAL();
1541 }
1542
1543 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001544 * Proactively control network data connections when they exceed
1545 * {@link NetworkPolicy#limitBytes}.
1546 */
Felipe Lemef0823852016-06-08 13:43:08 -07001547 void updateNetworkEnabledNL() {
1548 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001549
1550 // TODO: reset any policy-disabled networks when any policy is removed
1551 // completely, which is currently rare case.
1552
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001553 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1554 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001555 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001556 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001557 setNetworkTemplateEnabled(policy.template, true);
1558 continue;
1559 }
1560
Jeff Sharkey53313d72017-07-13 16:47:32 -06001561 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1562 .cycleIterator(policy).next();
1563 final long start = cycle.first.toInstant().toEpochMilli();
1564 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001565 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566
1567 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001568 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1569 && policy.lastLimitSnooze < start;
1570 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001571
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001572 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001573 }
1574 }
1575
1576 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001577 * Proactively disable networks that match the given
1578 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001579 */
1580 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001581 // TODO: reach into ConnectivityManager to proactively disable bringing
1582 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001583
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001584 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001585 // If mobile data usage hits the limit or if the user resumes the data, we need to
1586 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001587 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1588 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001589
Jeff Sharkey2e471452018-01-19 18:02:47 +09001590 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001591 for (int subId : subIds) {
1592 final String subscriberId = tm.getSubscriberId(subId);
1593 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001594 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1595 true);
Jack Yu8781b682016-07-08 14:28:51 -07001596 // Template is matched when subscriber id matches.
1597 if (template.matches(probeIdent)) {
1598 tm.setPolicyDataEnabled(enabled, subId);
1599 }
1600 }
1601 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001602 }
1603
1604 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001605 * Collect all ifaces from a {@link NetworkState} into the given set.
1606 */
1607 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1608 final String baseIface = state.linkProperties.getInterfaceName();
1609 if (baseIface != null) {
1610 ifaces.add(baseIface);
1611 }
1612 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1613 final String stackedIface = stackedLink.getInterfaceName();
1614 if (stackedIface != null) {
1615 ifaces.add(stackedIface);
1616 }
1617 }
1618 }
1619
1620 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621 * Examine all connected {@link NetworkState}, looking for
1622 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1623 * remaining quota based on usage cycle and historical stats.
1624 */
Felipe Lemef0823852016-06-08 13:43:08 -07001625 void updateNetworkRulesNL() {
1626 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001627
1628 final NetworkState[] states;
1629 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001630 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001631 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001632 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001633 return;
1634 }
1635
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001636 // First, generate identities of all connected networks so we can
1637 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001638 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001639 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001640 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001641 if (state.network != null) {
1642 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1643 }
Wei Liub8eaf452016-01-25 10:32:27 -08001644 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001645 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1646 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001647 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648 }
1649 }
1650
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001651 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001652 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001653
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001654 // For every well-defined policy, compute remaining data based on
1655 // current cycle and historical stats, and push to kernel.
1656 final ArraySet<String> matchingIfaces = new ArraySet<>();
1657 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1658 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1659
1660 // Collect all ifaces that match this policy
1661 matchingIfaces.clear();
1662 for (int j = identified.size() - 1; j >= 0; j--) {
1663 if (policy.template.matches(identified.valueAt(j))) {
1664 collectIfaces(matchingIfaces, identified.keyAt(j));
1665 }
1666 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001668 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001669 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001670 }
1671
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001672 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001673 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001674 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001675 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001676 if (hasLimit && policy.hasCycle()) {
1677 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1678 .cycleIterator(policy).next();
1679 final long start = cycle.first.toInstant().toEpochMilli();
1680 final long end = cycle.second.toInstant().toEpochMilli();
1681 final long totalBytes = getTotalBytes(policy.template, start, end);
1682
1683 if (policy.lastLimitSnooze >= start) {
1684 // snoozing past quota, but we still need to restrict apps,
1685 // so push really high quota.
1686 quotaBytes = Long.MAX_VALUE;
1687 } else {
1688 // remaining "quota" bytes are based on total usage in
1689 // current cycle. kernel doesn't like 0-byte rules, so we
1690 // set 1-byte quota and disable the radio later.
1691 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1692 }
1693 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001694 // metered network, but no policy limit; we still need to
1695 // restrict apps, so push really high quota.
1696 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001697 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001698
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001699 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001700 // TODO: switch to shared quota once NMS supports
1701 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001702 }
1703
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001704 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1705 final String iface = matchingIfaces.valueAt(j);
1706 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001707 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001708 }
1709 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001710
1711 // keep track of lowest warning or limit of active policies
1712 if (hasWarning && policy.warningBytes < lowestRule) {
1713 lowestRule = policy.warningBytes;
1714 }
1715 if (hasLimit && policy.limitBytes < lowestRule) {
1716 lowestRule = policy.limitBytes;
1717 }
1718 }
1719
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001720 // One final pass to catch any metered ifaces that don't have explicitly
1721 // defined policies; typically Wi-Fi networks.
1722 for (NetworkState state : states) {
1723 if (state.networkInfo != null && state.networkInfo.isConnected()
1724 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1725 matchingIfaces.clear();
1726 collectIfaces(matchingIfaces, state);
1727 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1728 final String iface = matchingIfaces.valueAt(j);
1729 if (!newMeteredIfaces.contains(iface)) {
1730 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1731 newMeteredIfaces.add(iface);
1732 }
1733 }
1734 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001735 }
1736
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001737 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001738 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1739 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001740 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001741 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001742 }
1743 }
1744 mMeteredIfaces = newMeteredIfaces;
1745
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001746 final ContentResolver cr = mContext.getContentResolver();
1747 final boolean quotaEnabled = Settings.Global.getInt(cr,
1748 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1749 final long quotaUnlimited = Settings.Global.getLong(cr,
1750 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1751 final float quotaLimited = Settings.Global.getFloat(cr,
1752 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1753
Jeff Sharkey9252b342018-01-19 07:58:35 +09001754 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001755 mSubscriptionOpportunisticQuota.clear();
1756 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001757 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001758 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001759 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001760 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001761 if (plan == null) continue;
1762
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001763 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001764 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001765 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001766 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001767 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001768 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001769 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001770 } else {
1771 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001772 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001773 final long start = cycle.first.toInstant().toEpochMilli();
1774 final long end = cycle.second.toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001775 final Instant now = mClock.instant();
1776 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.first.getZone())
1777 .truncatedTo(ChronoUnit.DAYS)
1778 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001779 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001780 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1781 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001782 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001783 // Number of remaining days including current day
1784 final long remainingDays =
1785 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001786
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001787 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001788 }
1789
1790 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1791 }
1792
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001793 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001794 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001795
1796 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001797 }
1798
1799 /**
1800 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1801 * have at least a default mobile policy defined.
1802 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001803 private void ensureActiveMobilePolicyAL() {
1804 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001805 if (mSuppressDefaultPolicy) return;
1806
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001807 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1808 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001809
Jeff Sharkey2e471452018-01-19 18:02:47 +09001810 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001811 for (int subId : subIds) {
1812 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001813 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001814 }
1815 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001816
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001817 /**
1818 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1819 * have at least a default mobile policy defined.
1820 *
1821 * @param subId to build a default policy for
1822 * @param subscriberId that we check for an existing policy
1823 * @return true if a mobile network policy was added, or false one already existed.
1824 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001825 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001826 // Poke around to see if we already have a policy
1827 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001828 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001829 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1830 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1831 if (template.matches(probeIdent)) {
1832 if (LOGD) {
1833 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1834 + NetworkIdentity.scrubSubscriberId(subscriberId));
1835 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001836 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001837 }
1838 }
1839
Jeff Sharkey32566012014-12-02 18:30:14 -08001840 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1841 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001842 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001843 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001844 return true;
1845 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001846
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001847 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001848 final int dataWarningConfig = mContext.getResources().getInteger(
1849 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001850 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001851 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001852 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001853 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001854 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001855 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001856
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001857 private long getPlatformDefaultLimitBytes() {
1858 return LIMIT_DISABLED;
1859 }
1860
1861 @VisibleForTesting
1862 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001863 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001864 final RecurrenceRule cycleRule = NetworkPolicy
1865 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001866 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001867 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1868 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1869 synchronized (mUidRulesFirstLock) {
1870 synchronized (mNetworkPoliciesSecondLock) {
1871 updateDefaultMobilePolicyAL(subId, policy);
1872 }
1873 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001874 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001875 }
1876
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001877 /**
1878 * Update the given {@link NetworkPolicy} based on any carrier-provided
1879 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1880 * Leaves policy untouched if the user has modified it.
1881 *
1882 * @return if the policy was modified
1883 */
1884 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1885 if (!policy.inferred) {
1886 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1887 return false;
1888 }
1889
1890 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1891 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1892 policy.lastLimitSnooze, policy.metered, policy.inferred);
1893
1894 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1895 if (!ArrayUtils.isEmpty(plans)) {
1896 final SubscriptionPlan plan = plans[0];
1897 policy.cycleRule = plan.getCycleRule();
1898 final long planLimitBytes = plan.getDataLimitBytes();
1899 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1900 policy.warningBytes = getPlatformDefaultWarningBytes();
1901 policy.limitBytes = getPlatformDefaultLimitBytes();
1902 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1903 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1904 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1905 } else {
1906 policy.warningBytes = (planLimitBytes * 9) / 10;
1907 switch (plan.getDataLimitBehavior()) {
1908 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1909 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1910 policy.limitBytes = planLimitBytes;
1911 break;
1912 default:
1913 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1914 break;
1915 }
1916 }
1917 } else {
1918 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1919 final int currentCycleDay;
1920 if (policy.cycleRule.isMonthly()) {
1921 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1922 } else {
1923 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1924 }
1925 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1926 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1927 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1928 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1929 }
1930
1931 if (policy.equals(original)) {
1932 return false;
1933 } else {
1934 Slog.d(TAG, "Updated " + original + " to " + policy);
1935 return true;
1936 }
1937 }
1938
Felipe Lemef0823852016-06-08 13:43:08 -07001939 private void readPolicyAL() {
1940 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001941
1942 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001943 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001944 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001945 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001946 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001947
1948 FileInputStream fis = null;
1949 try {
1950 fis = mPolicyFile.openRead();
1951 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001952 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001953
Felipe Leme46b451f2016-08-19 08:46:17 -07001954 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1955 // to skip UIDs that were explicitly blacklisted.
1956 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1957
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001958 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001959 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001960 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 while ((type = in.next()) != END_DOCUMENT) {
1962 final String tag = in.getName();
1963 if (type == START_TAG) {
1964 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001965 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001966 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001967 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1968 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001969 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1970 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1971 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001972 final String networkId;
1973 if (version >= VERSION_ADDED_NETWORK_ID) {
1974 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1975 } else {
1976 networkId = null;
1977 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001978 final RecurrenceRule cycleRule;
1979 if (version >= VERSION_ADDED_CYCLE) {
1980 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1981 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1982 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1983 cycleRule = new RecurrenceRule(
1984 RecurrenceRule.convertZonedDateTime(start),
1985 RecurrenceRule.convertZonedDateTime(end),
1986 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001987 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001988 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1989 final String cycleTimezone;
1990 if (version >= VERSION_ADDED_TIMEZONE) {
1991 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1992 } else {
1993 cycleTimezone = "UTC";
1994 }
1995 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001996 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001997 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1998 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001999 final long lastLimitSnooze;
2000 if (version >= VERSION_SPLIT_SNOOZE) {
2001 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2002 } else if (version >= VERSION_ADDED_SNOOZE) {
2003 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002004 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002005 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002006 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002007 final boolean metered;
2008 if (version >= VERSION_ADDED_METERED) {
2009 metered = readBooleanAttribute(in, ATTR_METERED);
2010 } else {
2011 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002012 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002013 metered = true;
2014 break;
2015 default:
2016 metered = false;
2017 }
2018 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002019 final long lastWarningSnooze;
2020 if (version >= VERSION_SPLIT_SNOOZE) {
2021 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2022 } else {
2023 lastWarningSnooze = SNOOZE_NEVER;
2024 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002025 final boolean inferred;
2026 if (version >= VERSION_ADDED_INFERRED) {
2027 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2028 } else {
2029 inferred = false;
2030 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002031
Jeff Sharkey32566012014-12-02 18:30:14 -08002032 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2033 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002034 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002035 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2036 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002037 lastLimitSnooze, metered, inferred));
2038 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002039
2040 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2041 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2042 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2043 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2044 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2045 RecurrenceRule.convertZonedDateTime(start),
2046 RecurrenceRule.convertZonedDateTime(end),
2047 RecurrenceRule.convertPeriod(period));
2048 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2049 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2050
2051 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2052 SubscriptionPlan.BYTES_UNKNOWN);
2053 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2054 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2055 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2056 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2057 builder.setDataLimit(limitBytes, limitBehavior);
2058 }
2059
2060 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2061 SubscriptionPlan.BYTES_UNKNOWN);
2062 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2063 SubscriptionPlan.TIME_UNKNOWN);
2064 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2065 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2066 builder.setDataUsage(usageBytes, usageTime);
2067 }
2068
2069 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2070 final SubscriptionPlan plan = builder.build();
2071 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2072 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2073
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002074 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2075 mSubscriptionPlansOwner.put(subId, ownerPackage);
2076
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002077 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002078 final int uid = readIntAttribute(in, ATTR_UID);
2079 final int policy = readIntAttribute(in, ATTR_POLICY);
2080
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002081 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002082 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002083 } else {
2084 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2085 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002086 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002087 final int appId = readIntAttribute(in, ATTR_APP_ID);
2088 final int policy = readIntAttribute(in, ATTR_POLICY);
2089
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002090 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002091 // app policy is deprecated so this is only used in pre system user split.
2092 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002093 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002094 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002095 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002096 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002097 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002098 } else if (TAG_WHITELIST.equals(tag)) {
2099 insideWhitelist = true;
2100 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2101 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002102 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002103 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2104 final int uid = readIntAttribute(in, ATTR_UID);
2105 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002106 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002107 } else if (type == END_TAG) {
2108 if (TAG_WHITELIST.equals(tag)) {
2109 insideWhitelist = false;
2110 }
2111
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002112 }
2113 }
2114
Felipe Leme46b451f2016-08-19 08:46:17 -07002115 final int size = whitelistedRestrictBackground.size();
2116 for (int i = 0; i < size; i++) {
2117 final int uid = whitelistedRestrictBackground.keyAt(i);
2118 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2119 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2120 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2121 + " because its policy is " + uidPoliciesToString(policy));
2122 continue;
2123 }
2124 if (UserHandle.isApp(uid)) {
2125 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2126 if (LOGV)
2127 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2128 setUidPolicyUncheckedUL(uid, newPolicy, false);
2129 } else {
2130 Slog.w(TAG, "unable to update policy on UID " + uid);
2131 }
2132 }
2133
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002134 } catch (FileNotFoundException e) {
2135 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002136 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002137 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002138 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002139 } finally {
2140 IoUtils.closeQuietly(fis);
2141 }
2142 }
2143
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002144 /**
2145 * Upgrade legacy background data flags, notifying listeners of one last
2146 * change to always-true.
2147 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002148 private void upgradeDefaultBackgroundDataUL() {
2149 // This method is only called when we're unable to find the network policy flag, which
2150 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002151
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002152 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002153 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002154 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2155
2156 // NOTE: We used to read the legacy setting here :
2157 //
2158 // final int legacyFlagValue = Settings.Secure.getInt(
2159 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2160 //
2161 // This is no longer necessary because we will never upgrade directly from Gingerbread
2162 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2163 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002164 }
2165
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002166 /**
2167 * Perform upgrade step of moving any user-defined meterness overrides over
2168 * into {@link WifiConfiguration}.
2169 */
2170 private void upgradeWifiMeteredOverrideAL() {
2171 boolean modified = false;
2172 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2173 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2174 for (int i = 0; i < mNetworkPolicy.size(); ) {
2175 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2176 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2177 && !policy.inferred) {
2178 mNetworkPolicy.removeAt(i);
2179 modified = true;
2180
2181 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2182 for (WifiConfiguration config : configs) {
2183 if (Objects.equals(resolveNetworkId(config), networkId)) {
2184 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2185 config.meteredOverride = policy.metered
2186 ? WifiConfiguration.METERED_OVERRIDE_METERED
2187 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2188 wm.updateNetwork(config);
2189 }
2190 }
2191 } else {
2192 i++;
2193 }
2194 }
2195 if (modified) {
2196 writePolicyAL();
2197 }
2198 }
2199
Felipe Lemef0823852016-06-08 13:43:08 -07002200 void writePolicyAL() {
2201 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002202
2203 FileOutputStream fos = null;
2204 try {
2205 fos = mPolicyFile.startWrite();
2206
2207 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002208 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002209 out.startDocument(null, true);
2210
2211 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002212 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002213 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002214
2215 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002216 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2217 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002218 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002219 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002220
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002221 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002222 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2223 final String subscriberId = template.getSubscriberId();
2224 if (subscriberId != null) {
2225 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002226 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002227 final String networkId = template.getNetworkId();
2228 if (networkId != null) {
2229 out.attribute(null, ATTR_NETWORK_ID, networkId);
2230 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002231 writeStringAttribute(out, ATTR_CYCLE_START,
2232 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2233 writeStringAttribute(out, ATTR_CYCLE_END,
2234 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2235 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2236 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002237 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2238 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002239 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2240 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002241 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002242 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002243 out.endTag(null, TAG_NETWORK_POLICY);
2244 }
2245
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002246 // write all known subscription plans
2247 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2248 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002249 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002250 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2251 if (ArrayUtils.isEmpty(plans)) continue;
2252
2253 for (SubscriptionPlan plan : plans) {
2254 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2255 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002256 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002257 final RecurrenceRule cycleRule = plan.getCycleRule();
2258 writeStringAttribute(out, ATTR_CYCLE_START,
2259 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2260 writeStringAttribute(out, ATTR_CYCLE_END,
2261 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2262 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2263 RecurrenceRule.convertPeriod(cycleRule.period));
2264 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2265 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2266 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2267 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2268 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2269 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2270 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2271 }
2272 }
2273
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002274 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002275 for (int i = 0; i < mUidPolicy.size(); i++) {
2276 final int uid = mUidPolicy.keyAt(i);
2277 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002278
Jeff Sharkey497e4432011-06-14 17:27:29 -07002279 // skip writing empty policies
2280 if (policy == POLICY_NONE) continue;
2281
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002282 out.startTag(null, TAG_UID_POLICY);
2283 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002284 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002285 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002286 }
2287
2288 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002289
2290 // write all whitelists
2291 out.startTag(null, TAG_WHITELIST);
2292
Felipe Lemea9505cc2016-02-26 10:28:41 -08002293 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002294 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002295 for (int i = 0; i < size; i++) {
2296 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2297 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2298 writeIntAttribute(out, ATTR_UID, uid);
2299 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2300 }
2301
Felipe Lemeb85a6372016-01-14 16:16:16 -08002302 out.endTag(null, TAG_WHITELIST);
2303
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002304 out.endDocument();
2305
2306 mPolicyFile.finishWrite(fos);
2307 } catch (IOException e) {
2308 if (fos != null) {
2309 mPolicyFile.failWrite(fos);
2310 }
2311 }
2312 }
2313
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002314 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002315 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002316 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002317
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002318 if (!UserHandle.isApp(uid)) {
2319 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002320 }
Felipe Lemef0823852016-06-08 13:43:08 -07002321 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002322 final long token = Binder.clearCallingIdentity();
2323 try {
2324 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2325 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002326 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002327 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002328 }
2329 } finally {
2330 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002331 }
2332 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002333 }
2334
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002335 @Override
2336 public void addUidPolicy(int uid, int policy) {
2337 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002338
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002339 if (!UserHandle.isApp(uid)) {
2340 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2341 }
2342
Felipe Lemef0823852016-06-08 13:43:08 -07002343 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002344 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2345 policy |= oldPolicy;
2346 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002347 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002348 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002349 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002350 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002351 }
2352
2353 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002354 public void removeUidPolicy(int uid, int policy) {
2355 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2356
2357 if (!UserHandle.isApp(uid)) {
2358 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2359 }
2360
Felipe Lemef0823852016-06-08 13:43:08 -07002361 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002362 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2363 policy = oldPolicy & ~policy;
2364 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002365 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002366 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002367 }
2368 }
2369 }
2370
Felipe Lemef0823852016-06-08 13:43:08 -07002371 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002372 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002373
Felipe Leme57e3d312016-08-23 14:42:52 -07002374 final boolean notifyApp;
2375 if (!isUidValidForWhitelistRules(uid)) {
2376 notifyApp = false;
2377 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002378 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2379 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2380 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2381 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002382 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2383 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002384 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2385 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2386 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2387 if (LOGD)
2388 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2389 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2390 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002391 notifyApp = wasBlocked != isBlocked;
2392 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002393 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2394 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002395 if (persist) {
2396 synchronized (mNetworkPoliciesSecondLock) {
2397 writePolicyAL();
2398 }
2399 }
Felipe Leme923845f2016-03-02 13:42:48 -08002400 }
2401
Felipe Lemef0823852016-06-08 13:43:08 -07002402 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002403 if (policy == POLICY_NONE) {
2404 mUidPolicy.delete(uid);
2405 } else {
2406 mUidPolicy.put(uid, policy);
2407 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002408
2409 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002410 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002411 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002412 synchronized (mNetworkPoliciesSecondLock) {
2413 writePolicyAL();
2414 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002415 }
2416 }
2417
2418 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002419 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002420 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2421
Felipe Lemef0823852016-06-08 13:43:08 -07002422 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002423 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002424 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002425 }
2426
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002427 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002428 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002429 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2430
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002431 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002432 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002433 for (int i = 0; i < mUidPolicy.size(); i++) {
2434 final int uid = mUidPolicy.keyAt(i);
2435 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002436 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2437 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002438 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002439 }
2440 }
2441 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002442 return uids;
2443 }
2444
2445 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002446 * Removes any persistable state associated with given {@link UserHandle}, persisting
2447 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002448 */
Felipe Lemef0823852016-06-08 13:43:08 -07002449 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002450
Sudheer Shanka352dc572017-09-22 17:09:38 -07002451 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002452 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002453
Felipe Lemea110eec2016-04-29 09:58:06 -07002454 // Remove entries from revoked default restricted background UID whitelist
2455 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2456 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2457 if (UserHandle.getUserId(uid) == userId) {
2458 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002459 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002460 }
2461 }
2462
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002463 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002464 int[] uids = new int[0];
2465 for (int i = 0; i < mUidPolicy.size(); i++) {
2466 final int uid = mUidPolicy.keyAt(i);
2467 if (UserHandle.getUserId(uid) == userId) {
2468 uids = appendInt(uids, uid);
2469 }
2470 }
2471
2472 if (uids.length > 0) {
2473 for (int uid : uids) {
2474 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002475 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002476 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002477 }
Felipe Lemef0823852016-06-08 13:43:08 -07002478 synchronized (mNetworkPoliciesSecondLock) {
2479 updateRulesForGlobalChangeAL(true);
2480 if (writePolicy && changed) {
2481 writePolicyAL();
2482 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002483 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002484 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002485 }
2486
2487 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002488 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002489 // TODO: create permission for observing network policy
2490 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002491 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002492 }
2493
2494 @Override
2495 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002496 // TODO: create permission for observing network policy
2497 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002498 mListeners.unregister(listener);
2499 }
2500
Jeff Sharkey1b861272011-05-22 00:34:52 -07002501 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002502 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002503 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2504
Felipe Leme6a05eee2016-02-19 14:43:51 -08002505 final long token = Binder.clearCallingIdentity();
2506 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002507 synchronized (mUidRulesFirstLock) {
2508 synchronized (mNetworkPoliciesSecondLock) {
2509 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002510 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002511 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002512 }
2513 } finally {
2514 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002515 }
2516 }
2517
Hugo Benichi446c9c92017-04-10 09:41:10 +09002518 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002519 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002520 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2521 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002522 }
2523
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002524 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002525 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002526 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002527 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002528 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2529 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2530 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002531 } catch (SecurityException e) {
2532 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002533
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002534 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2535 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2536 return new NetworkPolicy[0];
2537 }
Svet Ganov16a16892015-04-16 10:32:04 -07002538 }
2539
Felipe Lemef0823852016-06-08 13:43:08 -07002540 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002541 final int size = mNetworkPolicy.size();
2542 final NetworkPolicy[] policies = new NetworkPolicy[size];
2543 for (int i = 0; i < size; i++) {
2544 policies[i] = mNetworkPolicy.valueAt(i);
2545 }
2546 return policies;
2547 }
2548 }
2549
Felipe Lemef0823852016-06-08 13:43:08 -07002550 private void normalizePoliciesNL() {
2551 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002552 }
2553
Felipe Lemef0823852016-06-08 13:43:08 -07002554 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002555 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002556 final String[] merged = tele.getMergedSubscriberIds();
2557
2558 mNetworkPolicy.clear();
2559 for (NetworkPolicy policy : policies) {
2560 // When two normalized templates conflict, prefer the most
2561 // restrictive policy
2562 policy.template = NetworkTemplate.normalize(policy.template, merged);
2563 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2564 if (existing == null || existing.compareTo(policy) > 0) {
2565 if (existing != null) {
2566 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2567 }
2568 mNetworkPolicy.put(policy.template, policy);
2569 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002570 }
2571 }
2572
2573 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002574 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002575 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002576
2577 final long token = Binder.clearCallingIdentity();
2578 try {
2579 performSnooze(template, TYPE_LIMIT);
2580 } finally {
2581 Binder.restoreCallingIdentity(token);
2582 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002583 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002584
Dianne Hackborn497175b2014-07-01 12:56:08 -07002585 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002586 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002587 synchronized (mUidRulesFirstLock) {
2588 synchronized (mNetworkPoliciesSecondLock) {
2589 // find and snooze local policy that matches
2590 final NetworkPolicy policy = mNetworkPolicy.get(template);
2591 if (policy == null) {
2592 throw new IllegalArgumentException("unable to find policy for " + template);
2593 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002594
Felipe Lemef0823852016-06-08 13:43:08 -07002595 switch (type) {
2596 case TYPE_WARNING:
2597 policy.lastWarningSnooze = currentTime;
2598 break;
2599 case TYPE_LIMIT:
2600 policy.lastLimitSnooze = currentTime;
2601 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002602 case TYPE_RAPID:
2603 policy.lastRapidSnooze = currentTime;
2604 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002605 default:
2606 throw new IllegalArgumentException("unexpected type");
2607 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002608
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002609 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002610 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002611 }
2612 }
2613
2614 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002615 public void onTetheringChanged(String iface, boolean tethering) {
2616 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002617 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002618 if (mRestrictBackground && tethering) {
2619 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2620 setRestrictBackground(false);
2621 }
2622 }
2623 }
2624
2625 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002626 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002627 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002628 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002629 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2630 final long token = Binder.clearCallingIdentity();
2631 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002632 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002633 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002634 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002635 } finally {
2636 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002637 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002638 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002639 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002640 }
2641 }
2642
Felipe Lemef0823852016-06-08 13:43:08 -07002643 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002644 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002645 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002646 if (restrictBackground == mRestrictBackground) {
2647 // Ideally, UI should never allow this scenario...
2648 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002649 return;
2650 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002651 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2652 final boolean oldRestrictBackground = mRestrictBackground;
2653 mRestrictBackground = restrictBackground;
2654 // Must whitelist foreground apps before turning data saver mode on.
2655 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2656 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2657 updateRulesForRestrictBackgroundUL();
2658 try {
2659 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2660 Slog.e(TAG,
2661 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2662 mRestrictBackground = oldRestrictBackground;
2663 // TODO: if it knew the foreground apps (see TODO above), it could call
2664 // updateRulesForRestrictBackgroundUL() again to restore state.
2665 return;
2666 }
2667 } catch (RemoteException e) {
2668 // ignored; service lives in system_server
2669 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002670
Sudheer Shanka543339f2017-07-28 15:18:07 -07002671 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002672 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002673
2674 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2675 mRestrictBackgroundChangedInBsm = true;
2676 }
2677 synchronized (mNetworkPoliciesSecondLock) {
2678 updateNotificationsNL();
2679 writePolicyAL();
2680 }
2681 } finally {
2682 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002683 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002684 }
2685
2686 private void sendRestrictBackgroundChangedMsg() {
2687 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2688 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2689 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002690 }
2691
Felipe Lemeb85a6372016-01-14 16:16:16 -08002692 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002693 public int getRestrictBackgroundByCaller() {
2694 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2695 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002696
Felipe Lemef0823852016-06-08 13:43:08 -07002697 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002698 // Must clear identity because getUidPolicy() is restricted to system.
2699 final long token = Binder.clearCallingIdentity();
2700 final int policy;
2701 try {
2702 policy = getUidPolicy(uid);
2703 } finally {
2704 Binder.restoreCallingIdentity(token);
2705 }
2706 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2707 // App is blacklisted.
2708 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2709 }
Felipe Leme1b103232016-01-22 09:44:57 -08002710 if (!mRestrictBackground) {
2711 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2712 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002713 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002714 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2715 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2716 }
2717 }
2718
2719 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002720 public boolean getRestrictBackground() {
2721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2722
Felipe Lemef0823852016-06-08 13:43:08 -07002723 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002724 return mRestrictBackground;
2725 }
2726 }
2727
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002728 @Override
2729 public void setDeviceIdleMode(boolean enabled) {
2730 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002731 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2732 try {
2733 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002734 if (mDeviceIdleMode == enabled) {
2735 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002736 }
Felipe Lemeea014392016-09-06 13:59:54 -07002737 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002738 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002739 if (mSystemReady) {
2740 // Device idle change means we need to rebuild rules for all
2741 // known apps, so do a global refresh.
2742 updateRulesForRestrictPowerUL();
2743 }
2744 }
2745 if (enabled) {
2746 EventLogTags.writeDeviceIdleOnPhase("net");
2747 } else {
2748 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002749 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002750 } finally {
2751 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002752 }
2753 }
2754
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002755 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002756 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2757 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002758 final long token = Binder.clearCallingIdentity();
2759 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002760 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2761 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2762 for (WifiConfiguration config : configs) {
2763 if (Objects.equals(resolveNetworkId(config), networkId)) {
2764 config.meteredOverride = meteredOverride;
2765 wm.updateNetwork(config);
2766 }
2767 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002768 } finally {
2769 Binder.restoreCallingIdentity(token);
2770 }
2771 }
2772
Jeff Sharkey46645002011-07-27 21:11:21 -07002773 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002774 @Deprecated
2775 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2776 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2777 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2778 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002779 }
2780
Jeff Sharkey53313d72017-07-13 16:47:32 -06002781 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2782 // Verify they're not lying about package name
2783 mAppOps.checkPackage(callingUid, callingPackage);
2784
Jeff Sharkey53313d72017-07-13 16:47:32 -06002785 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002786 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002787 final long token = Binder.clearCallingIdentity();
2788 try {
2789 si = mContext.getSystemService(SubscriptionManager.class)
2790 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002791 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002792 } finally {
2793 Binder.restoreCallingIdentity(token);
2794 }
2795
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002796 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002797 if (si != null) {
2798 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2799 return;
2800 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002801 }
2802
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002803 // Second check: has the CarrierService delegated access?
2804 if (config != null) {
2805 final String overridePackage = config
2806 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2807 if (!TextUtils.isEmpty(overridePackage)
2808 && Objects.equals(overridePackage, callingPackage)) {
2809 return;
2810 }
2811 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002812
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002813 // Third check: is caller the fallback/default CarrierService?
2814 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2815 if (!TextUtils.isEmpty(defaultPackage)
2816 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002817 return;
2818 }
2819
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002820 // Fourth check: is caller a testing app?
2821 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2822 if (!TextUtils.isEmpty(testPackage)
2823 && Objects.equals(testPackage, callingPackage)) {
2824 return;
2825 }
2826
2827 // Fifth check: is caller a legacy testing app?
2828 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2829 if (!TextUtils.isEmpty(legacyTestPackage)
2830 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002831 return;
2832 }
2833
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002834 // Final check: does the caller hold a permission?
2835 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002836 }
2837
2838 @Override
2839 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2840 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2841
Jeff Sharkey53313d72017-07-13 16:47:32 -06002842 final String fake = SystemProperties.get("fw.fake_plan");
2843 if (!TextUtils.isEmpty(fake)) {
2844 final List<SubscriptionPlan> plans = new ArrayList<>();
2845 if ("month_hard".equals(fake)) {
2846 plans.add(SubscriptionPlan.Builder
2847 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2848 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002849 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2850 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2851 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2852 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2853 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002854 plans.add(SubscriptionPlan.Builder
2855 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2856 .setTitle("G-Mobile Happy")
2857 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2858 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2859 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2860 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2861 .build());
2862 plans.add(SubscriptionPlan.Builder
2863 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2864 .setTitle("G-Mobile, Charged after limit")
2865 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2866 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2867 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2868 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2869 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002870 } else if ("month_soft".equals(fake)) {
2871 plans.add(SubscriptionPlan.Builder
2872 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2873 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2874 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2875 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002876 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2877 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2878 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2879 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2880 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002881 plans.add(SubscriptionPlan.Builder
2882 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2883 .setTitle("G-Mobile, Throttled after limit")
2884 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2885 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2886 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2887 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2888 .build());
2889 plans.add(SubscriptionPlan.Builder
2890 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2891 .setTitle("G-Mobile, No data connection after limit")
2892 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2893 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2894 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2895 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2896 .build());
2897
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002898 } else if ("month_over".equals(fake)) {
2899 plans.add(SubscriptionPlan.Builder
2900 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2901 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2902 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2903 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2904 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2905 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2906 .build());
2907 plans.add(SubscriptionPlan.Builder
2908 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2909 .setTitle("G-Mobile, Throttled after limit")
2910 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2911 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2912 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2913 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2914 .build());
2915 plans.add(SubscriptionPlan.Builder
2916 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2917 .setTitle("G-Mobile, No data connection after limit")
2918 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2919 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2920 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2921 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2922 .build());
2923
Jeff Sharkey53313d72017-07-13 16:47:32 -06002924 } else if ("month_none".equals(fake)) {
2925 plans.add(SubscriptionPlan.Builder
2926 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2927 .setTitle("G-Mobile")
2928 .build());
2929 } else if ("prepaid".equals(fake)) {
2930 plans.add(SubscriptionPlan.Builder
2931 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2932 ZonedDateTime.now().plusDays(10))
2933 .setTitle("G-Mobile")
2934 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2935 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2936 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2937 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2938 .build());
2939 } else if ("prepaid_crazy".equals(fake)) {
2940 plans.add(SubscriptionPlan.Builder
2941 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2942 ZonedDateTime.now().plusDays(10))
2943 .setTitle("G-Mobile Anytime")
2944 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2945 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2946 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2947 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2948 .build());
2949 plans.add(SubscriptionPlan.Builder
2950 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2951 ZonedDateTime.now().plusDays(20))
2952 .setTitle("G-Mobile Nickel Nights")
2953 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002954 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2955 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002956 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2957 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2958 .build());
2959 plans.add(SubscriptionPlan.Builder
2960 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2961 ZonedDateTime.now().plusDays(20))
2962 .setTitle("G-Mobile Bonus 3G")
2963 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002964 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002965 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2966 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2967 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2968 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002969 } else if ("unlimited".equals(fake)) {
2970 plans.add(SubscriptionPlan.Builder
2971 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2972 ZonedDateTime.now().plusDays(10))
2973 .setTitle("G-Mobile Awesome")
2974 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2975 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2976 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2977 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2978 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002979 }
2980 return plans.toArray(new SubscriptionPlan[plans.size()]);
2981 }
2982
Jeff Sharkey4635f102017-09-01 11:27:13 -06002983 synchronized (mNetworkPoliciesSecondLock) {
2984 // Only give out plan details to the package that defined them,
2985 // so that we don't risk leaking plans between apps. We always
2986 // let in core system components (like the Settings app).
2987 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2988 if (Objects.equals(ownerPackage, callingPackage)
2989 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2990 return mSubscriptionPlans.get(subId);
2991 } else {
2992 Log.w(TAG, "Not returning plans because caller " + callingPackage
2993 + " doesn't match owner " + ownerPackage);
2994 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002995 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002996 }
2997 }
2998
2999 @Override
3000 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3001 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3002
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003003 for (SubscriptionPlan plan : plans) {
3004 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003005 }
3006
3007 final long token = Binder.clearCallingIdentity();
3008 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003009 synchronized (mUidRulesFirstLock) {
3010 synchronized (mNetworkPoliciesSecondLock) {
3011 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003012 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003013
3014 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
3015 .getSubscriberId(subId);
3016 ensureActiveMobilePolicyAL(subId, subscriberId);
3017 maybeUpdateMobilePolicyCycleAL(subId);
3018 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003019 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003020 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003021
3022 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3023 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3024 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3025 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003026 } finally {
3027 Binder.restoreCallingIdentity(token);
3028 }
3029 }
3030
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003031 /**
3032 * Only visible for testing purposes. This doesn't give any access to
3033 * existing plans; it simply lets the debug package define new plans.
3034 */
3035 void setSubscriptionPlansOwner(int subId, String packageName) {
3036 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3037 }
3038
Jeff Sharkey53313d72017-07-13 16:47:32 -06003039 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003040 public String getSubscriptionPlansOwner(int subId) {
3041 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3042 throw new SecurityException();
3043 }
3044
3045 synchronized (mNetworkPoliciesSecondLock) {
3046 return mSubscriptionPlansOwner.get(subId);
3047 }
3048 }
3049
3050 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003051 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3052 long timeoutMillis, String callingPackage) {
3053 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3054
3055 // We can only override when carrier told us about plans
3056 synchronized (mNetworkPoliciesSecondLock) {
3057 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3058 throw new IllegalStateException(
3059 "Must provide SubscriptionPlan information before overriding");
3060 }
3061 }
3062
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003063 // Only allow overrides when feature is enabled. However, we always
3064 // allow disabling of overrides for safety reasons.
3065 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3066 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3067 if (overrideEnabled || overrideValue == 0) {
3068 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3069 overrideMask, overrideValue, subId));
3070 if (timeoutMillis > 0) {
3071 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3072 overrideMask, 0, subId), timeoutMillis);
3073 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003074 }
3075 }
3076
3077 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003078 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003079 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003080
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003081 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3082
Dianne Hackborn497175b2014-07-01 12:56:08 -07003083 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003084 for (String arg : args) {
3085 argSet.add(arg);
3086 }
3087
Felipe Lemef0823852016-06-08 13:43:08 -07003088 synchronized (mUidRulesFirstLock) {
3089 synchronized (mNetworkPoliciesSecondLock) {
3090 if (argSet.contains("--unsnooze")) {
3091 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3092 mNetworkPolicy.valueAt(i).clearSnooze();
3093 }
3094
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003095 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003096
3097 fout.println("Cleared snooze timestamps");
3098 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003099 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003100
Felipe Lemef0823852016-06-08 13:43:08 -07003101 fout.print("System ready: "); fout.println(mSystemReady);
3102 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3103 fout.print("Restrict power: "); fout.println(mRestrictPower);
3104 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003105 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3106
3107 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003108 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003109 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003110 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3111 fout.println(mNetworkPolicy.valueAt(i).toString());
3112 }
3113 fout.decreaseIndent();
3114
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003115 fout.println();
3116 fout.println("Subscription plans:");
3117 fout.increaseIndent();
3118 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3119 final int subId = mSubscriptionPlans.keyAt(i);
3120 fout.println("Subscriber ID " + subId + ":");
3121 fout.increaseIndent();
3122 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3123 if (!ArrayUtils.isEmpty(plans)) {
3124 for (SubscriptionPlan plan : plans) {
3125 fout.println(plan);
3126 }
3127 }
3128 fout.decreaseIndent();
3129 }
3130 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003131
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003132 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003133 fout.println("Policy for UIDs:");
3134 fout.increaseIndent();
3135 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003136 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003137 final int uid = mUidPolicy.keyAt(i);
3138 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003139 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003140 fout.print(uid);
3141 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003142 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003143 fout.println();
3144 }
3145 fout.decreaseIndent();
3146
3147 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3148 if (size > 0) {
3149 fout.println("Power save whitelist (except idle) app ids:");
3150 fout.increaseIndent();
3151 for (int i = 0; i < size; i++) {
3152 fout.print("UID=");
3153 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3154 fout.print(": ");
3155 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3156 fout.println();
3157 }
3158 fout.decreaseIndent();
3159 }
3160
3161 size = mPowerSaveWhitelistAppIds.size();
3162 if (size > 0) {
3163 fout.println("Power save whitelist app ids:");
3164 fout.increaseIndent();
3165 for (int i = 0; i < size; i++) {
3166 fout.print("UID=");
3167 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3168 fout.print(": ");
3169 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3170 fout.println();
3171 }
3172 fout.decreaseIndent();
3173 }
3174
Felipe Lemef0823852016-06-08 13:43:08 -07003175 size = mDefaultRestrictBackgroundWhitelistUids.size();
3176 if (size > 0) {
3177 fout.println("Default restrict background whitelist uids:");
3178 fout.increaseIndent();
3179 for (int i = 0; i < size; i++) {
3180 fout.print("UID=");
3181 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3182 fout.println();
3183 }
3184 fout.decreaseIndent();
3185 }
3186
3187 size = mRestrictBackgroundWhitelistRevokedUids.size();
3188 if (size > 0) {
3189 fout.println("Default restrict background whitelist uids revoked by users:");
3190 fout.increaseIndent();
3191 for (int i = 0; i < size; i++) {
3192 fout.print("UID=");
3193 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3194 fout.println();
3195 }
3196 fout.decreaseIndent();
3197 }
3198
3199 final SparseBooleanArray knownUids = new SparseBooleanArray();
3200 collectKeys(mUidState, knownUids);
3201 collectKeys(mUidRules, knownUids);
3202
3203 fout.println("Status for all known UIDs:");
3204 fout.increaseIndent();
3205 size = knownUids.size();
3206 for (int i = 0; i < size; i++) {
3207 final int uid = knownUids.keyAt(i);
3208 fout.print("UID=");
3209 fout.print(uid);
3210
3211 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3212 fout.print(" state=");
3213 fout.print(state);
3214 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3215 fout.print(" (fg)");
3216 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003217 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003218 ? " (fg svc)" : " (bg)");
3219 }
3220
3221 final int uidRules = mUidRules.get(uid, RULE_NONE);
3222 fout.print(" rules=");
3223 fout.print(uidRulesToString(uidRules));
3224 fout.println();
3225 }
3226 fout.decreaseIndent();
3227
3228 fout.println("Status for just UIDs with rules:");
3229 fout.increaseIndent();
3230 size = mUidRules.size();
3231 for (int i = 0; i < size; i++) {
3232 final int uid = mUidRules.keyAt(i);
3233 fout.print("UID=");
3234 fout.print(uid);
3235 final int uidRules = mUidRules.get(uid, RULE_NONE);
3236 fout.print(" rules=");
3237 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003238 fout.println();
3239 }
3240 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003241
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003242 fout.println("Admin restricted uids for metered data:");
3243 fout.increaseIndent();
3244 size = mMeteredRestrictedUids.size();
3245 for (int i = 0; i < size; ++i) {
3246 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3247 fout.println(mMeteredRestrictedUids.valueAt(i));
3248 }
3249 fout.decreaseIndent();
3250
Sudheer Shanka352dc572017-09-22 17:09:38 -07003251 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003252 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003253 }
3254 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003255
3256 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003257 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003258 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003259 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003260 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003261 }
3262
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003263 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003264 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003265 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003266 return isUidStateForeground(
3267 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003268 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003269 }
3270
Felipe Lemef0823852016-06-08 13:43:08 -07003271 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003272 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003273 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003274 }
3275
Felipe Lemef0823852016-06-08 13:43:08 -07003276 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003277 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3278 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3279 }
3280
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003281 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003282 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003283 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003284 }
3285
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003286 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003287 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003288 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3289 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003290 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003291 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003292 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3293 try {
3294 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3295 if (oldUidState != uidState) {
3296 // state changed, push updated rules
3297 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003298 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3299 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3300 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003301 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003302 if (mDeviceIdleMode) {
3303 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003304 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003305 if (mRestrictPower) {
3306 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003307 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003308 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003309 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003310 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003311 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003312 } finally {
3313 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003314 }
3315 }
3316
Felipe Lemef0823852016-06-08 13:43:08 -07003317 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003318 final int index = mUidState.indexOfKey(uid);
3319 if (index >= 0) {
3320 final int oldUidState = mUidState.valueAt(index);
3321 mUidState.removeAt(index);
3322 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003323 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003324 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003325 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003326 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003327 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003328 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003329 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003330 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003331 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003332 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003333 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003334 }
3335 }
3336
Felipe Lemef28983d2016-03-25 12:18:23 -07003337 // adjust stats accounting based on foreground status
3338 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003339 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3340 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3341 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3342 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003343 try {
3344 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003345 } finally {
3346 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003347 }
3348 }
3349
Sudheer Shankac9d94072017-02-22 22:13:55 +00003350 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3351 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003352 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003353 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003354 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003355 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003356 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003357 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003358 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003359 }
3360
Felipe Lemef0823852016-06-08 13:43:08 -07003361 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003362 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3363 try {
3364 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3365 mUidFirewallPowerSaveRules);
3366 } finally {
3367 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3368 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003369 }
3370
Felipe Lemef0823852016-06-08 13:43:08 -07003371 void updateRuleForRestrictPowerUL(int uid) {
3372 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003373 }
3374
Felipe Lemef0823852016-06-08 13:43:08 -07003375 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003376 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3377 try {
3378 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3379 mUidFirewallDozableRules);
3380 } finally {
3381 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3382 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003383 }
3384
Felipe Lemef0823852016-06-08 13:43:08 -07003385 void updateRuleForDeviceIdleUL(int uid) {
3386 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003387 }
3388
Felipe Lemef28983d2016-03-25 12:18:23 -07003389 // NOTE: since both fw_dozable and fw_powersave uses the same map
3390 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003391 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003392 SparseIntArray rules) {
3393 if (enabled) {
3394 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003395 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003396 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003397 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003398 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003399 for (int ui = users.size() - 1; ui >= 0; ui--) {
3400 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003401 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3402 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3403 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3404 updateRulesForWhitelistedAppIds(uidRules,
3405 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003406 }
3407 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003408 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003409 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003410 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3411 }
3412 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003413 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003414 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003415 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003416 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003417 }
3418
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003419 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3420 final SparseBooleanArray whitelistedAppIds, int userId) {
3421 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3422 if (whitelistedAppIds.valueAt(i)) {
3423 final int appId = whitelistedAppIds.keyAt(i);
3424 final int uid = UserHandle.getUid(userId, appId);
3425 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3426 }
3427 }
3428 }
3429
3430 /**
3431 * @param deviceIdleMode if true then we don't consider
3432 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3433 * whitelisted.
3434 */
3435 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003436 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003437 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3438 || mPowerSaveWhitelistAppIds.get(appId);
3439 if (!deviceIdleMode) {
3440 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3441 }
3442 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003443 }
3444
Felipe Lemef28983d2016-03-25 12:18:23 -07003445 // NOTE: since both fw_dozable and fw_powersave uses the same map
3446 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003447 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003448 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003449 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3450 chain == FIREWALL_CHAIN_DOZABLE);
3451 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003452 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003453 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003454 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003455 }
3456 }
3457 }
3458
Felipe Lemef0823852016-06-08 13:43:08 -07003459 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003460 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3461 try {
3462 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3463 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003464
Felipe Leme873a83a2016-09-07 11:34:10 -07003465 // Fully update the app idle firewall chain.
3466 final List<UserInfo> users = mUserManager.getUsers();
3467 for (int ui = users.size() - 1; ui >= 0; ui--) {
3468 UserInfo user = users.get(ui);
3469 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3470 for (int uid : idleUids) {
3471 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3472 // quick check: if this uid doesn't have INTERNET permission, it
3473 // doesn't have network access anyway, so it is a waste to mess
3474 // with it here.
3475 if (hasInternetPermissions(uid)) {
3476 uidRules.put(uid, FIREWALL_RULE_DENY);
3477 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003478 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003479 }
3480 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003481
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003482 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003483 } finally {
3484 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3485 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003486 }
3487
Felipe Lemef0823852016-06-08 13:43:08 -07003488 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003489 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003490
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003491 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3492 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3493 }
3494 try {
3495 int appId = UserHandle.getAppId(uid);
3496 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3497 && !isUidForegroundOnRestrictPowerUL(uid)) {
3498 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3499 } else {
3500 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3501 }
3502 } finally {
3503 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003504 }
3505 }
3506
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003507 /**
3508 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3509 * changed.
3510 */
Felipe Lemef0823852016-06-08 13:43:08 -07003511 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003512 boolean paroled = mUsageStats.isAppIdleParoleOn();
3513 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003514 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003515
3516 int ruleCount = mUidFirewallStandbyRules.size();
3517 for (int i = 0; i < ruleCount; i++) {
3518 int uid = mUidFirewallStandbyRules.keyAt(i);
3519 int oldRules = mUidRules.get(uid);
3520 if (enableChain) {
3521 // Chain wasn't enabled before and the other power-related
3522 // chains are whitelists, so we can clear the
3523 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3524 // the effective rules result in blocking network access.
3525 oldRules &= MASK_METERED_NETWORKS;
3526 } else {
3527 // Skip if it had no restrictions to begin with
3528 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3529 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003530 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3531 if (newUidRules == RULE_NONE) {
3532 mUidRules.delete(uid);
3533 } else {
3534 mUidRules.put(uid, newUidRules);
3535 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003536 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003537 }
3538
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003539 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003540 * Update rules that might be changed by {@link #mRestrictBackground},
3541 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003542 */
Felipe Lemef0823852016-06-08 13:43:08 -07003543 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003544 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3545 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3546 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3547 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003548 try {
Felipe Leme09700462016-09-08 09:33:48 -07003549 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003550 updateRulesForRestrictPowerUL();
3551 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003552
Felipe Leme873a83a2016-09-07 11:34:10 -07003553 // If the set of restricted networks may have changed, re-evaluate those.
3554 if (restrictedNetworksChanged) {
3555 normalizePoliciesNL();
3556 updateNetworkRulesNL();
3557 }
3558 } finally {
3559 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003560 }
3561 }
3562
Felipe Leme09700462016-09-08 09:33:48 -07003563 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003564 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003565 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3566 try {
3567 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003568 updateRulesForPowerSaveUL();
3569 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3570 } finally {
3571 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3572 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003573 }
3574
Felipe Lemef0823852016-06-08 13:43:08 -07003575 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003576 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3577 try {
3578 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3579 } finally {
3580 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3581 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003582 }
3583
3584 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3585 private static final int TYPE_RESTRICT_POWER = 2;
3586 @Retention(RetentionPolicy.SOURCE)
3587 @IntDef(flag = false, value = {
3588 TYPE_RESTRICT_BACKGROUND,
3589 TYPE_RESTRICT_POWER,
3590 })
3591 public @interface RestrictType {
3592 }
3593
3594 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003595 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003596 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3597 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3598 }
3599 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003600 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003601
3602 final PackageManager pm = mContext.getPackageManager();
3603 final List<UserInfo> users;
3604 final List<ApplicationInfo> apps;
3605
3606 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3607 try {
3608 users = mUserManager.getUsers();
3609 } finally {
3610 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3611 }
3612 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3613 try {
3614 apps = pm.getInstalledApplications(
3615 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3616 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3617 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3618 } finally {
3619 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3620 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003621
Felipe Leme873a83a2016-09-07 11:34:10 -07003622 final int usersSize = users.size();
3623 final int appsSize = apps.size();
3624 for (int i = 0; i < usersSize; i++) {
3625 final UserInfo user = users.get(i);
3626 for (int j = 0; j < appsSize; j++) {
3627 final ApplicationInfo app = apps.get(j);
3628 final int uid = UserHandle.getUid(user.id, app.uid);
3629 switch (type) {
3630 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003631 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003632 break;
3633 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003634 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003635 break;
3636 default:
3637 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3638 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003639 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003640 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003641 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003642 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003643 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003644 }
3645
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003646 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003647 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003648 final int numUsers = users.size();
3649 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003650 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003651 int uid = UserHandle.getUid(user.id, appId);
3652 // Update external firewall rules.
3653 updateRuleForAppIdleUL(uid);
3654 updateRuleForDeviceIdleUL(uid);
3655 updateRuleForRestrictPowerUL(uid);
3656 // Update internal rules.
3657 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003658 }
3659 }
3660
Felipe Leme70c57c22016-03-29 10:45:13 -07003661 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3662 // methods below could be merged into a isUidValidForRules() method.
3663 private boolean isUidValidForBlacklistRules(int uid) {
3664 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003665 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003666 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003667 return true;
3668 }
3669
3670 return false;
3671 }
3672
Felipe Leme70c57c22016-03-29 10:45:13 -07003673 private boolean isUidValidForWhitelistRules(int uid) {
3674 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3675 }
3676
Amith Yamasani15e472352015-04-24 19:06:07 -07003677 private boolean isUidIdle(int uid) {
3678 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3679 final int userId = UserHandle.getUserId(uid);
3680
songjinshi0655edd2016-05-18 19:55:32 +08003681 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003682 for (String packageName : packages) {
3683 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3684 return false;
3685 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003686 }
3687 }
3688 return true;
3689 }
3690
3691 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003692 * Checks if an uid has INTERNET permissions.
3693 * <p>
3694 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003695 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003696 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003697 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003698 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003699 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003700 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003701 }
3702 } catch (RemoteException e) {
3703 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003704 return true;
3705 }
3706
3707 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003708 * Clears all state - internal and external - associated with an UID.
3709 */
3710 private void onUidDeletedUL(int uid) {
3711 // First cleanup in-memory state synchronously...
3712 mUidRules.delete(uid);
3713 mUidPolicy.delete(uid);
3714 mUidFirewallStandbyRules.delete(uid);
3715 mUidFirewallDozableRules.delete(uid);
3716 mUidFirewallPowerSaveRules.delete(uid);
3717 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3718 mPowerSaveWhitelistAppIds.delete(uid);
3719 mPowerSaveTempWhitelistAppIds.delete(uid);
3720
3721 // ...then update iptables asynchronously.
3722 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3723 }
3724
3725 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003726 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003727 *
Felipe Leme781ba142016-05-09 16:24:48 -07003728 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003729 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003730 * <li>Doze mode
3731 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003732 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003733 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003734 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003735 *
3736 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003737 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003738 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003739 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003740 updateRuleForDeviceIdleUL(uid);
3741 updateRuleForAppIdleUL(uid);
3742 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003743
3744 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003745 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003746
3747 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003748 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003749 }
3750
Felipe Leme70c57c22016-03-29 10:45:13 -07003751 /**
3752 * Applies network rules to bandwidth controllers based on process state and user-defined
3753 * restrictions (blacklist / whitelist).
3754 *
3755 * <p>
3756 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3757 * networks:
3758 * <ul>
3759 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3760 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3761 * also blacklisted.
3762 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3763 * no UIDs other those whitelisted will have access.
3764 * <ul>
3765 *
3766 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3767 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3768 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3769 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003770 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003771 * {@link INetworkManagementService}, but this method should also be called in events (like
3772 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3773 * following rules should also be applied:
3774 *
3775 * <ul>
3776 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3777 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3778 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3779 * {@code bw_penalty_box}.
3780 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3781 * </ul>
3782 *
3783 * <p>For optimization, the rules are only applied on user apps that have internet access
3784 * permission, since there is no need to change the {@code iptables} rule if the app does not
3785 * have permission to use the internet.
3786 *
3787 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003788 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003789 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003790 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003791 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3792 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3793 "updateRulesForDataUsageRestrictionsUL: " + uid);
3794 }
3795 try {
3796 updateRulesForDataUsageRestrictionsULInner(uid);
3797 } finally {
3798 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3799 }
3800 }
3801
3802 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003803 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003804 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003805 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003806 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003807
Dianne Hackborn497175b2014-07-01 12:56:08 -07003808 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003809 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003810 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003811 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003812
Felipe Leme781ba142016-05-09 16:24:48 -07003813 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003814 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003815 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3816 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003817
Felipe Leme70c57c22016-03-29 10:45:13 -07003818 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003819 if (isRestrictedByAdmin) {
3820 newRule = RULE_REJECT_METERED;
3821 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003822 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3823 newRule = RULE_TEMPORARY_ALLOW_METERED;
3824 } else if (isWhitelisted) {
3825 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003826 }
3827 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003828 if (isBlacklisted) {
3829 newRule = RULE_REJECT_METERED;
3830 } else if (mRestrictBackground && isWhitelisted) {
3831 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003832 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003833 }
Felipe Leme781ba142016-05-09 16:24:48 -07003834 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003835
Felipe Lemef28983d2016-03-25 12:18:23 -07003836 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003837 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003838 + ": isForeground=" +isForeground
3839 + ", isBlacklisted=" + isBlacklisted
3840 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003841 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003842 + ", oldRule=" + uidRulesToString(oldRule)
3843 + ", newRule=" + uidRulesToString(newRule)
3844 + ", newUidRules=" + uidRulesToString(newUidRules)
3845 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003846 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003847
Felipe Leme46c4fc32016-05-04 09:21:43 -07003848 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003849 mUidRules.delete(uid);
3850 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003851 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003852 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003853
Felipe Leme70c57c22016-03-29 10:45:13 -07003854 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003855 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003856 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003857 // Temporarily whitelist foreground app, removing from blacklist if necessary
3858 // (since bw_penalty_box prevails over bw_happy_box).
3859
3860 setMeteredNetworkWhitelist(uid, true);
3861 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3862 // but ideally it should be just:
3863 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003864 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003865 setMeteredNetworkBlacklist(uid, false);
3866 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003867 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003868 // Remove temporary whitelist from app that is not on foreground anymore.
3869
3870 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3871 // but ideally they should be just:
3872 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3873 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003874 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003875 setMeteredNetworkWhitelist(uid, false);
3876 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003877 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003878 setMeteredNetworkBlacklist(uid, true);
3879 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003880 } else if (hasRule(newRule, RULE_REJECT_METERED)
3881 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003882 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003883 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003884 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003885 // Since blacklist prevails over whitelist, we need to handle the special case
3886 // where app is whitelisted and blacklisted at the same time (although such
3887 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003888 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003889 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003890 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3891 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003892 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003893 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003894 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003895 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003896 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3897 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003898 + ", whitelisted=" + isWhitelisted
3899 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003900 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003901 + ", newRule=" + uidRulesToString(newUidRules)
3902 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003903 }
Felipe Leme781ba142016-05-09 16:24:48 -07003904
Sudheer Shankac9d94072017-02-22 22:13:55 +00003905 // Dispatch changed rule to existing listeners.
3906 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003907 }
3908 }
3909
3910 /**
3911 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3912 * listeners in case of change.
3913 * <p>
3914 * There are 3 power-related rules that affects whether an app has background access on
3915 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3916 * restriction, it's added to the equivalent firewall chain:
3917 * <ul>
3918 * <li>App is idle: {@code fw_standby} firewall chain.
3919 * <li>Device is idle: {@code fw_dozable} firewall chain.
3920 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3921 * </ul>
3922 * <p>
3923 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3924 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3925 * <p>
3926 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3927 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003928 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003929 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3930
Sudheer Shankac9d94072017-02-22 22:13:55 +00003931 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003932
Sudheer Shankac9d94072017-02-22 22:13:55 +00003933 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003934 mUidRules.delete(uid);
3935 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003936 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003937 }
3938 }
3939
3940 /**
3941 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3942 *
3943 * @param uid the uid of the app to update rules for
3944 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3945 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3946 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003947 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003948 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003949 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003950 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3951 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3952 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3953 + (paroled ? "P" : "-"));
3954 }
3955 try {
3956 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3957 } finally {
3958 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3959 }
3960 }
3961
3962 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003963 if (!isUidValidForBlacklistRules(uid)) {
3964 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003965 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003966 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003967
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003968 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003969 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003970 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003971
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003972 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003973 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3974 int newRule = RULE_NONE;
3975
3976 // First step: define the new rule based on user restrictions and foreground state.
3977
3978 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3979 // by considering the foreground and non-foreground states.
3980 if (isForeground) {
3981 if (restrictMode) {
3982 newRule = RULE_ALLOW_ALL;
3983 }
3984 } else if (restrictMode) {
3985 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3986 }
3987
3988 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3989
3990 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003991 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003992 + ", isIdle: " + isIdle
3993 + ", mRestrictPower: " + mRestrictPower
3994 + ", mDeviceIdleMode: " + mDeviceIdleMode
3995 + ", isForeground=" + isForeground
3996 + ", isWhitelisted=" + isWhitelisted
3997 + ", oldRule=" + uidRulesToString(oldRule)
3998 + ", newRule=" + uidRulesToString(newRule)
3999 + ", newUidRules=" + uidRulesToString(newUidRules)
4000 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4001 }
4002
Felipe Leme781ba142016-05-09 16:24:48 -07004003 // Second step: notify listeners if state changed.
4004 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004005 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004006 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004007 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004008 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4009 } else {
4010 // All scenarios should have been covered above
4011 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4012 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004013 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004014 + ", newRule=" + uidRulesToString(newUidRules)
4015 + ", oldRule=" + uidRulesToString(oldUidRules));
4016 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004017 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004018 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004019
Sudheer Shankac9d94072017-02-22 22:13:55 +00004020 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004021 }
4022
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004023 private class AppIdleStateChangeListener
4024 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4025
4026 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004027 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4028 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004029 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004030 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4031 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004032 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004033 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004034 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004035 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004036 }
4037 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004038 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004039 }
4040
4041 @Override
4042 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004043 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004044 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004045 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004046 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004047 }
4048 }
4049
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004050 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4051 if (listener != null) {
4052 try {
4053 listener.onUidRulesChanged(uid, uidRules);
4054 } catch (RemoteException ignored) {
4055 }
4056 }
4057 }
4058
4059 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4060 String[] meteredIfaces) {
4061 if (listener != null) {
4062 try {
4063 listener.onMeteredIfacesChanged(meteredIfaces);
4064 } catch (RemoteException ignored) {
4065 }
4066 }
4067 }
4068
4069 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4070 boolean restrictBackground) {
4071 if (listener != null) {
4072 try {
4073 listener.onRestrictBackgroundChanged(restrictBackground);
4074 } catch (RemoteException ignored) {
4075 }
4076 }
4077 }
4078
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004079 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4080 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004081 if (listener != null) {
4082 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004083 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004084 } catch (RemoteException ignored) {
4085 }
4086 }
4087 }
4088
Jeff Sharkey9252b342018-01-19 07:58:35 +09004089 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4090 int overrideMask, int overrideValue) {
4091 if (listener != null) {
4092 try {
4093 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4094 } catch (RemoteException ignored) {
4095 }
4096 }
4097 }
4098
Makoto Onuki8e777332017-03-28 11:25:47 -07004099 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004100 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004101 public boolean handleMessage(Message msg) {
4102 switch (msg.what) {
4103 case MSG_RULES_CHANGED: {
4104 final int uid = msg.arg1;
4105 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004106 final int length = mListeners.beginBroadcast();
4107 for (int i = 0; i < length; i++) {
4108 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4109 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004110 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004111 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004112 return true;
4113 }
4114 case MSG_METERED_IFACES_CHANGED: {
4115 final String[] meteredIfaces = (String[]) msg.obj;
4116 final int length = mListeners.beginBroadcast();
4117 for (int i = 0; i < length; i++) {
4118 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004119 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004120 }
4121 mListeners.finishBroadcast();
4122 return true;
4123 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004124 case MSG_LIMIT_REACHED: {
4125 final String iface = (String) msg.obj;
4126
Felipe Lemef0823852016-06-08 13:43:08 -07004127 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004128 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004129 // force stats update to make sure we have
4130 // numbers that caused alert to trigger.
4131 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004132
Felipe Lemef0823852016-06-08 13:43:08 -07004133 updateNetworkEnabledNL();
4134 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004135 }
4136 }
4137 return true;
4138 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004139 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4140 final boolean restrictBackground = msg.arg1 != 0;
4141 final int length = mListeners.beginBroadcast();
4142 for (int i = 0; i < length; i++) {
4143 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004144 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004145 }
4146 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004147 final Intent intent =
4148 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4149 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4150 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4151 return true;
4152 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004153 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004154 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004155 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004156 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004157 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004158 final int length = mListeners.beginBroadcast();
4159 for (int i = 0; i < length; i++) {
4160 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004161 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004162 }
4163 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004164 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4165 if (notifyApp.booleanValue()) {
4166 broadcastRestrictBackgroundChanged(uid, notifyApp);
4167 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004168 return true;
4169 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004170 case MSG_ADVISE_PERSIST_THRESHOLD: {
4171 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004172 // make sure stats are recorded frequently enough; we aim
4173 // for 2MB threshold for 2GB/month rules.
4174 final long persistThreshold = lowestRule / 1000;
4175 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004176 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004177 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004178 case MSG_UPDATE_INTERFACE_QUOTA: {
4179 removeInterfaceQuota((String) msg.obj);
4180 // int params need to be stitched back into a long
4181 setInterfaceQuota((String) msg.obj,
4182 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4183 return true;
4184 }
4185 case MSG_REMOVE_INTERFACE_QUOTA: {
4186 removeInterfaceQuota((String) msg.obj);
4187 return true;
4188 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004189 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4190 resetUidFirewallRules(msg.arg1);
4191 return true;
4192 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004193 case MSG_SUBSCRIPTION_OVERRIDE: {
4194 final int overrideMask = msg.arg1;
4195 final int overrideValue = msg.arg2;
4196 final int subId = (int) msg.obj;
4197 final int length = mListeners.beginBroadcast();
4198 for (int i = 0; i < length; i++) {
4199 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4200 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4201 }
4202 mListeners.finishBroadcast();
4203 return true;
4204 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004205 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4206 final int userId = msg.arg1;
4207 final Set<String> packageNames = (Set<String>) msg.obj;
4208 setMeteredRestrictedPackagesInternal(packageNames, userId);
4209 return true;
4210 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004211 default: {
4212 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004213 }
4214 }
4215 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004216 };
4217
4218 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4219 @Override
4220 public boolean handleMessage(Message msg) {
4221 switch (msg.what) {
4222 case UID_MSG_STATE_CHANGED: {
4223 final int uid = msg.arg1;
4224 final int procState = msg.arg2;
4225 final long procStateSeq = (Long) msg.obj;
4226
4227 handleUidChanged(uid, procState, procStateSeq);
4228 return true;
4229 }
4230 case UID_MSG_GONE: {
4231 final int uid = msg.arg1;
4232 handleUidGone(uid);
4233 return true;
4234 }
4235 default: {
4236 return false;
4237 }
4238 }
4239 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004240
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004241 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004242
Makoto Onuki8e777332017-03-28 11:25:47 -07004243 void handleUidChanged(int uid, int procState, long procStateSeq) {
4244 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4245 try {
4246 synchronized (mUidRulesFirstLock) {
4247 // We received a uid state change callback, add it to the history so that it
4248 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004249 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004250 // Now update the network policy rules as per the updated uid state.
4251 updateUidStateUL(uid, procState);
4252 // Updating the network rules is done, so notify AMS about this.
4253 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4254 }
4255 } finally {
4256 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4257 }
4258 }
4259
4260 void handleUidGone(int uid) {
4261 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4262 try {
4263 synchronized (mUidRulesFirstLock) {
4264 removeUidStateUL(uid);
4265 }
4266 } finally {
4267 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4268 }
4269 }
4270
Felipe Leme57e3d312016-08-23 14:42:52 -07004271 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4272 final PackageManager pm = mContext.getPackageManager();
4273 final String[] packages = pm.getPackagesForUid(uid);
4274 if (packages != null) {
4275 final int userId = UserHandle.getUserId(uid);
4276 for (String packageName : packages) {
4277 final Intent intent =
4278 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4279 intent.setPackage(packageName);
4280 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4281 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4282 }
4283 }
4284 }
4285
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004286 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4287 // long quotaBytes split up into two ints to fit in message
4288 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4289 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4290 }
4291
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004292 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004293 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004294 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004295 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004296 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004297 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004298 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004299 }
4300 }
4301
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004302 private void removeInterfaceQuotaAsync(String iface) {
4303 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4304 }
4305
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004306 private void removeInterfaceQuota(String iface) {
4307 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004308 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004309 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004310 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004311 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004312 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004313 }
4314 }
4315
Felipe Leme70c57c22016-03-29 10:45:13 -07004316 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4317 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004318 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004319 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004320 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004321 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4322 } catch (RemoteException e) {
4323 // ignored; service lives in system_server
4324 }
4325 }
4326
4327 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4328 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4329 try {
4330 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4331 } catch (IllegalStateException e) {
4332 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004333 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004334 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004335 }
4336 }
4337
Felipe Lemebc853dd2016-09-08 13:26:55 -07004338 private static final int CHAIN_TOGGLE_NONE = 0;
4339 private static final int CHAIN_TOGGLE_ENABLE = 1;
4340 private static final int CHAIN_TOGGLE_DISABLE = 2;
4341 @Retention(RetentionPolicy.SOURCE)
4342 @IntDef(flag = false, value = {
4343 CHAIN_TOGGLE_NONE,
4344 CHAIN_TOGGLE_ENABLE,
4345 CHAIN_TOGGLE_DISABLE
4346 })
4347 public @interface ChainToggleType {
4348 }
4349
4350 /**
4351 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004352 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004353 *
4354 * @param chain firewall chain.
4355 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4356 * @param toggle whether the chain should be enabled, disabled, or not changed.
4357 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004358 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004359 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004360 if (uidRules != null) {
4361 setUidFirewallRulesUL(chain, uidRules);
4362 }
4363 if (toggle != CHAIN_TOGGLE_NONE) {
4364 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4365 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004366 }
4367
Amith Yamasani15e472352015-04-24 19:06:07 -07004368 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004369 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4370 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4371 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004372 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004373 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004374 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004375 int size = uidRules.size();
4376 int[] uids = new int[size];
4377 int[] rules = new int[size];
4378 for(int index = size - 1; index >= 0; --index) {
4379 uids[index] = uidRules.keyAt(index);
4380 rules[index] = uidRules.valueAt(index);
4381 }
4382 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004383 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004384 } catch (IllegalStateException e) {
4385 Log.wtf(TAG, "problem setting firewall uid rules", e);
4386 } catch (RemoteException e) {
4387 // ignored; service lives in system_server
4388 }
4389 }
4390
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004391 /**
4392 * Add or remove a uid to the firewall blacklist for all network ifaces.
4393 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004394 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004395 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4396 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4397 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004398 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004399 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004400 if (chain == FIREWALL_CHAIN_DOZABLE) {
4401 mUidFirewallDozableRules.put(uid, rule);
4402 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4403 mUidFirewallStandbyRules.put(uid, rule);
4404 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4405 mUidFirewallPowerSaveRules.put(uid, rule);
4406 }
4407
4408 try {
4409 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004410 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004411 } catch (IllegalStateException e) {
4412 Log.wtf(TAG, "problem setting firewall uid rules", e);
4413 } catch (RemoteException e) {
4414 // ignored; service lives in system_server
4415 }
4416 } finally {
4417 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004418 }
4419 }
4420
4421 /**
4422 * Add or remove a uid to the firewall blacklist for all network ifaces.
4423 */
Felipe Lemef0823852016-06-08 13:43:08 -07004424 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004425 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4426 mFirewallChainStates.get(chain) == enable) {
4427 // All is the same, nothing to do.
4428 return;
4429 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004430 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004431 try {
4432 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004433 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004434 } catch (IllegalStateException e) {
4435 Log.wtf(TAG, "problem enable firewall chain", e);
4436 } catch (RemoteException e) {
4437 // ignored; service lives in system_server
4438 }
4439 }
4440
Felipe Leme03e95e22016-09-09 09:25:31 -07004441 /**
4442 * Resets all firewall rules associated with an UID.
4443 */
4444 private void resetUidFirewallRules(int uid) {
4445 try {
4446 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4447 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4448 mNetworkManager
4449 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4450 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4451 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4452 } catch (IllegalStateException e) {
4453 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4454 } catch (RemoteException e) {
4455 // ignored; service lives in system_server
4456 }
4457 }
4458
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004459 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004460 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004461 return getNetworkTotalBytes(template, start, end);
4462 }
4463
4464 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004465 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004466 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004467 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004468 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004469 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004470 }
4471 }
4472
4473 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4474 try {
4475 return mNetworkStats.getNetworkUidBytes(template, start, end);
4476 } catch (RuntimeException e) {
4477 Slog.w(TAG, "Failed to read network stats: " + e);
4478 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004479 }
4480 }
4481
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004482 private boolean isBandwidthControlEnabled() {
4483 final long token = Binder.clearCallingIdentity();
4484 try {
4485 return mNetworkManager.isBandwidthControlEnabled();
4486 } catch (RemoteException e) {
4487 // ignored; service lives in system_server
4488 return false;
4489 } finally {
4490 Binder.restoreCallingIdentity(token);
4491 }
4492 }
4493
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004494 private static Intent buildAllowBackgroundDataIntent() {
4495 return new Intent(ACTION_ALLOW_BACKGROUND);
4496 }
4497
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004498 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4499 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004500 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4501 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4502 return intent;
4503 }
4504
4505 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4506 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4507 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004508 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4509 return intent;
4510 }
4511
Wei Liu546cb772016-07-21 16:19:01 -07004512 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004513 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004514 intent.setComponent(ComponentName.unflattenFromString(
4515 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004516 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4517 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4518 return intent;
4519 }
4520
Wei Liu546cb772016-07-21 16:19:01 -07004521 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004522 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004523 intent.setComponent(ComponentName.unflattenFromString(
4524 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004525 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4526 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4527 return intent;
4528 }
4529
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004530 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004531 public void addIdleHandler(IdleHandler handler) {
4532 mHandler.getLooper().getQueue().addIdleHandler(handler);
4533 }
4534
jackqdyulei29c82ab2017-03-10 14:09:16 -08004535 @VisibleForTesting
4536 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4537 mRestrictBackgroundPowerState = result;
4538
4539 boolean restrictBackground = result.batterySaverEnabled;
4540 boolean shouldInvokeRestrictBackground;
4541 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4542 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4543
4544 if (result.globalBatterySaverEnabled) {
4545 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4546 // turn it on.
4547 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4548 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4549 localRestrictBgChangedInBsm = false;
4550 } else {
4551 // Try to restore the restrictBackground if it doesn't change in bsm
4552 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4553 restrictBackground = mRestrictBackgroundBeforeBsm;
4554 }
4555
4556 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004557 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004558 }
4559
4560 // Change it at last so setRestrictBackground() won't affect this variable
4561 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4562 }
4563
Jeff Sharkey1b861272011-05-22 00:34:52 -07004564 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4565 final int size = source.size();
4566 for (int i = 0; i < size; i++) {
4567 target.put(source.keyAt(i), true);
4568 }
4569 }
4570
Stuart Scottf1fb3972015-04-02 18:00:02 -07004571 @Override
4572 public void factoryReset(String subscriber) {
4573 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4574
Stuart Scotte3e314d2015-04-20 14:07:45 -07004575 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4576 return;
4577 }
4578
Stuart Scottf1fb3972015-04-02 18:00:02 -07004579 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004580 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004581 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4582 for (NetworkPolicy policy : policies) {
4583 if (policy.template.equals(template)) {
4584 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4585 policy.inferred = false;
4586 policy.clearSnooze();
4587 }
4588 }
4589 setNetworkPolicies(policies);
4590
4591 // Turn restrict background data off
4592 setRestrictBackground(false);
4593
Stuart Scotte3e314d2015-04-20 14:07:45 -07004594 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4595 // Remove app's "restrict background data" flag
4596 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4597 setUidPolicy(uid, POLICY_NONE);
4598 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004599 }
4600 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004601
Sudheer Shankab8f23162017-08-04 13:30:10 -07004602 @Override
4603 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4604 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4605 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4606 }
4607
4608 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4609 final int uidRules;
4610 final boolean isBackgroundRestricted;
4611 synchronized (mUidRulesFirstLock) {
4612 uidRules = mUidRules.get(uid, RULE_NONE);
4613 isBackgroundRestricted = mRestrictBackground;
4614 }
4615 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004616 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004617 return true;
4618 }
4619 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004620 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004621 return false;
4622 }
4623 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004624 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004625 return true;
4626 }
4627 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004628 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004629 return false;
4630 }
4631 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004632 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004633 return false;
4634 }
4635 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004636 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004637 return true;
4638 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004639 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004640 return false;
4641 }
4642
Felipe Lemed17fda42016-04-29 11:12:45 -07004643 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4644
4645 @Override
4646 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004647 synchronized (mUidRulesFirstLock) {
4648 boolean changed = removeUserStateUL(userId, false);
4649 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004650 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004651 synchronized (mNetworkPoliciesSecondLock) {
4652 writePolicyAL();
4653 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004654 }
4655 }
4656 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004657
4658 /**
4659 * @return true if the given uid is restricted from doing networking on metered networks.
4660 */
4661 @Override
4662 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4663 final int uidRules;
4664 final boolean isBackgroundRestricted;
4665 synchronized (mUidRulesFirstLock) {
4666 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4667 isBackgroundRestricted = mRestrictBackground;
4668 }
4669 return isBackgroundRestricted
4670 && !hasRule(uidRules, RULE_ALLOW_METERED)
4671 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4672 }
4673
4674 /**
4675 * @return true if networking is blocked on the given interface for the given uid according
4676 * to current networking policies.
4677 */
4678 @Override
4679 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004680 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004681 synchronized (mNetworkPoliciesSecondLock) {
4682 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004683 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004684 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004685 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004686
4687 @Override
4688 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4689 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004690 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004691 if (added) {
4692 mPowerSaveTempWhitelistAppIds.put(appId, true);
4693 } else {
4694 mPowerSaveTempWhitelistAppIds.delete(appId);
4695 }
4696 updateRulesForTempWhitelistChangeUL(appId);
4697 }
4698 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004699
4700 @Override
4701 public SubscriptionPlan getSubscriptionPlan(Network network) {
4702 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004703 final int subId = getSubIdLocked(network);
4704 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004705 }
4706 }
4707
4708 @Override
4709 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004710 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004711 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004712 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004713 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004714 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004715 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4716 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4717 }
4718
4719 if (quotaType == QUOTA_TYPE_JOBS) {
4720 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4721 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4722 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4723 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4724 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4725 } else {
4726 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4727 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004728 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004729
4730 @Override
4731 public void onAdminDataAvailable() {
4732 mAdminDataAvailableLatch.countDown();
4733 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004734
4735 @Override
4736 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4737 setMeteredRestrictedPackagesInternal(packageNames, userId);
4738 }
4739
4740 @Override
4741 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4742 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4743 userId, 0, packageNames).sendToTarget();
4744 }
4745 }
4746
4747 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4748 synchronized (mUidRulesFirstLock) {
4749 final Set<Integer> newRestrictedUids = new ArraySet<>();
4750 for (String packageName : packageNames) {
4751 final int uid = getUidForPackage(packageName, userId);
4752 if (uid >= 0) {
4753 newRestrictedUids.add(uid);
4754 }
4755 }
4756 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4757 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4758 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4759 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4760 }
4761 }
4762
4763 private int getUidForPackage(String packageName, int userId) {
4764 try {
4765 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4766 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4767 } catch (NameNotFoundException e) {
4768 return -1;
4769 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004770 }
4771
4772 private int parseSubId(NetworkState state) {
4773 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4774 int subId = INVALID_SUBSCRIPTION_ID;
4775 if (state != null && state.networkCapabilities != null
4776 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4777 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4778 if (spec instanceof StringNetworkSpecifier) {
4779 try {
4780 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4781 } catch (NumberFormatException e) {
4782 }
4783 }
4784 }
4785 return subId;
4786 }
4787
Andreas Gampea36dc622018-02-05 17:19:22 -08004788 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004789 private int getSubIdLocked(Network network) {
4790 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004791 }
4792
Andreas Gampea36dc622018-02-05 17:19:22 -08004793 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004794 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4795 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4796 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4797 }
4798
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004799 /**
4800 * This will only ever be called once - during device boot.
4801 */
4802 private void waitForAdminData() {
4803 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4804 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4805 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4806 }
4807 }
4808
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004809 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4810 Set<Integer> newRestrictedUids) {
4811 if (oldRestrictedUids == null) {
4812 for (int uid : newRestrictedUids) {
4813 updateRulesForDataUsageRestrictionsUL(uid);
4814 }
4815 return;
4816 }
4817 for (int uid : oldRestrictedUids) {
4818 if (!newRestrictedUids.contains(uid)) {
4819 updateRulesForDataUsageRestrictionsUL(uid);
4820 }
4821 }
4822 for (int uid : newRestrictedUids) {
4823 if (!oldRestrictedUids.contains(uid)) {
4824 updateRulesForDataUsageRestrictionsUL(uid);
4825 }
4826 }
4827 }
4828
4829 private boolean isRestrictedByAdminUL(int uid) {
4830 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4831 UserHandle.getUserId(uid));
4832 return restrictedUids != null && restrictedUids.contains(uid);
4833 }
4834
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004835 private static boolean hasRule(int uidRules, int rule) {
4836 return (uidRules & rule) != 0;
4837 }
4838
Jeff Sharkey2e471452018-01-19 18:02:47 +09004839 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4840 return (val != null) ? val : new NetworkState[0];
4841 }
4842
Chris Wren193ae6b2017-03-31 15:17:11 -04004843 private class NotificationId {
4844 private final String mTag;
4845 private final int mId;
4846
4847 NotificationId(NetworkPolicy policy, int type) {
4848 mTag = buildNotificationTag(policy, type);
4849 mId = type;
4850 }
4851
4852 @Override
4853 public boolean equals(Object o) {
4854 if (this == o) return true;
4855 if (!(o instanceof NotificationId)) return false;
4856 NotificationId that = (NotificationId) o;
4857 return Objects.equals(mTag, that.mTag);
4858 }
4859
4860 @Override
4861 public int hashCode() {
4862 return Objects.hash(mTag);
4863 }
4864
4865 /**
4866 * Build unique tag that identifies an active {@link NetworkPolicy}
4867 * notification of a specific type, like {@link #TYPE_LIMIT}.
4868 */
4869 private String buildNotificationTag(NetworkPolicy policy, int type) {
4870 return TAG + ":" + policy.template.hashCode() + ":" + type;
4871 }
4872
4873 public String getTag() {
4874 return mTag;
4875 }
4876
4877 public int getId() {
4878 return mId;
4879 }
4880 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004881}