blob: b9c60746ca46fb91bb55ae382e6da2cc792841d3 [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;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070073import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070074import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060075import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090076import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070084import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
85import static com.android.internal.util.XmlUtils.writeIntAttribute;
86import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060087import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070088import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070089import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
90import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
91import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
92import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
93import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
94import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
95import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060097
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080099import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700101
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700102import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700103import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900104import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700105import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700106import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800107import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700109import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700111import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700113import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700115import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700116import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700117import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700119import android.content.Intent;
120import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700121import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700122import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700123import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700124import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700125import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600128import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700130import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700131import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700132import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700133import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700134import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600135import android.net.Network;
136import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700137import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600139import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700140import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900142import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700143import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700144import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700145import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900146import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700148import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700149import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700150import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700151import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import android.os.Environment;
153import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700154import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700155import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700156import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700157import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700158import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700159import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700160import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700161import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700162import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600163import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800164import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700165import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700166import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600167import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700169import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700170import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600171import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700172import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700173import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700174import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700175import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100176import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700177import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600178import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800179import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600180import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700181import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400182import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700183import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700184import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700185import android.util.ArrayMap;
186import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700187import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900188import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700189import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700190import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600191import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600192import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700193import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600194import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195import android.util.SparseBooleanArray;
196import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900197import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700199
Jeff Sharkey497e4432011-06-14 17:27:29 -0700200import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700201import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800202import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400203import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500204import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700205import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800206import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800207import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600208import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700210import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600211import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700212import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700213import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700214import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800215import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600216
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600217import libcore.io.IoUtils;
218
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220import org.xmlpull.v1.XmlSerializer;
221
222import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700223import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224import java.io.FileInputStream;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700228import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700229import java.lang.annotation.Retention;
230import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100231import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700232import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900233import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600234import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700235import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600236import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900237import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700239import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600240import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400241import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800242import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800243import java.util.concurrent.CountDownLatch;
244import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700246/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700247 * Service that maintains low-level network policy rules, using
248 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700249 * <p>
250 * Derives active rules by combining a given policy with other system status,
251 * and delivers to listeners, such as {@link ConnectivityManager}, for
252 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700253 *
254 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000255 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700256 * <ul>
257 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
258 * rules).
259 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
260 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000261 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
262 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700263 * </ul>
264 *
265 * <p>
266 * As such, methods that require synchronization have the following prefixes:
267 * <ul>
268 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
269 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000270 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
271 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700272 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700273 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700274public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700275 static final String TAG = NetworkPolicyLogger.TAG;
276 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
277 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700278
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900279 /**
280 * No opportunistic quota could be calculated from user data plan or data settings.
281 */
282 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 private static final int VERSION_INIT = 1;
285 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700286 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800287 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800288 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800289 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700290 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700291 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700293 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600294 private static final int VERSION_ADDED_CYCLE = 11;
295 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700296
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800297 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400298 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800299 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400300 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800301 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400302 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900303 @VisibleForTesting
304 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700305
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 private static final String TAG_POLICY_LIST = "policy-list";
307 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700310 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800311 private static final String TAG_WHITELIST = "whitelist";
312 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800313 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
315 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700316 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
318 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700319 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600320 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
321 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
322 private static final String ATTR_CYCLE_START = "cycleStart";
323 private static final String ATTR_CYCLE_END = "cycleEnd";
324 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String ATTR_WARNING_BYTES = "warningBytes";
326 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700327 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800328 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
329 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800330 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700331 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700333 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600335 private static final String ATTR_SUB_ID = "subId";
336 private static final String ATTR_TITLE = "title";
337 private static final String ATTR_SUMMARY = "summary";
338 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
339 private static final String ATTR_USAGE_BYTES = "usageBytes";
340 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600341 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800343 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800345 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800346 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700347 private static final String ACTION_SNOOZE_RAPID =
348 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700349
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800350 /**
351 * Indicates the maximum wait time for admin data to be available;
352 */
353 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
354
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700355 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700356 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800357 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800358 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700359 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700360 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
361 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700362 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700363 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900364 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800365 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700366
Makoto Onuki8e777332017-03-28 11:25:47 -0700367 private static final int UID_MSG_STATE_CHANGED = 100;
368 private static final int UID_MSG_GONE = 101;
369
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600370 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
371
Jeff Sharkey75279902011-05-24 18:39:45 -0700372 private final Context mContext;
373 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700374 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700375 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700376 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700377 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700378 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700379 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700380
381 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700382 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700383 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800384 @GuardedBy("mUidRulesFirstLock")
385 private PowerSaveState mRestrictBackgroundPowerState;
386
387 // Store the status of restrict background before turning on battery saver.
388 // Used to restore mRestrictBackground when battery saver is turned off.
389 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700390
Sudheer Shanka543339f2017-07-28 15:18:07 -0700391 // Denotes the status of restrict background read from disk.
392 private boolean mLoadedRestrictBackground;
393
Felipe Lemef0823852016-06-08 13:43:08 -0700394 // See main javadoc for instructions on how to use these locks.
395 final Object mUidRulesFirstLock = new Object();
396 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700397
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("allLocks") volatile boolean mSystemReady;
399
Felipe Lemef0823852016-06-08 13:43:08 -0700400 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
401 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
402 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800403 // Store whether user flipped restrict background in battery saver mode
404 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700405
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700406 private final boolean mSuppressDefaultPolicy;
407
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800408 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
409
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700410 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600411 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800412 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700413
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600414 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600415 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600416 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600417 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600418 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600419 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600420
Jeff Sharkey9252b342018-01-19 07:58:35 +0900421 /** Map from subId to daily opportunistic quota. */
422 @GuardedBy("mNetworkPoliciesSecondLock")
423 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
424
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700425 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700426 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700427 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700429
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700431 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700432 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700433 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700434 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800435 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700436
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700437 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700438 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700439 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
440
Jeff Sharkey32566012014-12-02 18:30:14 -0800441 /**
442 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700443 * in power save mode, except device idle (doze) still applies.
444 * TODO: An int array might be sufficient
445 */
Felipe Lemef0823852016-06-08 13:43:08 -0700446 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700447 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
448
449 /**
450 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800451 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700452 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800453 */
Felipe Lemef0823852016-06-08 13:43:08 -0700454 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700455 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700456
Felipe Lemef0823852016-06-08 13:43:08 -0700457 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700458 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
459
Felipe Lemeb85a6372016-01-14 16:16:16 -0800460 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800461 * UIDs that have been initially white-listed by system to avoid restricted background.
462 */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800464 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
465 new SparseBooleanArray();
466
467 /**
468 * UIDs that have been initially white-listed by system to avoid restricted background,
469 * but later revoked by user.
470 */
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800472 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
473 new SparseBooleanArray();
474
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700475 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700476 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800477 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700478 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700479 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800480 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700481
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700482 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700483 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400484 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700485
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700486 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700487 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800488 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700489
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600490 /** Map from network ID to last observed meteredness state */
491 @GuardedBy("mNetworkPoliciesSecondLock")
492 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
493
Jeff Sharkey9252b342018-01-19 07:58:35 +0900494 /** Map from netId to subId as of last update */
495 @GuardedBy("mNetworkPoliciesSecondLock")
496 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
497
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800498 /**
499 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
500 * userId to restricted uids which belong to that user.
501 */
502 @GuardedBy("mUidRulesFirstLock")
503 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
504
Jeff Sharkey32566012014-12-02 18:30:14 -0800505 private final RemoteCallbackList<INetworkPolicyListener>
506 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700507
Dianne Hackborn497175b2014-07-01 12:56:08 -0700508 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700509 @VisibleForTesting
510 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700511
512 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700513
Felipe Lemef0823852016-06-08 13:43:08 -0700514 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700515 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700516
Svet Ganov16a16892015-04-16 10:32:04 -0700517 private final AppOpsManager mAppOps;
518
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800519 private final IPackageManager mIPm;
520
Sudheer Shankae7361852017-03-07 11:51:46 -0800521 private ActivityManagerInternal mActivityManagerInternal;
522
Sudheer Shanka352dc572017-09-22 17:09:38 -0700523 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800524
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700525 // TODO: keep whitelist of system-critical services that should never have
526 // rules enforced, such as system, phone, and radio UIDs.
527
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700528 // TODO: migrate notifications to SystemUI
529
Jeff Sharkey75279902011-05-24 18:39:45 -0700530 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700531 INetworkManagementService networkManagement) {
532 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
533 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700534 }
535
Jeff Sharkey9911a282018-02-14 22:29:11 -0700536 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700537 return new File(Environment.getDataDirectory(), "system");
538 }
539
Jeff Sharkey9911a282018-02-14 22:29:11 -0700540 private static @NonNull Clock getDefaultClock() {
541 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
542 Clock.systemUTC());
543 }
544
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700545 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700546 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
547 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700548 mContext = checkNotNull(context, "missing context");
549 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700550 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700551 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700552 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700553 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700554 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700555 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700556 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700557
Amith Yamasani450a16b2013-09-18 16:28:50 -0700558 HandlerThread thread = new HandlerThread(TAG);
559 thread.start();
560 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561
Makoto Onuki8e777332017-03-28 11:25:47 -0700562 // We create another thread for the UID events, which are more time-critical.
563 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
564 /*allowIo=*/ false);
565 mUidEventThread.start();
566 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
567
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700568 mSuppressDefaultPolicy = suppressDefaultPolicy;
569
Dianne Hackborne17b4452018-01-10 13:15:40 -0800570 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700571
572 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800573
Felipe Lemed17fda42016-04-29 11:12:45 -0700574 // Expose private service for system components to use.
575 LocalServices.addService(NetworkPolicyManagerInternal.class,
576 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700577 }
578
579 public void bindConnectivityManager(IConnectivityManager connManager) {
580 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700581 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700582
Felipe Lemef0823852016-06-08 13:43:08 -0700583 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700584 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700585 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
586 mPowerSaveWhitelistExceptIdleAppIds.clear();
587 if (whitelist != null) {
588 for (int uid : whitelist) {
589 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
590 }
591 }
592 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700593 mPowerSaveWhitelistAppIds.clear();
594 if (whitelist != null) {
595 for (int uid : whitelist) {
596 mPowerSaveWhitelistAppIds.put(uid, true);
597 }
598 }
599 } catch (RemoteException e) {
600 }
601 }
602
Felipe Lemea9505cc2016-02-26 10:28:41 -0800603 /**
604 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
605 * revoke the whitelist.
606 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700607 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800608 */
Felipe Lemef0823852016-06-08 13:43:08 -0700609 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800610 final List<UserInfo> users = mUserManager.getUsers();
611 final int numberUsers = users.size();
612
Felipe Lemea110eec2016-04-29 09:58:06 -0700613 boolean changed = false;
614 for (int i = 0; i < numberUsers; i++) {
615 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700616 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700617 }
618 return changed;
619 }
620
Felipe Lemef0823852016-06-08 13:43:08 -0700621 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700622 final SystemConfig sysConfig = SystemConfig.getInstance();
623 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800624 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
625 boolean changed = false;
626 for (int i = 0; i < allowDataUsage.size(); i++) {
627 final String pkg = allowDataUsage.valueAt(i);
628 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700629 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
630 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800631 final ApplicationInfo app;
632 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700633 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800634 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700635 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
636 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800637 continue;
638 }
639 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700640 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
641 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800642 continue;
643 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700644 final int uid = UserHandle.getUid(userId, app.uid);
645 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
646 if (LOGD)
647 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
648 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800649 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700650 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700651 if (LOGD)
652 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
653 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700654 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700655 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800656 }
657 }
658 return changed;
659 }
660
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800661 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700662 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800663 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700664 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800665 // Boost thread's priority during system server init
666 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700667 if (!isBandwidthControlEnabled()) {
668 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
669 return;
670 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700671
Felipe Leme873a83a2016-09-07 11:34:10 -0700672 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700673 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700674
Felipe Leme873a83a2016-09-07 11:34:10 -0700675 synchronized (mUidRulesFirstLock) {
676 synchronized (mNetworkPoliciesSecondLock) {
677 updatePowerSaveWhitelistUL();
678 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
679 mPowerManagerInternal.registerLowPowerModeObserver(
680 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800681 @Override
682 public int getServiceType() {
683 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700684 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800685
686 @Override
687 public void onLowPowerModeChanged(PowerSaveState result) {
688 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800689 if (LOGD) {
690 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
691 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800692 synchronized (mUidRulesFirstLock) {
693 if (mRestrictPower != enabled) {
694 mRestrictPower = enabled;
695 updateRulesForRestrictPowerUL();
696 }
697 }
698 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800699 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800700 mRestrictPower = mPowerManagerInternal.getLowPowerState(
701 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700702
703 mSystemReady = true;
704
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800705 waitForAdminData();
706
Felipe Leme873a83a2016-09-07 11:34:10 -0700707 // read policy from disk
708 readPolicyAL();
709
jackqdyulei29c82ab2017-03-10 14:09:16 -0800710 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700711 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800712 mRestrictBackgroundPowerState = mPowerManagerInternal
713 .getLowPowerState(ServiceType.DATA_SAVER);
714 final boolean localRestrictBackground =
715 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700716 if (localRestrictBackground && !mLoadedRestrictBackground) {
717 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800718 }
719 mPowerManagerInternal.registerLowPowerModeObserver(
720 new PowerManagerInternal.LowPowerModeListener() {
721 @Override
722 public int getServiceType() {
723 return ServiceType.DATA_SAVER;
724 }
725
726 @Override
727 public void onLowPowerModeChanged(PowerSaveState result) {
728 synchronized (mUidRulesFirstLock) {
729 updateRestrictBackgroundByLowPowerModeUL(result);
730 }
731 }
732 });
733
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
735 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700736 }
Felipe Lemef0823852016-06-08 13:43:08 -0700737
Sudheer Shanka543339f2017-07-28 15:18:07 -0700738 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700739 updateRulesForGlobalChangeAL(false);
740 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700741 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800742 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700743
Sudheer Shankae7361852017-03-07 11:51:46 -0800744 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700745 try {
746 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000747 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800748 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700749 mNetworkManager.registerObserver(mAlertObserver);
750 } catch (RemoteException e) {
751 // ignored; both services live in system_server
752 }
753
754 // listen for changes to power save whitelist
755 final IntentFilter whitelistFilter = new IntentFilter(
756 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
757 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
758
Felipe Leme873a83a2016-09-07 11:34:10 -0700759 // watch for network interfaces to be claimed
760 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
761 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
762
763 // listen for package changes to update policy
764 final IntentFilter packageFilter = new IntentFilter();
765 packageFilter.addAction(ACTION_PACKAGE_ADDED);
766 packageFilter.addDataScheme("package");
767 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
768
769 // listen for UID changes to update policy
770 mContext.registerReceiver(
771 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
772
773 // listen for user changes to update policy
774 final IntentFilter userFilter = new IntentFilter();
775 userFilter.addAction(ACTION_USER_ADDED);
776 userFilter.addAction(ACTION_USER_REMOVED);
777 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
778
779 // listen for stats update events
780 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
781 mContext.registerReceiver(
782 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
783
784 // listen for restrict background changes from notifications
785 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
786 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
787
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700788 // Listen for snooze from notifications
789 mContext.registerReceiver(mSnoozeReceiver,
790 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
791 mContext.registerReceiver(mSnoozeReceiver,
792 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700793
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600794 // listen for configured wifi networks to be loaded
795 final IntentFilter wifiFilter =
796 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
797 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700798
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700799 // listen for carrier config changes to update data cycle information
800 final IntentFilter carrierConfigFilter = new IntentFilter(
801 ACTION_CARRIER_CONFIG_CHANGED);
802 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
803
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600804 // listen for meteredness changes
805 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
806 new NetworkRequest.Builder().build(), mNetworkCallback);
807
Felipe Leme873a83a2016-09-07 11:34:10 -0700808 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800809 // tell systemReady() that the service has been initialized
810 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700811 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800812 // Restore the default priority after init is done
813 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700814 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700815 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700816 }
817
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800818 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
819 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
820 mHandler.post(() -> initService(initCompleteSignal));
821 return initCompleteSignal;
822 }
823
824 public void systemReady(CountDownLatch initCompleteSignal) {
825 // wait for initService to complete
826 try {
827 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
828 throw new IllegalStateException("Service " + TAG +" init timeout");
829 }
830 } catch (InterruptedException e) {
831 Thread.currentThread().interrupt();
832 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
833 }
834 }
835
Sudheer Shankac9d94072017-02-22 22:13:55 +0000836 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700837 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700838 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
839 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700840 }
841
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700842 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700843 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700844 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700845
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700846 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700847 }
848
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700849 @Override public void onUidIdle(int uid, boolean disabled) {
850 }
851
852 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700853 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700854 };
855
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700856 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700857 @Override
858 public void onReceive(Context context, Intent intent) {
859 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700860 synchronized (mUidRulesFirstLock) {
861 updatePowerSaveWhitelistUL();
862 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700863 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700864 }
865 }
866 };
867
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700868 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700869 @Override
870 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700871 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700872
873 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700874 final int uid = intent.getIntExtra(EXTRA_UID, -1);
875 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700876
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700877 if (ACTION_PACKAGE_ADDED.equals(action)) {
878 // update rules for UID, since it might be subject to
879 // global background data policy
880 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700881 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700882 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700883 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700884 }
885 }
886 };
887
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700888 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700889 @Override
890 public void onReceive(Context context, Intent intent) {
891 // on background handler thread, and UID_REMOVED is protected
892
893 final int uid = intent.getIntExtra(EXTRA_UID, -1);
894 if (uid == -1) return;
895
896 // remove any policy and update rules to clean up
897 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700898 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700899 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700900 synchronized (mNetworkPoliciesSecondLock) {
901 writePolicyAL();
902 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700903 }
904 }
905 };
906
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700907 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700908 @Override
909 public void onReceive(Context context, Intent intent) {
910 // on background handler thread, and USER_ADDED and USER_REMOVED
911 // broadcasts are protected
912
913 final String action = intent.getAction();
914 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
915 if (userId == -1) return;
916
Amith Yamasani15e472352015-04-24 19:06:07 -0700917 switch (action) {
918 case ACTION_USER_REMOVED:
919 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700920 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800921 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700922 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700923 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800924 // Removing outside removeUserStateUL since that can also be called when
925 // user resets app preferences.
926 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700927 if (action == ACTION_USER_ADDED) {
928 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700929 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700930 }
931 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700932 synchronized (mNetworkPoliciesSecondLock) {
933 updateRulesForGlobalChangeAL(true);
934 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700935 }
936 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700937 }
938 }
939 };
940
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700941 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700942 * Receiver that watches for {@link INetworkStatsService} updates, which we
943 * use to check against {@link NetworkPolicy#warningBytes}.
944 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700945 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700946 @Override
947 public void onReceive(Context context, Intent intent) {
948 // on background handler thread, and verified
949 // READ_NETWORK_USAGE_HISTORY permission above.
950
Felipe Lemef0823852016-06-08 13:43:08 -0700951 synchronized (mNetworkPoliciesSecondLock) {
952 updateNetworkEnabledNL();
953 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954 }
955 }
956 };
957
958 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700959 * Receiver that watches for {@link Notification} control of
960 * {@link #mRestrictBackground}.
961 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700963 @Override
964 public void onReceive(Context context, Intent intent) {
965 // on background handler thread, and verified MANAGE_NETWORK_POLICY
966 // permission above.
967
968 setRestrictBackground(false);
969 }
970 };
971
972 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800973 * Receiver that watches for {@link Notification} control of
974 * {@link NetworkPolicy#lastWarningSnooze}.
975 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700976 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800977 @Override
978 public void onReceive(Context context, Intent intent) {
979 // on background handler thread, and verified MANAGE_NETWORK_POLICY
980 // permission above.
981
982 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700983 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
984 performSnooze(template, TYPE_WARNING);
985 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
986 performSnooze(template, TYPE_RAPID);
987 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800988 }
989 };
990
991 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600992 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600993 * we can perform upgrade logic. After initial upgrade logic, it updates
994 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700995 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600996 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700997 @Override
998 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900999 synchronized (mUidRulesFirstLock) {
1000 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001001 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001002 }
1003 }
1004 // Only need to perform upgrade logic once
1005 mContext.unregisterReceiver(this);
1006 }
1007 };
1008
1009 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1010 @Override
1011 public void onCapabilitiesChanged(Network network,
1012 NetworkCapabilities networkCapabilities) {
1013 if (network == null || networkCapabilities == null) return;
1014
1015 synchronized (mNetworkPoliciesSecondLock) {
1016 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1017 final boolean newMetered = !networkCapabilities
1018 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1019
1020 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001021 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001022 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001023 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001024 }
1025 }
1026 }
1027 };
1028
1029 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001030 * Observer that watches for {@link INetworkManagementService} alerts.
1031 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001032 final private INetworkManagementEventObserver mAlertObserver
1033 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 @Override
1035 public void limitReached(String limitName, String iface) {
1036 // only someone like NMS should be calling us
1037 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1038
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001039 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1040 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 }
1042 }
1043 };
1044
1045 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1047 * to show visible notifications as needed.
1048 */
Felipe Lemef0823852016-06-08 13:43:08 -07001049 void updateNotificationsNL() {
1050 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001051
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001053 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055
1056 // TODO: when switching to kernel notifications, compute next future
1057 // cycle boundary to recompute notifications.
1058
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001059 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001060 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001061 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1062 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 // ignore policies that aren't relevant to user
1064 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001065 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001066
Jeff Sharkey53313d72017-07-13 16:47:32 -06001067 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1068 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001069 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1070 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1071 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001073 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001074 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001075 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1076 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001077 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001078 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001079 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001080 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 }
1082
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001084 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001086 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1087 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001088 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089 }
1090 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001091
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001092 // Warn if average usage over last 4 days is on track to blow pretty
1093 // far past the plan limits.
1094 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001095 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001096 final long recentStart = now - recentDuration;
1097 final long recentEnd = now;
1098 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001099
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001100 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001101 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001102 final long alertBytes = (policy.limitBytes * 3) / 2;
1103
1104 if (LOGD) {
1105 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1106 + projectedBytes + " alert " + alertBytes);
1107 }
1108
1109 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1110 - DateUtils.DAY_IN_MILLIS;
1111 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001112 enqueueNotification(policy, TYPE_RAPID, 0,
1113 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001114 }
1115 }
1116 }
1117
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001118 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001119 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001120 final NotificationId notificationId = beforeNotifs.valueAt(i);
1121 if (!mActiveNotifs.contains(notificationId)) {
1122 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001123 }
1124 }
1125 }
1126
1127 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001128 * Attempt to find a specific app to blame for rapid data usage during the
1129 * given time period.
1130 */
1131 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1132 long start, long end) {
1133 long totalBytes = 0;
1134 long maxBytes = 0;
1135 int maxUid = 0;
1136
1137 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1138 NetworkStats.Entry entry = null;
1139 for (int i = 0; i < stats.size(); i++) {
1140 entry = stats.getValues(i, entry);
1141 final long bytes = entry.rxBytes + entry.txBytes;
1142 totalBytes += bytes;
1143 if (bytes > maxBytes) {
1144 maxBytes = bytes;
1145 maxUid = entry.uid;
1146 }
1147 }
1148
1149 // Only point blame if the majority of usage was done by a single app.
1150 // TODO: support shared UIDs
1151 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1152 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001153 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001154 try {
1155 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1156 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1157 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1158 } catch (NameNotFoundException ignored) {
1159 }
1160 }
1161 }
1162
1163 return null;
1164 }
1165
1166 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001167 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001168 * current device state, such as when
1169 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1170 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001171 */
1172 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001173 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001174 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1175 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001176
Jeff Sharkey32566012014-12-02 18:30:14 -08001177 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001178 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001179 for (int subId : subIds) {
1180 final String subscriberId = tele.getSubscriberId(subId);
1181 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001182 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1183 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001184 if (template.matches(probeIdent)) {
1185 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001186 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001187 }
1188 return false;
1189 } else {
1190 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001191 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 }
1193
1194 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 * Notify that given {@link NetworkTemplate} is over
1196 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1197 */
Felipe Lemef0823852016-06-08 13:43:08 -07001198 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001199 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001200 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001201 mOverLimitNotified.add(template);
1202 }
1203 }
1204
Felipe Lemef0823852016-06-08 13:43:08 -07001205 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001206 mOverLimitNotified.remove(template);
1207 }
1208
1209 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001210 * Show notification for combined {@link NetworkPolicy} and specific type,
1211 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1212 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001213 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1214 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001215 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001216 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001217 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001218 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001219 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001220 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001221 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001222
1223 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001224 final CharSequence title;
1225 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001226 switch (type) {
1227 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001228 title = res.getText(R.string.data_usage_warning_title);
1229 body = res.getString(R.string.data_usage_warning_body,
1230 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001231
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001232 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001233
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001234 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1235 builder.setDeleteIntent(PendingIntent.getBroadcast(
1236 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1237
Wei Liu546cb772016-07-21 16:19:01 -07001238 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001239 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001240 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1241
Jeff Sharkey497e4432011-06-14 17:27:29 -07001242 break;
1243 }
1244 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001245 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001247 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001248 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001249 case MATCH_WIFI:
1250 title = res.getText(R.string.data_usage_wifi_limit_title);
1251 break;
1252 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001253 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001254 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001255 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001256
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001257 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001258 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001259
Wei Liu546cb772016-07-21 16:19:01 -07001260 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001261 builder.setContentIntent(PendingIntent.getActivity(
1262 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1263 break;
1264 }
1265 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001266 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001267 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001268 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1269 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001270 case MATCH_WIFI:
1271 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1272 break;
1273 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001274 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001275 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001276 final long overBytes = totalBytes - policy.limitBytes;
1277 body = res.getString(R.string.data_usage_limit_snoozed_body,
1278 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001279
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001280 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001281 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001282 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001283
Wei Liu546cb772016-07-21 16:19:01 -07001284 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001285 builder.setContentIntent(PendingIntent.getActivity(
1286 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001287 break;
1288 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001289 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001290 title = res.getText(R.string.data_usage_rapid_title);
1291 if (rapidBlame != null) {
1292 body = res.getString(R.string.data_usage_rapid_app_body,
1293 rapidBlame.loadLabel(mContext.getPackageManager()));
1294 } else {
1295 body = res.getString(R.string.data_usage_rapid_body);
1296 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001297
Jeff Sharkey2e471452018-01-19 18:02:47 +09001298 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001299
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001300 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1301 builder.setDeleteIntent(PendingIntent.getBroadcast(
1302 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1303
1304 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001305 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001306 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001307 break;
1308 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001309 default: {
1310 return;
1311 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001312 }
1313
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001314 builder.setTicker(title);
1315 builder.setContentTitle(title);
1316 builder.setContentText(body);
1317 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001318
1319 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1320 notificationId.getId(), builder.build(), UserHandle.ALL);
1321 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001322 }
1323
Chris Wren193ae6b2017-03-31 15:17:11 -04001324 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001325 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1326 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 }
1328
1329 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001331 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001333 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334 @Override
1335 public void onReceive(Context context, Intent intent) {
1336 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1337 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001338
Hugo Benichi446c9c92017-04-10 09:41:10 +09001339 synchronized (mUidRulesFirstLock) {
1340 synchronized (mNetworkPoliciesSecondLock) {
1341 ensureActiveMobilePolicyAL();
1342 normalizePoliciesNL();
1343 updateNetworkEnabledNL();
1344 updateNetworkRulesNL();
1345 updateNotificationsNL();
1346 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001347 }
1348 }
1349 };
1350
Jeff Sharkey2e471452018-01-19 18:02:47 +09001351 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001352 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001353 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001354 final CountDownLatch latch = new CountDownLatch(1);
1355 mHandler.post(() -> {
1356 latch.countDown();
1357 });
1358 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001359 }
1360
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001361 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001362 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1363 * if necessary.
1364 *
1365 * @param subId that has its associated NetworkPolicy updated if necessary
1366 * @return if any policies were updated
1367 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001368 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1369 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001370
1371 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001372 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1373 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001374
1375 // find and update the mobile NetworkPolicy for this subscriber id
1376 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001377 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001378 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1379 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1380 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001381 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1382 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001383 }
1384 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001385 return policyUpdated;
1386 }
1387
1388 /**
1389 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1390 *
1391 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1392 * to do so, it returns the fallback value.
1393 *
1394 * @param config The CarrierConfig to read the value from.
1395 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1396 * @return cycleDay to use in the mobile NetworkPolicy.
1397 */
1398 @VisibleForTesting
1399 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1400 int fallbackCycleDay) {
1401 if (config == null) {
1402 return fallbackCycleDay;
1403 }
1404 int cycleDay =
1405 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1406 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1407 return fallbackCycleDay;
1408 }
1409 // validate cycleDay value
1410 final Calendar cal = Calendar.getInstance();
1411 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1412 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1413 Slog.e(TAG, "Invalid date in "
1414 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1415 return fallbackCycleDay;
1416 }
1417 return cycleDay;
1418 }
1419
1420 /**
1421 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1422 *
1423 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1424 * to do so, it returns the fallback value.
1425 *
1426 * @param config The CarrierConfig to read the value from.
1427 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1428 * @return warningBytes to use in the mobile NetworkPolicy.
1429 */
1430 @VisibleForTesting
1431 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1432 long fallbackWarningBytes) {
1433 if (config == null) {
1434 return fallbackWarningBytes;
1435 }
1436 long warningBytes =
1437 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1438
1439 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1440 return WARNING_DISABLED;
1441 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1442 return getPlatformDefaultWarningBytes();
1443 } else if (warningBytes < 0) {
1444 Slog.e(TAG, "Invalid value in "
1445 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1446 + "non-negative value but got: " + warningBytes);
1447 return fallbackWarningBytes;
1448 }
1449
1450 return warningBytes;
1451 }
1452
1453 /**
1454 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1455 *
1456 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1457 * to do so, it returns the fallback value.
1458 *
1459 * @param config The CarrierConfig to read the value from.
1460 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1461 * @return limitBytes to use in the mobile NetworkPolicy.
1462 */
1463 @VisibleForTesting
1464 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1465 long fallbackLimitBytes) {
1466 if (config == null) {
1467 return fallbackLimitBytes;
1468 }
1469 long limitBytes =
1470 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1471
1472 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1473 return LIMIT_DISABLED;
1474 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1475 return getPlatformDefaultLimitBytes();
1476 } else if (limitBytes < 0) {
1477 Slog.e(TAG, "Invalid value in "
1478 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1479 + "non-negative value but got: " + limitBytes);
1480 return fallbackLimitBytes;
1481 }
1482 return limitBytes;
1483 }
1484
1485 /**
1486 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1487 */
1488 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1489 @Override
1490 public void onReceive(Context context, Intent intent) {
1491 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1492 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1493
1494 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1495 return;
1496 }
1497 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001498 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001499 final String subscriberId = tele.getSubscriberId(subId);
1500
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001501 synchronized (mUidRulesFirstLock) {
1502 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001503 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001504 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001505 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001506 if (!updated) return;
1507 // update network and notification rules, as the data cycle changed and it's
1508 // possible that we should be triggering warnings/limits now
1509 handleNetworkPoliciesUpdateAL(true);
1510 }
1511 }
1512 }
1513 };
1514
1515 /**
1516 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1517 * one has been updated.
1518 *
1519 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1520 * update.
1521 */
1522 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1523 if (shouldNormalizePolicies) {
1524 normalizePoliciesNL();
1525 }
1526 updateNetworkEnabledNL();
1527 updateNetworkRulesNL();
1528 updateNotificationsNL();
1529 writePolicyAL();
1530 }
1531
1532 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001533 * Proactively control network data connections when they exceed
1534 * {@link NetworkPolicy#limitBytes}.
1535 */
Felipe Lemef0823852016-06-08 13:43:08 -07001536 void updateNetworkEnabledNL() {
1537 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001538
1539 // TODO: reset any policy-disabled networks when any policy is removed
1540 // completely, which is currently rare case.
1541
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001542 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1543 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001544 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001545 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001546 setNetworkTemplateEnabled(policy.template, true);
1547 continue;
1548 }
1549
Jeff Sharkey53313d72017-07-13 16:47:32 -06001550 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1551 .cycleIterator(policy).next();
1552 final long start = cycle.first.toInstant().toEpochMilli();
1553 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001554 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001555
1556 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001557 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1558 && policy.lastLimitSnooze < start;
1559 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001560
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001561 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001562 }
1563 }
1564
1565 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001566 * Proactively disable networks that match the given
1567 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001568 */
1569 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001570 // TODO: reach into ConnectivityManager to proactively disable bringing
1571 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001572
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001573 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001574 // If mobile data usage hits the limit or if the user resumes the data, we need to
1575 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001576 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1577 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001578
Jeff Sharkey2e471452018-01-19 18:02:47 +09001579 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001580 for (int subId : subIds) {
1581 final String subscriberId = tm.getSubscriberId(subId);
1582 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001583 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1584 true);
Jack Yu8781b682016-07-08 14:28:51 -07001585 // Template is matched when subscriber id matches.
1586 if (template.matches(probeIdent)) {
1587 tm.setPolicyDataEnabled(enabled, subId);
1588 }
1589 }
1590 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001591 }
1592
1593 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001594 * Collect all ifaces from a {@link NetworkState} into the given set.
1595 */
1596 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1597 final String baseIface = state.linkProperties.getInterfaceName();
1598 if (baseIface != null) {
1599 ifaces.add(baseIface);
1600 }
1601 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1602 final String stackedIface = stackedLink.getInterfaceName();
1603 if (stackedIface != null) {
1604 ifaces.add(stackedIface);
1605 }
1606 }
1607 }
1608
1609 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 * Examine all connected {@link NetworkState}, looking for
1611 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1612 * remaining quota based on usage cycle and historical stats.
1613 */
Felipe Lemef0823852016-06-08 13:43:08 -07001614 void updateNetworkRulesNL() {
1615 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001616
1617 final NetworkState[] states;
1618 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001619 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001621 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001622 return;
1623 }
1624
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001625 // First, generate identities of all connected networks so we can
1626 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001627 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001628 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001629 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001630 if (state.network != null) {
1631 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1632 }
Wei Liub8eaf452016-01-25 10:32:27 -08001633 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001634 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1635 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001636 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001637 }
1638 }
1639
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001640 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001641 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001642
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001643 // For every well-defined policy, compute remaining data based on
1644 // current cycle and historical stats, and push to kernel.
1645 final ArraySet<String> matchingIfaces = new ArraySet<>();
1646 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1647 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1648
1649 // Collect all ifaces that match this policy
1650 matchingIfaces.clear();
1651 for (int j = identified.size() - 1; j >= 0; j--) {
1652 if (policy.template.matches(identified.valueAt(j))) {
1653 collectIfaces(matchingIfaces, identified.keyAt(j));
1654 }
1655 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001657 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001658 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001659 }
1660
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001661 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001662 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001663 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001664 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001665 if (hasLimit && policy.hasCycle()) {
1666 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1667 .cycleIterator(policy).next();
1668 final long start = cycle.first.toInstant().toEpochMilli();
1669 final long end = cycle.second.toInstant().toEpochMilli();
1670 final long totalBytes = getTotalBytes(policy.template, start, end);
1671
1672 if (policy.lastLimitSnooze >= start) {
1673 // snoozing past quota, but we still need to restrict apps,
1674 // so push really high quota.
1675 quotaBytes = Long.MAX_VALUE;
1676 } else {
1677 // remaining "quota" bytes are based on total usage in
1678 // current cycle. kernel doesn't like 0-byte rules, so we
1679 // set 1-byte quota and disable the radio later.
1680 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1681 }
1682 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001683 // metered network, but no policy limit; we still need to
1684 // restrict apps, so push really high quota.
1685 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001686 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001687
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001688 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001689 // TODO: switch to shared quota once NMS supports
1690 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001691 }
1692
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001693 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1694 final String iface = matchingIfaces.valueAt(j);
1695 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001696 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001697 }
1698 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001699
1700 // keep track of lowest warning or limit of active policies
1701 if (hasWarning && policy.warningBytes < lowestRule) {
1702 lowestRule = policy.warningBytes;
1703 }
1704 if (hasLimit && policy.limitBytes < lowestRule) {
1705 lowestRule = policy.limitBytes;
1706 }
1707 }
1708
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001709 // One final pass to catch any metered ifaces that don't have explicitly
1710 // defined policies; typically Wi-Fi networks.
1711 for (NetworkState state : states) {
1712 if (state.networkInfo != null && state.networkInfo.isConnected()
1713 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1714 matchingIfaces.clear();
1715 collectIfaces(matchingIfaces, state);
1716 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1717 final String iface = matchingIfaces.valueAt(j);
1718 if (!newMeteredIfaces.contains(iface)) {
1719 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1720 newMeteredIfaces.add(iface);
1721 }
1722 }
1723 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001724 }
1725
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001726 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001727 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1728 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001729 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001730 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001731 }
1732 }
1733 mMeteredIfaces = newMeteredIfaces;
1734
Jeff Sharkey9252b342018-01-19 07:58:35 +09001735 // Finally, calculate our opportunistic quotas
1736 // TODO: add experiments support to disable or tweak ratios
1737 mSubscriptionOpportunisticQuota.clear();
1738 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001739 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001740 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001741 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001742 if (plan == null) continue;
1743
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001744 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001745 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001746 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001747 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001748 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001749 // Unlimited data; let's use 20MiB/day (600MiB/month)
1750 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1751 } else {
1752 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001753 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1754 final long start = cycle.getLower().toInstant().toEpochMilli();
1755 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001756 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001757 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001758 .truncatedTo(ChronoUnit.DAYS)
1759 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001760 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001761 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1762 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001763 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001764 // Number of remaining days including current day
1765 final long remainingDays =
1766 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001767
1768 quotaBytes = Math.max(0, (remainingBytes / remainingDays) / 10);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001769 }
1770
1771 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1772 }
1773
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001774 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001775 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001776
1777 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001778 }
1779
1780 /**
1781 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1782 * have at least a default mobile policy defined.
1783 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001784 private void ensureActiveMobilePolicyAL() {
1785 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001786 if (mSuppressDefaultPolicy) return;
1787
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001788 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1789 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001790
Jeff Sharkey2e471452018-01-19 18:02:47 +09001791 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001792 for (int subId : subIds) {
1793 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001794 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001795 }
1796 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001797
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001798 /**
1799 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1800 * have at least a default mobile policy defined.
1801 *
1802 * @param subId to build a default policy for
1803 * @param subscriberId that we check for an existing policy
1804 * @return true if a mobile network policy was added, or false one already existed.
1805 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001806 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001807 // Poke around to see if we already have a policy
1808 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001809 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001810 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1811 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1812 if (template.matches(probeIdent)) {
1813 if (LOGD) {
1814 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1815 + NetworkIdentity.scrubSubscriberId(subscriberId));
1816 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001817 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001818 }
1819 }
1820
Jeff Sharkey32566012014-12-02 18:30:14 -08001821 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1822 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001823 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001824 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001825 return true;
1826 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001827
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001828 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001829 final int dataWarningConfig = mContext.getResources().getInteger(
1830 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001831 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001832 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001833 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001834 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001835 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001836 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001837
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001838 private long getPlatformDefaultLimitBytes() {
1839 return LIMIT_DISABLED;
1840 }
1841
1842 @VisibleForTesting
1843 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001844 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001845 final RecurrenceRule cycleRule = NetworkPolicy
1846 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001847 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001848 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1849 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1850 synchronized (mUidRulesFirstLock) {
1851 synchronized (mNetworkPoliciesSecondLock) {
1852 updateDefaultMobilePolicyAL(subId, policy);
1853 }
1854 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001855 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001856 }
1857
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001858 /**
1859 * Update the given {@link NetworkPolicy} based on any carrier-provided
1860 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1861 * Leaves policy untouched if the user has modified it.
1862 *
1863 * @return if the policy was modified
1864 */
1865 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1866 if (!policy.inferred) {
1867 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1868 return false;
1869 }
1870
1871 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1872 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1873 policy.lastLimitSnooze, policy.metered, policy.inferred);
1874
1875 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1876 if (!ArrayUtils.isEmpty(plans)) {
1877 final SubscriptionPlan plan = plans[0];
1878 policy.cycleRule = plan.getCycleRule();
1879 final long planLimitBytes = plan.getDataLimitBytes();
1880 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1881 policy.warningBytes = getPlatformDefaultWarningBytes();
1882 policy.limitBytes = getPlatformDefaultLimitBytes();
1883 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1884 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1885 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1886 } else {
1887 policy.warningBytes = (planLimitBytes * 9) / 10;
1888 switch (plan.getDataLimitBehavior()) {
1889 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1890 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1891 policy.limitBytes = planLimitBytes;
1892 break;
1893 default:
1894 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1895 break;
1896 }
1897 }
1898 } else {
1899 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1900 final int currentCycleDay;
1901 if (policy.cycleRule.isMonthly()) {
1902 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1903 } else {
1904 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1905 }
1906 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1907 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1908 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1909 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1910 }
1911
1912 if (policy.equals(original)) {
1913 return false;
1914 } else {
1915 Slog.d(TAG, "Updated " + original + " to " + policy);
1916 return true;
1917 }
1918 }
1919
Felipe Lemef0823852016-06-08 13:43:08 -07001920 private void readPolicyAL() {
1921 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001922
1923 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001924 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001925 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001926 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001927 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001928
1929 FileInputStream fis = null;
1930 try {
1931 fis = mPolicyFile.openRead();
1932 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001933 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001934
Felipe Leme46b451f2016-08-19 08:46:17 -07001935 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1936 // to skip UIDs that were explicitly blacklisted.
1937 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1938
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001940 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001941 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001942 while ((type = in.next()) != END_DOCUMENT) {
1943 final String tag = in.getName();
1944 if (type == START_TAG) {
1945 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001946 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001947 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001948 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1949 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001950 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1951 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1952 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001953 final String networkId;
1954 if (version >= VERSION_ADDED_NETWORK_ID) {
1955 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1956 } else {
1957 networkId = null;
1958 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001959 final RecurrenceRule cycleRule;
1960 if (version >= VERSION_ADDED_CYCLE) {
1961 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1962 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1963 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1964 cycleRule = new RecurrenceRule(
1965 RecurrenceRule.convertZonedDateTime(start),
1966 RecurrenceRule.convertZonedDateTime(end),
1967 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001968 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001969 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1970 final String cycleTimezone;
1971 if (version >= VERSION_ADDED_TIMEZONE) {
1972 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1973 } else {
1974 cycleTimezone = "UTC";
1975 }
1976 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001977 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001978 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1979 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001980 final long lastLimitSnooze;
1981 if (version >= VERSION_SPLIT_SNOOZE) {
1982 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1983 } else if (version >= VERSION_ADDED_SNOOZE) {
1984 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001985 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001986 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001987 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001988 final boolean metered;
1989 if (version >= VERSION_ADDED_METERED) {
1990 metered = readBooleanAttribute(in, ATTR_METERED);
1991 } else {
1992 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001993 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001994 metered = true;
1995 break;
1996 default:
1997 metered = false;
1998 }
1999 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002000 final long lastWarningSnooze;
2001 if (version >= VERSION_SPLIT_SNOOZE) {
2002 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2003 } else {
2004 lastWarningSnooze = SNOOZE_NEVER;
2005 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002006 final boolean inferred;
2007 if (version >= VERSION_ADDED_INFERRED) {
2008 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2009 } else {
2010 inferred = false;
2011 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002012
Jeff Sharkey32566012014-12-02 18:30:14 -08002013 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2014 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002015 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002016 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2017 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002018 lastLimitSnooze, metered, inferred));
2019 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002020
2021 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2022 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2023 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2024 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2025 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2026 RecurrenceRule.convertZonedDateTime(start),
2027 RecurrenceRule.convertZonedDateTime(end),
2028 RecurrenceRule.convertPeriod(period));
2029 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2030 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2031
2032 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2033 SubscriptionPlan.BYTES_UNKNOWN);
2034 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2035 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2036 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2037 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2038 builder.setDataLimit(limitBytes, limitBehavior);
2039 }
2040
2041 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2042 SubscriptionPlan.BYTES_UNKNOWN);
2043 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2044 SubscriptionPlan.TIME_UNKNOWN);
2045 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2046 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2047 builder.setDataUsage(usageBytes, usageTime);
2048 }
2049
2050 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2051 final SubscriptionPlan plan = builder.build();
2052 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2053 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2054
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002055 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2056 mSubscriptionPlansOwner.put(subId, ownerPackage);
2057
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002058 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002059 final int uid = readIntAttribute(in, ATTR_UID);
2060 final int policy = readIntAttribute(in, ATTR_POLICY);
2061
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002062 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002063 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002064 } else {
2065 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2066 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002067 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002068 final int appId = readIntAttribute(in, ATTR_APP_ID);
2069 final int policy = readIntAttribute(in, ATTR_POLICY);
2070
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002071 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002072 // app policy is deprecated so this is only used in pre system user split.
2073 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002074 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002075 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002076 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002077 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002078 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002079 } else if (TAG_WHITELIST.equals(tag)) {
2080 insideWhitelist = true;
2081 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2082 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002083 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002084 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2085 final int uid = readIntAttribute(in, ATTR_UID);
2086 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002087 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002088 } else if (type == END_TAG) {
2089 if (TAG_WHITELIST.equals(tag)) {
2090 insideWhitelist = false;
2091 }
2092
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002093 }
2094 }
2095
Felipe Leme46b451f2016-08-19 08:46:17 -07002096 final int size = whitelistedRestrictBackground.size();
2097 for (int i = 0; i < size; i++) {
2098 final int uid = whitelistedRestrictBackground.keyAt(i);
2099 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2100 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2101 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2102 + " because its policy is " + uidPoliciesToString(policy));
2103 continue;
2104 }
2105 if (UserHandle.isApp(uid)) {
2106 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2107 if (LOGV)
2108 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2109 setUidPolicyUncheckedUL(uid, newPolicy, false);
2110 } else {
2111 Slog.w(TAG, "unable to update policy on UID " + uid);
2112 }
2113 }
2114
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002115 } catch (FileNotFoundException e) {
2116 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002117 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002118 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002119 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002120 } finally {
2121 IoUtils.closeQuietly(fis);
2122 }
2123 }
2124
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002125 /**
2126 * Upgrade legacy background data flags, notifying listeners of one last
2127 * change to always-true.
2128 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002129 private void upgradeDefaultBackgroundDataUL() {
2130 // This method is only called when we're unable to find the network policy flag, which
2131 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002132
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002133 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002134 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002135 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2136
2137 // NOTE: We used to read the legacy setting here :
2138 //
2139 // final int legacyFlagValue = Settings.Secure.getInt(
2140 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2141 //
2142 // This is no longer necessary because we will never upgrade directly from Gingerbread
2143 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2144 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002145 }
2146
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002147 /**
2148 * Perform upgrade step of moving any user-defined meterness overrides over
2149 * into {@link WifiConfiguration}.
2150 */
2151 private void upgradeWifiMeteredOverrideAL() {
2152 boolean modified = false;
2153 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2154 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2155 for (int i = 0; i < mNetworkPolicy.size(); ) {
2156 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2157 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2158 && !policy.inferred) {
2159 mNetworkPolicy.removeAt(i);
2160 modified = true;
2161
2162 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2163 for (WifiConfiguration config : configs) {
2164 if (Objects.equals(resolveNetworkId(config), networkId)) {
2165 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2166 config.meteredOverride = policy.metered
2167 ? WifiConfiguration.METERED_OVERRIDE_METERED
2168 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2169 wm.updateNetwork(config);
2170 }
2171 }
2172 } else {
2173 i++;
2174 }
2175 }
2176 if (modified) {
2177 writePolicyAL();
2178 }
2179 }
2180
Felipe Lemef0823852016-06-08 13:43:08 -07002181 void writePolicyAL() {
2182 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002183
2184 FileOutputStream fos = null;
2185 try {
2186 fos = mPolicyFile.startWrite();
2187
2188 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002189 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002190 out.startDocument(null, true);
2191
2192 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002193 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002194 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002195
2196 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002197 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2198 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002199 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002200 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002201
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002202 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002203 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2204 final String subscriberId = template.getSubscriberId();
2205 if (subscriberId != null) {
2206 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002207 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002208 final String networkId = template.getNetworkId();
2209 if (networkId != null) {
2210 out.attribute(null, ATTR_NETWORK_ID, networkId);
2211 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002212 writeStringAttribute(out, ATTR_CYCLE_START,
2213 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2214 writeStringAttribute(out, ATTR_CYCLE_END,
2215 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2216 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2217 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002218 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2219 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002220 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2221 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002222 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002223 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002224 out.endTag(null, TAG_NETWORK_POLICY);
2225 }
2226
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002227 // write all known subscription plans
2228 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2229 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002230 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002231 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2232 if (ArrayUtils.isEmpty(plans)) continue;
2233
2234 for (SubscriptionPlan plan : plans) {
2235 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2236 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002237 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002238 final RecurrenceRule cycleRule = plan.getCycleRule();
2239 writeStringAttribute(out, ATTR_CYCLE_START,
2240 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2241 writeStringAttribute(out, ATTR_CYCLE_END,
2242 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2243 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2244 RecurrenceRule.convertPeriod(cycleRule.period));
2245 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2246 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2247 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2248 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2249 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2250 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2251 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2252 }
2253 }
2254
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002255 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 for (int i = 0; i < mUidPolicy.size(); i++) {
2257 final int uid = mUidPolicy.keyAt(i);
2258 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002259
Jeff Sharkey497e4432011-06-14 17:27:29 -07002260 // skip writing empty policies
2261 if (policy == POLICY_NONE) continue;
2262
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002263 out.startTag(null, TAG_UID_POLICY);
2264 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002265 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002267 }
2268
2269 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002270
2271 // write all whitelists
2272 out.startTag(null, TAG_WHITELIST);
2273
Felipe Lemea9505cc2016-02-26 10:28:41 -08002274 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002275 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002276 for (int i = 0; i < size; i++) {
2277 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2278 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2279 writeIntAttribute(out, ATTR_UID, uid);
2280 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2281 }
2282
Felipe Lemeb85a6372016-01-14 16:16:16 -08002283 out.endTag(null, TAG_WHITELIST);
2284
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002285 out.endDocument();
2286
2287 mPolicyFile.finishWrite(fos);
2288 } catch (IOException e) {
2289 if (fos != null) {
2290 mPolicyFile.failWrite(fos);
2291 }
2292 }
2293 }
2294
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002295 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002296 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002297 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002298
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002299 if (!UserHandle.isApp(uid)) {
2300 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002301 }
Felipe Lemef0823852016-06-08 13:43:08 -07002302 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002303 final long token = Binder.clearCallingIdentity();
2304 try {
2305 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2306 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002307 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002308 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002309 }
2310 } finally {
2311 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002312 }
2313 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002314 }
2315
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002316 @Override
2317 public void addUidPolicy(int uid, int policy) {
2318 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002319
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002320 if (!UserHandle.isApp(uid)) {
2321 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2322 }
2323
Felipe Lemef0823852016-06-08 13:43:08 -07002324 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002325 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2326 policy |= oldPolicy;
2327 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002328 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002329 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002330 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002331 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002332 }
2333
2334 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002335 public void removeUidPolicy(int uid, int policy) {
2336 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2337
2338 if (!UserHandle.isApp(uid)) {
2339 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2340 }
2341
Felipe Lemef0823852016-06-08 13:43:08 -07002342 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002343 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2344 policy = oldPolicy & ~policy;
2345 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002346 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002347 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002348 }
2349 }
2350 }
2351
Felipe Lemef0823852016-06-08 13:43:08 -07002352 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002353 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002354
Felipe Leme57e3d312016-08-23 14:42:52 -07002355 final boolean notifyApp;
2356 if (!isUidValidForWhitelistRules(uid)) {
2357 notifyApp = false;
2358 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002359 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2360 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2361 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2362 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002363 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2364 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002365 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2366 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2367 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2368 if (LOGD)
2369 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2370 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2371 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002372 notifyApp = wasBlocked != isBlocked;
2373 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002374 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2375 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002376 if (persist) {
2377 synchronized (mNetworkPoliciesSecondLock) {
2378 writePolicyAL();
2379 }
2380 }
Felipe Leme923845f2016-03-02 13:42:48 -08002381 }
2382
Felipe Lemef0823852016-06-08 13:43:08 -07002383 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002384 if (policy == POLICY_NONE) {
2385 mUidPolicy.delete(uid);
2386 } else {
2387 mUidPolicy.put(uid, policy);
2388 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002389
2390 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002391 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002392 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002393 synchronized (mNetworkPoliciesSecondLock) {
2394 writePolicyAL();
2395 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002396 }
2397 }
2398
2399 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002400 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002401 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2402
Felipe Lemef0823852016-06-08 13:43:08 -07002403 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002404 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002405 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002406 }
2407
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002408 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002409 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002410 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2411
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002412 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002413 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002414 for (int i = 0; i < mUidPolicy.size(); i++) {
2415 final int uid = mUidPolicy.keyAt(i);
2416 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002417 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2418 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002419 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002420 }
2421 }
2422 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002423 return uids;
2424 }
2425
2426 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002427 * Removes any persistable state associated with given {@link UserHandle}, persisting
2428 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002429 */
Felipe Lemef0823852016-06-08 13:43:08 -07002430 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002431
Sudheer Shanka352dc572017-09-22 17:09:38 -07002432 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002433 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002434
Felipe Lemea110eec2016-04-29 09:58:06 -07002435 // Remove entries from revoked default restricted background UID whitelist
2436 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2437 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2438 if (UserHandle.getUserId(uid) == userId) {
2439 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002440 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002441 }
2442 }
2443
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002444 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002445 int[] uids = new int[0];
2446 for (int i = 0; i < mUidPolicy.size(); i++) {
2447 final int uid = mUidPolicy.keyAt(i);
2448 if (UserHandle.getUserId(uid) == userId) {
2449 uids = appendInt(uids, uid);
2450 }
2451 }
2452
2453 if (uids.length > 0) {
2454 for (int uid : uids) {
2455 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002456 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002457 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002458 }
Felipe Lemef0823852016-06-08 13:43:08 -07002459 synchronized (mNetworkPoliciesSecondLock) {
2460 updateRulesForGlobalChangeAL(true);
2461 if (writePolicy && changed) {
2462 writePolicyAL();
2463 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002464 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002465 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002466 }
2467
2468 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002469 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002470 // TODO: create permission for observing network policy
2471 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002472 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002473 }
2474
2475 @Override
2476 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002477 // TODO: create permission for observing network policy
2478 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002479 mListeners.unregister(listener);
2480 }
2481
Jeff Sharkey1b861272011-05-22 00:34:52 -07002482 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002483 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002484 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2485
Felipe Leme6a05eee2016-02-19 14:43:51 -08002486 final long token = Binder.clearCallingIdentity();
2487 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002488 synchronized (mUidRulesFirstLock) {
2489 synchronized (mNetworkPoliciesSecondLock) {
2490 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002491 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002492 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002493 }
2494 } finally {
2495 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002496 }
2497 }
2498
Hugo Benichi446c9c92017-04-10 09:41:10 +09002499 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002500 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002501 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2502 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002503 }
2504
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002505 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002506 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002508 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002509 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2510 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2511 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002512 } catch (SecurityException e) {
2513 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002514
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002515 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2516 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2517 return new NetworkPolicy[0];
2518 }
Svet Ganov16a16892015-04-16 10:32:04 -07002519 }
2520
Felipe Lemef0823852016-06-08 13:43:08 -07002521 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002522 final int size = mNetworkPolicy.size();
2523 final NetworkPolicy[] policies = new NetworkPolicy[size];
2524 for (int i = 0; i < size; i++) {
2525 policies[i] = mNetworkPolicy.valueAt(i);
2526 }
2527 return policies;
2528 }
2529 }
2530
Felipe Lemef0823852016-06-08 13:43:08 -07002531 private void normalizePoliciesNL() {
2532 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002533 }
2534
Felipe Lemef0823852016-06-08 13:43:08 -07002535 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002536 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002537 final String[] merged = tele.getMergedSubscriberIds();
2538
2539 mNetworkPolicy.clear();
2540 for (NetworkPolicy policy : policies) {
2541 // When two normalized templates conflict, prefer the most
2542 // restrictive policy
2543 policy.template = NetworkTemplate.normalize(policy.template, merged);
2544 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2545 if (existing == null || existing.compareTo(policy) > 0) {
2546 if (existing != null) {
2547 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2548 }
2549 mNetworkPolicy.put(policy.template, policy);
2550 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002551 }
2552 }
2553
2554 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002555 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002556 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002557
2558 final long token = Binder.clearCallingIdentity();
2559 try {
2560 performSnooze(template, TYPE_LIMIT);
2561 } finally {
2562 Binder.restoreCallingIdentity(token);
2563 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002564 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002565
Dianne Hackborn497175b2014-07-01 12:56:08 -07002566 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002567 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002568 synchronized (mUidRulesFirstLock) {
2569 synchronized (mNetworkPoliciesSecondLock) {
2570 // find and snooze local policy that matches
2571 final NetworkPolicy policy = mNetworkPolicy.get(template);
2572 if (policy == null) {
2573 throw new IllegalArgumentException("unable to find policy for " + template);
2574 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002575
Felipe Lemef0823852016-06-08 13:43:08 -07002576 switch (type) {
2577 case TYPE_WARNING:
2578 policy.lastWarningSnooze = currentTime;
2579 break;
2580 case TYPE_LIMIT:
2581 policy.lastLimitSnooze = currentTime;
2582 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002583 case TYPE_RAPID:
2584 policy.lastRapidSnooze = currentTime;
2585 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002586 default:
2587 throw new IllegalArgumentException("unexpected type");
2588 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002589
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002590 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002591 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002592 }
2593 }
2594
2595 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002596 public void onTetheringChanged(String iface, boolean tethering) {
2597 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002598 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002599 if (mRestrictBackground && tethering) {
2600 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2601 setRestrictBackground(false);
2602 }
2603 }
2604 }
2605
2606 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002607 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002608 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002609 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002610 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2611 final long token = Binder.clearCallingIdentity();
2612 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002613 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002614 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002615 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002616 } finally {
2617 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002618 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002619 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002620 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002621 }
2622 }
2623
Felipe Lemef0823852016-06-08 13:43:08 -07002624 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002625 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002626 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002627 if (restrictBackground == mRestrictBackground) {
2628 // Ideally, UI should never allow this scenario...
2629 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002630 return;
2631 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002632 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2633 final boolean oldRestrictBackground = mRestrictBackground;
2634 mRestrictBackground = restrictBackground;
2635 // Must whitelist foreground apps before turning data saver mode on.
2636 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2637 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2638 updateRulesForRestrictBackgroundUL();
2639 try {
2640 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2641 Slog.e(TAG,
2642 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2643 mRestrictBackground = oldRestrictBackground;
2644 // TODO: if it knew the foreground apps (see TODO above), it could call
2645 // updateRulesForRestrictBackgroundUL() again to restore state.
2646 return;
2647 }
2648 } catch (RemoteException e) {
2649 // ignored; service lives in system_server
2650 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002651
Sudheer Shanka543339f2017-07-28 15:18:07 -07002652 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002653 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002654
2655 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2656 mRestrictBackgroundChangedInBsm = true;
2657 }
2658 synchronized (mNetworkPoliciesSecondLock) {
2659 updateNotificationsNL();
2660 writePolicyAL();
2661 }
2662 } finally {
2663 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002664 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002665 }
2666
2667 private void sendRestrictBackgroundChangedMsg() {
2668 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2669 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2670 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002671 }
2672
Felipe Lemeb85a6372016-01-14 16:16:16 -08002673 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002674 public int getRestrictBackgroundByCaller() {
2675 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2676 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002677
Felipe Lemef0823852016-06-08 13:43:08 -07002678 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002679 // Must clear identity because getUidPolicy() is restricted to system.
2680 final long token = Binder.clearCallingIdentity();
2681 final int policy;
2682 try {
2683 policy = getUidPolicy(uid);
2684 } finally {
2685 Binder.restoreCallingIdentity(token);
2686 }
2687 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2688 // App is blacklisted.
2689 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2690 }
Felipe Leme1b103232016-01-22 09:44:57 -08002691 if (!mRestrictBackground) {
2692 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2693 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002694 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002695 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2696 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2697 }
2698 }
2699
2700 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002701 public boolean getRestrictBackground() {
2702 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2703
Felipe Lemef0823852016-06-08 13:43:08 -07002704 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002705 return mRestrictBackground;
2706 }
2707 }
2708
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002709 @Override
2710 public void setDeviceIdleMode(boolean enabled) {
2711 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002712 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2713 try {
2714 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002715 if (mDeviceIdleMode == enabled) {
2716 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002717 }
Felipe Lemeea014392016-09-06 13:59:54 -07002718 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002719 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002720 if (mSystemReady) {
2721 // Device idle change means we need to rebuild rules for all
2722 // known apps, so do a global refresh.
2723 updateRulesForRestrictPowerUL();
2724 }
2725 }
2726 if (enabled) {
2727 EventLogTags.writeDeviceIdleOnPhase("net");
2728 } else {
2729 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002730 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002731 } finally {
2732 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002733 }
2734 }
2735
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002736 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002737 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2738 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002739 final long token = Binder.clearCallingIdentity();
2740 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002741 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2742 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2743 for (WifiConfiguration config : configs) {
2744 if (Objects.equals(resolveNetworkId(config), networkId)) {
2745 config.meteredOverride = meteredOverride;
2746 wm.updateNetwork(config);
2747 }
2748 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002749 } finally {
2750 Binder.restoreCallingIdentity(token);
2751 }
2752 }
2753
Jeff Sharkey46645002011-07-27 21:11:21 -07002754 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002755 @Deprecated
2756 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2757 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2758 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2759 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002760 }
2761
Jeff Sharkey53313d72017-07-13 16:47:32 -06002762 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2763 // Verify they're not lying about package name
2764 mAppOps.checkPackage(callingUid, callingPackage);
2765
Jeff Sharkey53313d72017-07-13 16:47:32 -06002766 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002767 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002768 final long token = Binder.clearCallingIdentity();
2769 try {
2770 si = mContext.getSystemService(SubscriptionManager.class)
2771 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002772 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
2776
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002777 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002778 if (si != null) {
2779 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2780 return;
2781 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002782 }
2783
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002784 // Second check: has the CarrierService delegated access?
2785 if (config != null) {
2786 final String overridePackage = config
2787 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2788 if (!TextUtils.isEmpty(overridePackage)
2789 && Objects.equals(overridePackage, callingPackage)) {
2790 return;
2791 }
2792 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002793
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002794 // Third check: is caller the fallback/default CarrierService?
2795 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2796 if (!TextUtils.isEmpty(defaultPackage)
2797 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002798 return;
2799 }
2800
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002801 // Fourth check: is caller a testing app?
2802 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2803 if (!TextUtils.isEmpty(testPackage)
2804 && Objects.equals(testPackage, callingPackage)) {
2805 return;
2806 }
2807
2808 // Fifth check: is caller a legacy testing app?
2809 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2810 if (!TextUtils.isEmpty(legacyTestPackage)
2811 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002812 return;
2813 }
2814
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002815 // Final check: does the caller hold a permission?
2816 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002817 }
2818
2819 @Override
2820 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2821 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2822
Jeff Sharkey53313d72017-07-13 16:47:32 -06002823 final String fake = SystemProperties.get("fw.fake_plan");
2824 if (!TextUtils.isEmpty(fake)) {
2825 final List<SubscriptionPlan> plans = new ArrayList<>();
2826 if ("month_hard".equals(fake)) {
2827 plans.add(SubscriptionPlan.Builder
2828 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2829 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002830 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2831 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2832 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2833 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2834 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002835 plans.add(SubscriptionPlan.Builder
2836 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2837 .setTitle("G-Mobile Happy")
2838 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2839 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2840 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2841 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2842 .build());
2843 plans.add(SubscriptionPlan.Builder
2844 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2845 .setTitle("G-Mobile, Charged after limit")
2846 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2847 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2848 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2849 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2850 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002851 } else if ("month_soft".equals(fake)) {
2852 plans.add(SubscriptionPlan.Builder
2853 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2854 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2855 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2856 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002857 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2858 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2859 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2860 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2861 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002862 plans.add(SubscriptionPlan.Builder
2863 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2864 .setTitle("G-Mobile, Throttled after limit")
2865 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2866 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2867 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2868 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2869 .build());
2870 plans.add(SubscriptionPlan.Builder
2871 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2872 .setTitle("G-Mobile, No data connection after limit")
2873 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2874 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2875 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2876 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2877 .build());
2878
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002879 } else if ("month_over".equals(fake)) {
2880 plans.add(SubscriptionPlan.Builder
2881 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2882 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2883 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2884 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2885 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2886 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2887 .build());
2888 plans.add(SubscriptionPlan.Builder
2889 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2890 .setTitle("G-Mobile, Throttled after limit")
2891 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2892 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2893 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2894 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2895 .build());
2896 plans.add(SubscriptionPlan.Builder
2897 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2898 .setTitle("G-Mobile, No data connection after limit")
2899 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2900 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2901 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2902 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2903 .build());
2904
Jeff Sharkey53313d72017-07-13 16:47:32 -06002905 } else if ("month_none".equals(fake)) {
2906 plans.add(SubscriptionPlan.Builder
2907 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2908 .setTitle("G-Mobile")
2909 .build());
2910 } else if ("prepaid".equals(fake)) {
2911 plans.add(SubscriptionPlan.Builder
2912 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2913 ZonedDateTime.now().plusDays(10))
2914 .setTitle("G-Mobile")
2915 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2916 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2917 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2918 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2919 .build());
2920 } else if ("prepaid_crazy".equals(fake)) {
2921 plans.add(SubscriptionPlan.Builder
2922 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2923 ZonedDateTime.now().plusDays(10))
2924 .setTitle("G-Mobile Anytime")
2925 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2926 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2927 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2928 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2929 .build());
2930 plans.add(SubscriptionPlan.Builder
2931 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2932 ZonedDateTime.now().plusDays(20))
2933 .setTitle("G-Mobile Nickel Nights")
2934 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002935 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2936 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002937 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2938 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2939 .build());
2940 plans.add(SubscriptionPlan.Builder
2941 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2942 ZonedDateTime.now().plusDays(20))
2943 .setTitle("G-Mobile Bonus 3G")
2944 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002945 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002946 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2947 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2948 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2949 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002950 } else if ("unlimited".equals(fake)) {
2951 plans.add(SubscriptionPlan.Builder
2952 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2953 ZonedDateTime.now().plusDays(10))
2954 .setTitle("G-Mobile Awesome")
2955 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2956 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2957 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2958 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2959 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002960 }
2961 return plans.toArray(new SubscriptionPlan[plans.size()]);
2962 }
2963
Jeff Sharkey4635f102017-09-01 11:27:13 -06002964 synchronized (mNetworkPoliciesSecondLock) {
2965 // Only give out plan details to the package that defined them,
2966 // so that we don't risk leaking plans between apps. We always
2967 // let in core system components (like the Settings app).
2968 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2969 if (Objects.equals(ownerPackage, callingPackage)
2970 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2971 return mSubscriptionPlans.get(subId);
2972 } else {
2973 Log.w(TAG, "Not returning plans because caller " + callingPackage
2974 + " doesn't match owner " + ownerPackage);
2975 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002976 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002977 }
2978 }
2979
2980 @Override
2981 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2982 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2983
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002984 for (SubscriptionPlan plan : plans) {
2985 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002986 }
2987
2988 final long token = Binder.clearCallingIdentity();
2989 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002990 synchronized (mUidRulesFirstLock) {
2991 synchronized (mNetworkPoliciesSecondLock) {
2992 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002993 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002994
2995 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2996 .getSubscriberId(subId);
2997 ensureActiveMobilePolicyAL(subId, subscriberId);
2998 maybeUpdateMobilePolicyCycleAL(subId);
2999 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003000 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003001 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003002
3003 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3004 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3005 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3006 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003007 } finally {
3008 Binder.restoreCallingIdentity(token);
3009 }
3010 }
3011
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003012 /**
3013 * Only visible for testing purposes. This doesn't give any access to
3014 * existing plans; it simply lets the debug package define new plans.
3015 */
3016 void setSubscriptionPlansOwner(int subId, String packageName) {
3017 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3018 }
3019
Jeff Sharkey53313d72017-07-13 16:47:32 -06003020 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003021 public String getSubscriptionPlansOwner(int subId) {
3022 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3023 throw new SecurityException();
3024 }
3025
3026 synchronized (mNetworkPoliciesSecondLock) {
3027 return mSubscriptionPlansOwner.get(subId);
3028 }
3029 }
3030
3031 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003032 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3033 long timeoutMillis, String callingPackage) {
3034 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3035
3036 // We can only override when carrier told us about plans
3037 synchronized (mNetworkPoliciesSecondLock) {
3038 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3039 throw new IllegalStateException(
3040 "Must provide SubscriptionPlan information before overriding");
3041 }
3042 }
3043
3044 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3045 overrideMask, overrideValue, subId));
3046 if (timeoutMillis > 0) {
3047 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3048 overrideMask, 0, subId), timeoutMillis);
3049 }
3050 }
3051
3052 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003053 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003054 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003055
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003056 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3057
Dianne Hackborn497175b2014-07-01 12:56:08 -07003058 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003059 for (String arg : args) {
3060 argSet.add(arg);
3061 }
3062
Felipe Lemef0823852016-06-08 13:43:08 -07003063 synchronized (mUidRulesFirstLock) {
3064 synchronized (mNetworkPoliciesSecondLock) {
3065 if (argSet.contains("--unsnooze")) {
3066 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3067 mNetworkPolicy.valueAt(i).clearSnooze();
3068 }
3069
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003070 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003071
3072 fout.println("Cleared snooze timestamps");
3073 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003074 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003075
Felipe Lemef0823852016-06-08 13:43:08 -07003076 fout.print("System ready: "); fout.println(mSystemReady);
3077 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3078 fout.print("Restrict power: "); fout.println(mRestrictPower);
3079 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003080 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3081
3082 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003083 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003084 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003085 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3086 fout.println(mNetworkPolicy.valueAt(i).toString());
3087 }
3088 fout.decreaseIndent();
3089
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003090 fout.println();
3091 fout.println("Subscription plans:");
3092 fout.increaseIndent();
3093 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3094 final int subId = mSubscriptionPlans.keyAt(i);
3095 fout.println("Subscriber ID " + subId + ":");
3096 fout.increaseIndent();
3097 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3098 if (!ArrayUtils.isEmpty(plans)) {
3099 for (SubscriptionPlan plan : plans) {
3100 fout.println(plan);
3101 }
3102 }
3103 fout.decreaseIndent();
3104 }
3105 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003106
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003107 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003108 fout.println("Policy for UIDs:");
3109 fout.increaseIndent();
3110 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003111 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003112 final int uid = mUidPolicy.keyAt(i);
3113 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003114 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003115 fout.print(uid);
3116 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003117 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003118 fout.println();
3119 }
3120 fout.decreaseIndent();
3121
3122 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3123 if (size > 0) {
3124 fout.println("Power save whitelist (except idle) app ids:");
3125 fout.increaseIndent();
3126 for (int i = 0; i < size; i++) {
3127 fout.print("UID=");
3128 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3129 fout.print(": ");
3130 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3131 fout.println();
3132 }
3133 fout.decreaseIndent();
3134 }
3135
3136 size = mPowerSaveWhitelistAppIds.size();
3137 if (size > 0) {
3138 fout.println("Power save whitelist app ids:");
3139 fout.increaseIndent();
3140 for (int i = 0; i < size; i++) {
3141 fout.print("UID=");
3142 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3143 fout.print(": ");
3144 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3145 fout.println();
3146 }
3147 fout.decreaseIndent();
3148 }
3149
Felipe Lemef0823852016-06-08 13:43:08 -07003150 size = mDefaultRestrictBackgroundWhitelistUids.size();
3151 if (size > 0) {
3152 fout.println("Default restrict background whitelist uids:");
3153 fout.increaseIndent();
3154 for (int i = 0; i < size; i++) {
3155 fout.print("UID=");
3156 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3157 fout.println();
3158 }
3159 fout.decreaseIndent();
3160 }
3161
3162 size = mRestrictBackgroundWhitelistRevokedUids.size();
3163 if (size > 0) {
3164 fout.println("Default restrict background whitelist uids revoked by users:");
3165 fout.increaseIndent();
3166 for (int i = 0; i < size; i++) {
3167 fout.print("UID=");
3168 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3169 fout.println();
3170 }
3171 fout.decreaseIndent();
3172 }
3173
3174 final SparseBooleanArray knownUids = new SparseBooleanArray();
3175 collectKeys(mUidState, knownUids);
3176 collectKeys(mUidRules, knownUids);
3177
3178 fout.println("Status for all known UIDs:");
3179 fout.increaseIndent();
3180 size = knownUids.size();
3181 for (int i = 0; i < size; i++) {
3182 final int uid = knownUids.keyAt(i);
3183 fout.print("UID=");
3184 fout.print(uid);
3185
3186 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3187 fout.print(" state=");
3188 fout.print(state);
3189 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3190 fout.print(" (fg)");
3191 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003192 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003193 ? " (fg svc)" : " (bg)");
3194 }
3195
3196 final int uidRules = mUidRules.get(uid, RULE_NONE);
3197 fout.print(" rules=");
3198 fout.print(uidRulesToString(uidRules));
3199 fout.println();
3200 }
3201 fout.decreaseIndent();
3202
3203 fout.println("Status for just UIDs with rules:");
3204 fout.increaseIndent();
3205 size = mUidRules.size();
3206 for (int i = 0; i < size; i++) {
3207 final int uid = mUidRules.keyAt(i);
3208 fout.print("UID=");
3209 fout.print(uid);
3210 final int uidRules = mUidRules.get(uid, RULE_NONE);
3211 fout.print(" rules=");
3212 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003213 fout.println();
3214 }
3215 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003216
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003217 fout.println("Admin restricted uids for metered data:");
3218 fout.increaseIndent();
3219 size = mMeteredRestrictedUids.size();
3220 for (int i = 0; i < size; ++i) {
3221 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3222 fout.println(mMeteredRestrictedUids.valueAt(i));
3223 }
3224 fout.decreaseIndent();
3225
Sudheer Shanka352dc572017-09-22 17:09:38 -07003226 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003227 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003228 }
3229 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003230
3231 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003232 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003233 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003234 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003235 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003236 }
3237
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003238 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003239 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003240 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003241 return isUidStateForeground(
3242 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003243 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003244 }
3245
Felipe Lemef0823852016-06-08 13:43:08 -07003246 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003247 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003248 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003249 }
3250
Felipe Lemef0823852016-06-08 13:43:08 -07003251 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003252 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3253 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3254 }
3255
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003256 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003257 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003258 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003259 }
3260
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003261 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003262 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003263 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3264 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003265 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003266 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003267 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3268 try {
3269 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3270 if (oldUidState != uidState) {
3271 // state changed, push updated rules
3272 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003273 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3274 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3275 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003276 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003277 if (mDeviceIdleMode) {
3278 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003279 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003280 if (mRestrictPower) {
3281 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003282 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003283 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003284 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003285 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003286 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003287 } finally {
3288 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003289 }
3290 }
3291
Felipe Lemef0823852016-06-08 13:43:08 -07003292 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003293 final int index = mUidState.indexOfKey(uid);
3294 if (index >= 0) {
3295 final int oldUidState = mUidState.valueAt(index);
3296 mUidState.removeAt(index);
3297 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003298 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003299 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003300 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003301 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003302 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003303 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003304 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003305 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003306 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003307 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003308 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003309 }
3310 }
3311
Felipe Lemef28983d2016-03-25 12:18:23 -07003312 // adjust stats accounting based on foreground status
3313 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003314 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3315 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3316 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3317 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003318 try {
3319 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003320 } finally {
3321 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003322 }
3323 }
3324
Sudheer Shankac9d94072017-02-22 22:13:55 +00003325 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3326 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003327 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003328 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003329 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003330 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003331 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003332 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003333 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003334 }
3335
Felipe Lemef0823852016-06-08 13:43:08 -07003336 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003337 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3338 try {
3339 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3340 mUidFirewallPowerSaveRules);
3341 } finally {
3342 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3343 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003344 }
3345
Felipe Lemef0823852016-06-08 13:43:08 -07003346 void updateRuleForRestrictPowerUL(int uid) {
3347 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003348 }
3349
Felipe Lemef0823852016-06-08 13:43:08 -07003350 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003351 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3352 try {
3353 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3354 mUidFirewallDozableRules);
3355 } finally {
3356 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3357 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003358 }
3359
Felipe Lemef0823852016-06-08 13:43:08 -07003360 void updateRuleForDeviceIdleUL(int uid) {
3361 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003362 }
3363
Felipe Lemef28983d2016-03-25 12:18:23 -07003364 // NOTE: since both fw_dozable and fw_powersave uses the same map
3365 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003366 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003367 SparseIntArray rules) {
3368 if (enabled) {
3369 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003370 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003371 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003372 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003373 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003374 for (int ui = users.size() - 1; ui >= 0; ui--) {
3375 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003376 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3377 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3378 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3379 updateRulesForWhitelistedAppIds(uidRules,
3380 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003381 }
3382 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003383 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003384 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003385 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3386 }
3387 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003388 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003389 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003390 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003391 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003392 }
3393
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003394 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3395 final SparseBooleanArray whitelistedAppIds, int userId) {
3396 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3397 if (whitelistedAppIds.valueAt(i)) {
3398 final int appId = whitelistedAppIds.keyAt(i);
3399 final int uid = UserHandle.getUid(userId, appId);
3400 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3401 }
3402 }
3403 }
3404
3405 /**
3406 * @param deviceIdleMode if true then we don't consider
3407 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3408 * whitelisted.
3409 */
3410 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003411 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003412 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3413 || mPowerSaveWhitelistAppIds.get(appId);
3414 if (!deviceIdleMode) {
3415 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3416 }
3417 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003418 }
3419
Felipe Lemef28983d2016-03-25 12:18:23 -07003420 // NOTE: since both fw_dozable and fw_powersave uses the same map
3421 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003422 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003423 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003424 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3425 chain == FIREWALL_CHAIN_DOZABLE);
3426 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003427 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003428 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003429 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003430 }
3431 }
3432 }
3433
Felipe Lemef0823852016-06-08 13:43:08 -07003434 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003435 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3436 try {
3437 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3438 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003439
Felipe Leme873a83a2016-09-07 11:34:10 -07003440 // Fully update the app idle firewall chain.
3441 final List<UserInfo> users = mUserManager.getUsers();
3442 for (int ui = users.size() - 1; ui >= 0; ui--) {
3443 UserInfo user = users.get(ui);
3444 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3445 for (int uid : idleUids) {
3446 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3447 // quick check: if this uid doesn't have INTERNET permission, it
3448 // doesn't have network access anyway, so it is a waste to mess
3449 // with it here.
3450 if (hasInternetPermissions(uid)) {
3451 uidRules.put(uid, FIREWALL_RULE_DENY);
3452 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003453 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003454 }
3455 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003456
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003457 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003458 } finally {
3459 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3460 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003461 }
3462
Felipe Lemef0823852016-06-08 13:43:08 -07003463 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003464 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003465
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003466 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3467 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3468 }
3469 try {
3470 int appId = UserHandle.getAppId(uid);
3471 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3472 && !isUidForegroundOnRestrictPowerUL(uid)) {
3473 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3474 } else {
3475 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3476 }
3477 } finally {
3478 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003479 }
3480 }
3481
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003482 /**
3483 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3484 * changed.
3485 */
Felipe Lemef0823852016-06-08 13:43:08 -07003486 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003487 boolean paroled = mUsageStats.isAppIdleParoleOn();
3488 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003489 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003490
3491 int ruleCount = mUidFirewallStandbyRules.size();
3492 for (int i = 0; i < ruleCount; i++) {
3493 int uid = mUidFirewallStandbyRules.keyAt(i);
3494 int oldRules = mUidRules.get(uid);
3495 if (enableChain) {
3496 // Chain wasn't enabled before and the other power-related
3497 // chains are whitelists, so we can clear the
3498 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3499 // the effective rules result in blocking network access.
3500 oldRules &= MASK_METERED_NETWORKS;
3501 } else {
3502 // Skip if it had no restrictions to begin with
3503 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3504 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003505 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3506 if (newUidRules == RULE_NONE) {
3507 mUidRules.delete(uid);
3508 } else {
3509 mUidRules.put(uid, newUidRules);
3510 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003511 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003512 }
3513
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003514 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003515 * Update rules that might be changed by {@link #mRestrictBackground},
3516 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003517 */
Felipe Lemef0823852016-06-08 13:43:08 -07003518 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003519 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3520 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3521 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3522 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003523 try {
Felipe Leme09700462016-09-08 09:33:48 -07003524 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003525 updateRulesForRestrictPowerUL();
3526 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003527
Felipe Leme873a83a2016-09-07 11:34:10 -07003528 // If the set of restricted networks may have changed, re-evaluate those.
3529 if (restrictedNetworksChanged) {
3530 normalizePoliciesNL();
3531 updateNetworkRulesNL();
3532 }
3533 } finally {
3534 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003535 }
3536 }
3537
Felipe Leme09700462016-09-08 09:33:48 -07003538 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003539 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003540 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3541 try {
3542 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003543 updateRulesForPowerSaveUL();
3544 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3545 } finally {
3546 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3547 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003548 }
3549
Felipe Lemef0823852016-06-08 13:43:08 -07003550 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003551 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3552 try {
3553 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3554 } finally {
3555 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3556 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003557 }
3558
3559 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3560 private static final int TYPE_RESTRICT_POWER = 2;
3561 @Retention(RetentionPolicy.SOURCE)
3562 @IntDef(flag = false, value = {
3563 TYPE_RESTRICT_BACKGROUND,
3564 TYPE_RESTRICT_POWER,
3565 })
3566 public @interface RestrictType {
3567 }
3568
3569 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003570 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003571 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3572 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3573 }
3574 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003575 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003576
3577 final PackageManager pm = mContext.getPackageManager();
3578 final List<UserInfo> users;
3579 final List<ApplicationInfo> apps;
3580
3581 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3582 try {
3583 users = mUserManager.getUsers();
3584 } finally {
3585 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3586 }
3587 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3588 try {
3589 apps = pm.getInstalledApplications(
3590 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3591 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3592 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3593 } finally {
3594 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3595 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003596
Felipe Leme873a83a2016-09-07 11:34:10 -07003597 final int usersSize = users.size();
3598 final int appsSize = apps.size();
3599 for (int i = 0; i < usersSize; i++) {
3600 final UserInfo user = users.get(i);
3601 for (int j = 0; j < appsSize; j++) {
3602 final ApplicationInfo app = apps.get(j);
3603 final int uid = UserHandle.getUid(user.id, app.uid);
3604 switch (type) {
3605 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003606 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003607 break;
3608 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003609 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003610 break;
3611 default:
3612 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3613 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003614 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003615 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003616 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003617 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003618 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003619 }
3620
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003621 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003622 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003623 final int numUsers = users.size();
3624 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003625 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003626 int uid = UserHandle.getUid(user.id, appId);
3627 // Update external firewall rules.
3628 updateRuleForAppIdleUL(uid);
3629 updateRuleForDeviceIdleUL(uid);
3630 updateRuleForRestrictPowerUL(uid);
3631 // Update internal rules.
3632 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003633 }
3634 }
3635
Felipe Leme70c57c22016-03-29 10:45:13 -07003636 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3637 // methods below could be merged into a isUidValidForRules() method.
3638 private boolean isUidValidForBlacklistRules(int uid) {
3639 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003640 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003641 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003642 return true;
3643 }
3644
3645 return false;
3646 }
3647
Felipe Leme70c57c22016-03-29 10:45:13 -07003648 private boolean isUidValidForWhitelistRules(int uid) {
3649 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3650 }
3651
Amith Yamasani15e472352015-04-24 19:06:07 -07003652 private boolean isUidIdle(int uid) {
3653 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3654 final int userId = UserHandle.getUserId(uid);
3655
songjinshi0655edd2016-05-18 19:55:32 +08003656 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003657 for (String packageName : packages) {
3658 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3659 return false;
3660 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003661 }
3662 }
3663 return true;
3664 }
3665
3666 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003667 * Checks if an uid has INTERNET permissions.
3668 * <p>
3669 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003670 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003671 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003672 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003673 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003674 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003675 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003676 }
3677 } catch (RemoteException e) {
3678 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003679 return true;
3680 }
3681
3682 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003683 * Clears all state - internal and external - associated with an UID.
3684 */
3685 private void onUidDeletedUL(int uid) {
3686 // First cleanup in-memory state synchronously...
3687 mUidRules.delete(uid);
3688 mUidPolicy.delete(uid);
3689 mUidFirewallStandbyRules.delete(uid);
3690 mUidFirewallDozableRules.delete(uid);
3691 mUidFirewallPowerSaveRules.delete(uid);
3692 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3693 mPowerSaveWhitelistAppIds.delete(uid);
3694 mPowerSaveTempWhitelistAppIds.delete(uid);
3695
3696 // ...then update iptables asynchronously.
3697 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3698 }
3699
3700 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003701 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003702 *
Felipe Leme781ba142016-05-09 16:24:48 -07003703 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003704 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003705 * <li>Doze mode
3706 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003707 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003708 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003709 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003710 *
3711 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003712 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003713 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003714 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003715 updateRuleForDeviceIdleUL(uid);
3716 updateRuleForAppIdleUL(uid);
3717 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003718
3719 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003720 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003721
3722 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003723 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003724 }
3725
Felipe Leme70c57c22016-03-29 10:45:13 -07003726 /**
3727 * Applies network rules to bandwidth controllers based on process state and user-defined
3728 * restrictions (blacklist / whitelist).
3729 *
3730 * <p>
3731 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3732 * networks:
3733 * <ul>
3734 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3735 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3736 * also blacklisted.
3737 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3738 * no UIDs other those whitelisted will have access.
3739 * <ul>
3740 *
3741 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3742 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3743 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3744 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003745 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003746 * {@link INetworkManagementService}, but this method should also be called in events (like
3747 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3748 * following rules should also be applied:
3749 *
3750 * <ul>
3751 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3752 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3753 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3754 * {@code bw_penalty_box}.
3755 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3756 * </ul>
3757 *
3758 * <p>For optimization, the rules are only applied on user apps that have internet access
3759 * permission, since there is no need to change the {@code iptables} rule if the app does not
3760 * have permission to use the internet.
3761 *
3762 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003763 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003764 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003765 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003766 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3767 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3768 "updateRulesForDataUsageRestrictionsUL: " + uid);
3769 }
3770 try {
3771 updateRulesForDataUsageRestrictionsULInner(uid);
3772 } finally {
3773 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3774 }
3775 }
3776
3777 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003778 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003779 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003780 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003781 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003782
Dianne Hackborn497175b2014-07-01 12:56:08 -07003783 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003784 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003785 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003786 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003787
Felipe Leme781ba142016-05-09 16:24:48 -07003788 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003789 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003790 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3791 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003792
Felipe Leme70c57c22016-03-29 10:45:13 -07003793 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003794 if (isRestrictedByAdmin) {
3795 newRule = RULE_REJECT_METERED;
3796 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003797 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3798 newRule = RULE_TEMPORARY_ALLOW_METERED;
3799 } else if (isWhitelisted) {
3800 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003801 }
3802 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003803 if (isBlacklisted) {
3804 newRule = RULE_REJECT_METERED;
3805 } else if (mRestrictBackground && isWhitelisted) {
3806 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003807 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003808 }
Felipe Leme781ba142016-05-09 16:24:48 -07003809 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003810
Felipe Lemef28983d2016-03-25 12:18:23 -07003811 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003812 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003813 + ": isForeground=" +isForeground
3814 + ", isBlacklisted=" + isBlacklisted
3815 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003816 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003817 + ", oldRule=" + uidRulesToString(oldRule)
3818 + ", newRule=" + uidRulesToString(newRule)
3819 + ", newUidRules=" + uidRulesToString(newUidRules)
3820 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003821 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003822
Felipe Leme46c4fc32016-05-04 09:21:43 -07003823 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003824 mUidRules.delete(uid);
3825 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003826 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003827 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003828
Felipe Leme70c57c22016-03-29 10:45:13 -07003829 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003830 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003831 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003832 // Temporarily whitelist foreground app, removing from blacklist if necessary
3833 // (since bw_penalty_box prevails over bw_happy_box).
3834
3835 setMeteredNetworkWhitelist(uid, true);
3836 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3837 // but ideally it should be just:
3838 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003839 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003840 setMeteredNetworkBlacklist(uid, false);
3841 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003842 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003843 // Remove temporary whitelist from app that is not on foreground anymore.
3844
3845 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3846 // but ideally they should be just:
3847 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3848 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003849 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003850 setMeteredNetworkWhitelist(uid, false);
3851 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003852 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003853 setMeteredNetworkBlacklist(uid, true);
3854 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003855 } else if (hasRule(newRule, RULE_REJECT_METERED)
3856 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003857 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003858 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003859 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003860 // Since blacklist prevails over whitelist, we need to handle the special case
3861 // where app is whitelisted and blacklisted at the same time (although such
3862 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003863 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003864 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003865 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3866 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003867 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003868 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003869 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003870 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003871 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3872 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003873 + ", whitelisted=" + isWhitelisted
3874 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003875 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003876 + ", newRule=" + uidRulesToString(newUidRules)
3877 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003878 }
Felipe Leme781ba142016-05-09 16:24:48 -07003879
Sudheer Shankac9d94072017-02-22 22:13:55 +00003880 // Dispatch changed rule to existing listeners.
3881 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003882 }
3883 }
3884
3885 /**
3886 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3887 * listeners in case of change.
3888 * <p>
3889 * There are 3 power-related rules that affects whether an app has background access on
3890 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3891 * restriction, it's added to the equivalent firewall chain:
3892 * <ul>
3893 * <li>App is idle: {@code fw_standby} firewall chain.
3894 * <li>Device is idle: {@code fw_dozable} firewall chain.
3895 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3896 * </ul>
3897 * <p>
3898 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3899 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3900 * <p>
3901 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3902 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003903 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003904 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3905
Sudheer Shankac9d94072017-02-22 22:13:55 +00003906 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003907
Sudheer Shankac9d94072017-02-22 22:13:55 +00003908 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003909 mUidRules.delete(uid);
3910 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003911 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003912 }
3913 }
3914
3915 /**
3916 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3917 *
3918 * @param uid the uid of the app to update rules for
3919 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3920 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3921 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003922 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003923 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003924 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003925 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3926 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3927 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3928 + (paroled ? "P" : "-"));
3929 }
3930 try {
3931 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3932 } finally {
3933 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3934 }
3935 }
3936
3937 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003938 if (!isUidValidForBlacklistRules(uid)) {
3939 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003940 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003941 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003942
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003943 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003944 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003945 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003946
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003947 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003948 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3949 int newRule = RULE_NONE;
3950
3951 // First step: define the new rule based on user restrictions and foreground state.
3952
3953 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3954 // by considering the foreground and non-foreground states.
3955 if (isForeground) {
3956 if (restrictMode) {
3957 newRule = RULE_ALLOW_ALL;
3958 }
3959 } else if (restrictMode) {
3960 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3961 }
3962
3963 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3964
3965 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003966 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003967 + ", isIdle: " + isIdle
3968 + ", mRestrictPower: " + mRestrictPower
3969 + ", mDeviceIdleMode: " + mDeviceIdleMode
3970 + ", isForeground=" + isForeground
3971 + ", isWhitelisted=" + isWhitelisted
3972 + ", oldRule=" + uidRulesToString(oldRule)
3973 + ", newRule=" + uidRulesToString(newRule)
3974 + ", newUidRules=" + uidRulesToString(newUidRules)
3975 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3976 }
3977
Felipe Leme781ba142016-05-09 16:24:48 -07003978 // Second step: notify listeners if state changed.
3979 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003980 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003981 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003982 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003983 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3984 } else {
3985 // All scenarios should have been covered above
3986 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3987 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003988 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003989 + ", newRule=" + uidRulesToString(newUidRules)
3990 + ", oldRule=" + uidRulesToString(oldUidRules));
3991 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003992 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003993 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003994
Sudheer Shankac9d94072017-02-22 22:13:55 +00003995 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003996 }
3997
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003998 private class AppIdleStateChangeListener
3999 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4000
4001 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004002 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4003 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004004 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004005 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4006 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004007 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004008 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004009 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004010 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004011 }
4012 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004013 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004014 }
4015
4016 @Override
4017 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004018 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004019 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004020 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004021 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004022 }
4023 }
4024
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004025 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4026 if (listener != null) {
4027 try {
4028 listener.onUidRulesChanged(uid, uidRules);
4029 } catch (RemoteException ignored) {
4030 }
4031 }
4032 }
4033
4034 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4035 String[] meteredIfaces) {
4036 if (listener != null) {
4037 try {
4038 listener.onMeteredIfacesChanged(meteredIfaces);
4039 } catch (RemoteException ignored) {
4040 }
4041 }
4042 }
4043
4044 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4045 boolean restrictBackground) {
4046 if (listener != null) {
4047 try {
4048 listener.onRestrictBackgroundChanged(restrictBackground);
4049 } catch (RemoteException ignored) {
4050 }
4051 }
4052 }
4053
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004054 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4055 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004056 if (listener != null) {
4057 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004058 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004059 } catch (RemoteException ignored) {
4060 }
4061 }
4062 }
4063
Jeff Sharkey9252b342018-01-19 07:58:35 +09004064 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4065 int overrideMask, int overrideValue) {
4066 if (listener != null) {
4067 try {
4068 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4069 } catch (RemoteException ignored) {
4070 }
4071 }
4072 }
4073
Makoto Onuki8e777332017-03-28 11:25:47 -07004074 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004075 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004076 public boolean handleMessage(Message msg) {
4077 switch (msg.what) {
4078 case MSG_RULES_CHANGED: {
4079 final int uid = msg.arg1;
4080 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004081 final int length = mListeners.beginBroadcast();
4082 for (int i = 0; i < length; i++) {
4083 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4084 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004085 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004086 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004087 return true;
4088 }
4089 case MSG_METERED_IFACES_CHANGED: {
4090 final String[] meteredIfaces = (String[]) msg.obj;
4091 final int length = mListeners.beginBroadcast();
4092 for (int i = 0; i < length; i++) {
4093 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004094 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004095 }
4096 mListeners.finishBroadcast();
4097 return true;
4098 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004099 case MSG_LIMIT_REACHED: {
4100 final String iface = (String) msg.obj;
4101
Felipe Lemef0823852016-06-08 13:43:08 -07004102 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004103 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004104 // force stats update to make sure we have
4105 // numbers that caused alert to trigger.
4106 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004107
Felipe Lemef0823852016-06-08 13:43:08 -07004108 updateNetworkEnabledNL();
4109 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004110 }
4111 }
4112 return true;
4113 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004114 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4115 final boolean restrictBackground = msg.arg1 != 0;
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 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004120 }
4121 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004122 final Intent intent =
4123 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4124 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4125 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4126 return true;
4127 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004128 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004129 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004130 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004131 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004132 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004133 final int length = mListeners.beginBroadcast();
4134 for (int i = 0; i < length; i++) {
4135 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004136 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004137 }
4138 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004139 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4140 if (notifyApp.booleanValue()) {
4141 broadcastRestrictBackgroundChanged(uid, notifyApp);
4142 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004143 return true;
4144 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004145 case MSG_ADVISE_PERSIST_THRESHOLD: {
4146 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004147 // make sure stats are recorded frequently enough; we aim
4148 // for 2MB threshold for 2GB/month rules.
4149 final long persistThreshold = lowestRule / 1000;
4150 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004151 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004152 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004153 case MSG_UPDATE_INTERFACE_QUOTA: {
4154 removeInterfaceQuota((String) msg.obj);
4155 // int params need to be stitched back into a long
4156 setInterfaceQuota((String) msg.obj,
4157 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4158 return true;
4159 }
4160 case MSG_REMOVE_INTERFACE_QUOTA: {
4161 removeInterfaceQuota((String) msg.obj);
4162 return true;
4163 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004164 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4165 resetUidFirewallRules(msg.arg1);
4166 return true;
4167 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004168 case MSG_SUBSCRIPTION_OVERRIDE: {
4169 final int overrideMask = msg.arg1;
4170 final int overrideValue = msg.arg2;
4171 final int subId = (int) msg.obj;
4172 final int length = mListeners.beginBroadcast();
4173 for (int i = 0; i < length; i++) {
4174 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4175 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4176 }
4177 mListeners.finishBroadcast();
4178 return true;
4179 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004180 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4181 final int userId = msg.arg1;
4182 final Set<String> packageNames = (Set<String>) msg.obj;
4183 setMeteredRestrictedPackagesInternal(packageNames, userId);
4184 return true;
4185 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004186 default: {
4187 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004188 }
4189 }
4190 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004191 };
4192
4193 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4194 @Override
4195 public boolean handleMessage(Message msg) {
4196 switch (msg.what) {
4197 case UID_MSG_STATE_CHANGED: {
4198 final int uid = msg.arg1;
4199 final int procState = msg.arg2;
4200 final long procStateSeq = (Long) msg.obj;
4201
4202 handleUidChanged(uid, procState, procStateSeq);
4203 return true;
4204 }
4205 case UID_MSG_GONE: {
4206 final int uid = msg.arg1;
4207 handleUidGone(uid);
4208 return true;
4209 }
4210 default: {
4211 return false;
4212 }
4213 }
4214 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004215
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004216 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004217
Makoto Onuki8e777332017-03-28 11:25:47 -07004218 void handleUidChanged(int uid, int procState, long procStateSeq) {
4219 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4220 try {
4221 synchronized (mUidRulesFirstLock) {
4222 // We received a uid state change callback, add it to the history so that it
4223 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004224 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004225 // Now update the network policy rules as per the updated uid state.
4226 updateUidStateUL(uid, procState);
4227 // Updating the network rules is done, so notify AMS about this.
4228 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4229 }
4230 } finally {
4231 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4232 }
4233 }
4234
4235 void handleUidGone(int uid) {
4236 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4237 try {
4238 synchronized (mUidRulesFirstLock) {
4239 removeUidStateUL(uid);
4240 }
4241 } finally {
4242 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4243 }
4244 }
4245
Felipe Leme57e3d312016-08-23 14:42:52 -07004246 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4247 final PackageManager pm = mContext.getPackageManager();
4248 final String[] packages = pm.getPackagesForUid(uid);
4249 if (packages != null) {
4250 final int userId = UserHandle.getUserId(uid);
4251 for (String packageName : packages) {
4252 final Intent intent =
4253 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4254 intent.setPackage(packageName);
4255 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4256 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4257 }
4258 }
4259 }
4260
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004261 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4262 // long quotaBytes split up into two ints to fit in message
4263 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4264 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4265 }
4266
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004267 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004268 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004269 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004270 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004271 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004272 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004273 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004274 }
4275 }
4276
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004277 private void removeInterfaceQuotaAsync(String iface) {
4278 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4279 }
4280
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004281 private void removeInterfaceQuota(String iface) {
4282 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004283 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004284 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004285 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004286 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004287 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004288 }
4289 }
4290
Felipe Leme70c57c22016-03-29 10:45:13 -07004291 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4292 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004293 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004294 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004295 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004296 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4297 } catch (RemoteException e) {
4298 // ignored; service lives in system_server
4299 }
4300 }
4301
4302 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4303 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4304 try {
4305 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4306 } catch (IllegalStateException e) {
4307 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004308 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004309 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004310 }
4311 }
4312
Felipe Lemebc853dd2016-09-08 13:26:55 -07004313 private static final int CHAIN_TOGGLE_NONE = 0;
4314 private static final int CHAIN_TOGGLE_ENABLE = 1;
4315 private static final int CHAIN_TOGGLE_DISABLE = 2;
4316 @Retention(RetentionPolicy.SOURCE)
4317 @IntDef(flag = false, value = {
4318 CHAIN_TOGGLE_NONE,
4319 CHAIN_TOGGLE_ENABLE,
4320 CHAIN_TOGGLE_DISABLE
4321 })
4322 public @interface ChainToggleType {
4323 }
4324
4325 /**
4326 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004327 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004328 *
4329 * @param chain firewall chain.
4330 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4331 * @param toggle whether the chain should be enabled, disabled, or not changed.
4332 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004333 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004334 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004335 if (uidRules != null) {
4336 setUidFirewallRulesUL(chain, uidRules);
4337 }
4338 if (toggle != CHAIN_TOGGLE_NONE) {
4339 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4340 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004341 }
4342
Amith Yamasani15e472352015-04-24 19:06:07 -07004343 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004344 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4345 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4346 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004347 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004348 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004349 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004350 int size = uidRules.size();
4351 int[] uids = new int[size];
4352 int[] rules = new int[size];
4353 for(int index = size - 1; index >= 0; --index) {
4354 uids[index] = uidRules.keyAt(index);
4355 rules[index] = uidRules.valueAt(index);
4356 }
4357 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004358 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004359 } catch (IllegalStateException e) {
4360 Log.wtf(TAG, "problem setting firewall uid rules", e);
4361 } catch (RemoteException e) {
4362 // ignored; service lives in system_server
4363 }
4364 }
4365
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004366 /**
4367 * Add or remove a uid to the firewall blacklist for all network ifaces.
4368 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004369 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004370 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4371 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4372 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004373 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004374 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004375 if (chain == FIREWALL_CHAIN_DOZABLE) {
4376 mUidFirewallDozableRules.put(uid, rule);
4377 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4378 mUidFirewallStandbyRules.put(uid, rule);
4379 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4380 mUidFirewallPowerSaveRules.put(uid, rule);
4381 }
4382
4383 try {
4384 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004385 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004386 } catch (IllegalStateException e) {
4387 Log.wtf(TAG, "problem setting firewall uid rules", e);
4388 } catch (RemoteException e) {
4389 // ignored; service lives in system_server
4390 }
4391 } finally {
4392 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004393 }
4394 }
4395
4396 /**
4397 * Add or remove a uid to the firewall blacklist for all network ifaces.
4398 */
Felipe Lemef0823852016-06-08 13:43:08 -07004399 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004400 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4401 mFirewallChainStates.get(chain) == enable) {
4402 // All is the same, nothing to do.
4403 return;
4404 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004405 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004406 try {
4407 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004408 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004409 } catch (IllegalStateException e) {
4410 Log.wtf(TAG, "problem enable firewall chain", e);
4411 } catch (RemoteException e) {
4412 // ignored; service lives in system_server
4413 }
4414 }
4415
Felipe Leme03e95e22016-09-09 09:25:31 -07004416 /**
4417 * Resets all firewall rules associated with an UID.
4418 */
4419 private void resetUidFirewallRules(int uid) {
4420 try {
4421 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4422 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4423 mNetworkManager
4424 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4425 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4426 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4427 } catch (IllegalStateException e) {
4428 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4429 } catch (RemoteException e) {
4430 // ignored; service lives in system_server
4431 }
4432 }
4433
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004434 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004435 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004436 return getNetworkTotalBytes(template, start, end);
4437 }
4438
4439 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004440 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004441 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004442 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004443 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004444 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004445 }
4446 }
4447
4448 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4449 try {
4450 return mNetworkStats.getNetworkUidBytes(template, start, end);
4451 } catch (RuntimeException e) {
4452 Slog.w(TAG, "Failed to read network stats: " + e);
4453 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004454 }
4455 }
4456
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004457 private boolean isBandwidthControlEnabled() {
4458 final long token = Binder.clearCallingIdentity();
4459 try {
4460 return mNetworkManager.isBandwidthControlEnabled();
4461 } catch (RemoteException e) {
4462 // ignored; service lives in system_server
4463 return false;
4464 } finally {
4465 Binder.restoreCallingIdentity(token);
4466 }
4467 }
4468
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004469 private static Intent buildAllowBackgroundDataIntent() {
4470 return new Intent(ACTION_ALLOW_BACKGROUND);
4471 }
4472
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004473 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4474 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004475 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4476 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4477 return intent;
4478 }
4479
4480 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4481 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4482 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004483 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4484 return intent;
4485 }
4486
Wei Liu546cb772016-07-21 16:19:01 -07004487 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004488 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004489 intent.setComponent(ComponentName.unflattenFromString(
4490 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004491 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4492 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4493 return intent;
4494 }
4495
Wei Liu546cb772016-07-21 16:19:01 -07004496 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004497 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004498 intent.setComponent(ComponentName.unflattenFromString(
4499 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004500 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4501 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4502 return intent;
4503 }
4504
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004505 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004506 public void addIdleHandler(IdleHandler handler) {
4507 mHandler.getLooper().getQueue().addIdleHandler(handler);
4508 }
4509
jackqdyulei29c82ab2017-03-10 14:09:16 -08004510 @VisibleForTesting
4511 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4512 mRestrictBackgroundPowerState = result;
4513
4514 boolean restrictBackground = result.batterySaverEnabled;
4515 boolean shouldInvokeRestrictBackground;
4516 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4517 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4518
4519 if (result.globalBatterySaverEnabled) {
4520 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4521 // turn it on.
4522 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4523 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4524 localRestrictBgChangedInBsm = false;
4525 } else {
4526 // Try to restore the restrictBackground if it doesn't change in bsm
4527 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4528 restrictBackground = mRestrictBackgroundBeforeBsm;
4529 }
4530
4531 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004532 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004533 }
4534
4535 // Change it at last so setRestrictBackground() won't affect this variable
4536 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4537 }
4538
Jeff Sharkey1b861272011-05-22 00:34:52 -07004539 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4540 final int size = source.size();
4541 for (int i = 0; i < size; i++) {
4542 target.put(source.keyAt(i), true);
4543 }
4544 }
4545
Stuart Scottf1fb3972015-04-02 18:00:02 -07004546 @Override
4547 public void factoryReset(String subscriber) {
4548 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4549
Stuart Scotte3e314d2015-04-20 14:07:45 -07004550 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4551 return;
4552 }
4553
Stuart Scottf1fb3972015-04-02 18:00:02 -07004554 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004555 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004556 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4557 for (NetworkPolicy policy : policies) {
4558 if (policy.template.equals(template)) {
4559 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4560 policy.inferred = false;
4561 policy.clearSnooze();
4562 }
4563 }
4564 setNetworkPolicies(policies);
4565
4566 // Turn restrict background data off
4567 setRestrictBackground(false);
4568
Stuart Scotte3e314d2015-04-20 14:07:45 -07004569 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4570 // Remove app's "restrict background data" flag
4571 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4572 setUidPolicy(uid, POLICY_NONE);
4573 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004574 }
4575 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004576
Sudheer Shankab8f23162017-08-04 13:30:10 -07004577 @Override
4578 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4579 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4580 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4581 }
4582
4583 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4584 final int uidRules;
4585 final boolean isBackgroundRestricted;
4586 synchronized (mUidRulesFirstLock) {
4587 uidRules = mUidRules.get(uid, RULE_NONE);
4588 isBackgroundRestricted = mRestrictBackground;
4589 }
4590 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004591 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004592 return true;
4593 }
4594 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004595 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004596 return false;
4597 }
4598 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004599 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004600 return true;
4601 }
4602 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004603 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004604 return false;
4605 }
4606 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004607 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004608 return false;
4609 }
4610 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004611 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004612 return true;
4613 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004614 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004615 return false;
4616 }
4617
Felipe Lemed17fda42016-04-29 11:12:45 -07004618 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4619
4620 @Override
4621 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004622 synchronized (mUidRulesFirstLock) {
4623 boolean changed = removeUserStateUL(userId, false);
4624 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004625 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004626 synchronized (mNetworkPoliciesSecondLock) {
4627 writePolicyAL();
4628 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004629 }
4630 }
4631 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004632
4633 /**
4634 * @return true if the given uid is restricted from doing networking on metered networks.
4635 */
4636 @Override
4637 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4638 final int uidRules;
4639 final boolean isBackgroundRestricted;
4640 synchronized (mUidRulesFirstLock) {
4641 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4642 isBackgroundRestricted = mRestrictBackground;
4643 }
4644 return isBackgroundRestricted
4645 && !hasRule(uidRules, RULE_ALLOW_METERED)
4646 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4647 }
4648
4649 /**
4650 * @return true if networking is blocked on the given interface for the given uid according
4651 * to current networking policies.
4652 */
4653 @Override
4654 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004655 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004656 synchronized (mNetworkPoliciesSecondLock) {
4657 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004658 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004659 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004660 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004661
4662 @Override
4663 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4664 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004665 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004666 if (added) {
4667 mPowerSaveTempWhitelistAppIds.put(appId, true);
4668 } else {
4669 mPowerSaveTempWhitelistAppIds.delete(appId);
4670 }
4671 updateRulesForTempWhitelistChangeUL(appId);
4672 }
4673 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004674
4675 @Override
4676 public SubscriptionPlan getSubscriptionPlan(Network network) {
4677 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004678 final int subId = getSubIdLocked(network);
4679 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004680 }
4681 }
4682
4683 @Override
4684 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4685 synchronized (mNetworkPoliciesSecondLock) {
4686 // TODO: handle splitting quota between use-cases
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004687 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
4688 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004689 }
4690 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004691
4692 @Override
4693 public void onAdminDataAvailable() {
4694 mAdminDataAvailableLatch.countDown();
4695 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004696
4697 @Override
4698 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4699 setMeteredRestrictedPackagesInternal(packageNames, userId);
4700 }
4701
4702 @Override
4703 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4704 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4705 userId, 0, packageNames).sendToTarget();
4706 }
4707 }
4708
4709 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4710 synchronized (mUidRulesFirstLock) {
4711 final Set<Integer> newRestrictedUids = new ArraySet<>();
4712 for (String packageName : packageNames) {
4713 final int uid = getUidForPackage(packageName, userId);
4714 if (uid >= 0) {
4715 newRestrictedUids.add(uid);
4716 }
4717 }
4718 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4719 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4720 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4721 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4722 }
4723 }
4724
4725 private int getUidForPackage(String packageName, int userId) {
4726 try {
4727 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4728 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4729 } catch (NameNotFoundException e) {
4730 return -1;
4731 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004732 }
4733
4734 private int parseSubId(NetworkState state) {
4735 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4736 int subId = INVALID_SUBSCRIPTION_ID;
4737 if (state != null && state.networkCapabilities != null
4738 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4739 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4740 if (spec instanceof StringNetworkSpecifier) {
4741 try {
4742 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4743 } catch (NumberFormatException e) {
4744 }
4745 }
4746 }
4747 return subId;
4748 }
4749
Andreas Gampea36dc622018-02-05 17:19:22 -08004750 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004751 private int getSubIdLocked(Network network) {
4752 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004753 }
4754
Andreas Gampea36dc622018-02-05 17:19:22 -08004755 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004756 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4757 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4758 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4759 }
4760
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004761 /**
4762 * This will only ever be called once - during device boot.
4763 */
4764 private void waitForAdminData() {
4765 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4766 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4767 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4768 }
4769 }
4770
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004771 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4772 Set<Integer> newRestrictedUids) {
4773 if (oldRestrictedUids == null) {
4774 for (int uid : newRestrictedUids) {
4775 updateRulesForDataUsageRestrictionsUL(uid);
4776 }
4777 return;
4778 }
4779 for (int uid : oldRestrictedUids) {
4780 if (!newRestrictedUids.contains(uid)) {
4781 updateRulesForDataUsageRestrictionsUL(uid);
4782 }
4783 }
4784 for (int uid : newRestrictedUids) {
4785 if (!oldRestrictedUids.contains(uid)) {
4786 updateRulesForDataUsageRestrictionsUL(uid);
4787 }
4788 }
4789 }
4790
4791 private boolean isRestrictedByAdminUL(int uid) {
4792 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4793 UserHandle.getUserId(uid));
4794 return restrictedUids != null && restrictedUids.contains(uid);
4795 }
4796
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004797 private static boolean hasRule(int uidRules, int rule) {
4798 return (uidRules & rule) != 0;
4799 }
4800
Jeff Sharkey2e471452018-01-19 18:02:47 +09004801 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4802 return (val != null) ? val : new NetworkState[0];
4803 }
4804
Chris Wren193ae6b2017-03-31 15:17:11 -04004805 private class NotificationId {
4806 private final String mTag;
4807 private final int mId;
4808
4809 NotificationId(NetworkPolicy policy, int type) {
4810 mTag = buildNotificationTag(policy, type);
4811 mId = type;
4812 }
4813
4814 @Override
4815 public boolean equals(Object o) {
4816 if (this == o) return true;
4817 if (!(o instanceof NotificationId)) return false;
4818 NotificationId that = (NotificationId) o;
4819 return Objects.equals(mTag, that.mTag);
4820 }
4821
4822 @Override
4823 public int hashCode() {
4824 return Objects.hash(mTag);
4825 }
4826
4827 /**
4828 * Build unique tag that identifies an active {@link NetworkPolicy}
4829 * notification of a specific type, like {@link #TYPE_LIMIT}.
4830 */
4831 private String buildNotificationTag(NetworkPolicy policy, int type) {
4832 return TAG + ":" + policy.template.hashCode() + ":" + type;
4833 }
4834
4835 public String getTag() {
4836 return mTag;
4837 }
4838
4839 public int getId() {
4840 return mId;
4841 }
4842 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004843}