blob: 98dee35168fe29448660a0d74db0d0e45d84aa28 [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 Sharkeya7f50462018-02-14 14:26:10 -0700152import android.os.Build;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700153import android.os.Environment;
154import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700155import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700156import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700157import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700158import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700159import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700160import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700161import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700162import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700163import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600164import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800165import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700167import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600168import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700169import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700170import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700171import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600172import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700173import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700174import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700175import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700176import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100177import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700178import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600179import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800180import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600181import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700182import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400183import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700184import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700185import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700186import android.util.ArrayMap;
187import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700188import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900189import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700190import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700191import android.util.Pair;
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;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600233import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700234import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600235import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700237import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600238import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400239import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800240import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800241import java.util.concurrent.CountDownLatch;
242import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700244/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700245 * Service that maintains low-level network policy rules, using
246 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 * <p>
248 * Derives active rules by combining a given policy with other system status,
249 * and delivers to listeners, such as {@link ConnectivityManager}, for
250 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700251 *
252 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000253 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700254 * <ul>
255 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
256 * rules).
257 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
258 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000259 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
260 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700261 * </ul>
262 *
263 * <p>
264 * As such, methods that require synchronization have the following prefixes:
265 * <ul>
266 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
267 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000268 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
269 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700270 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700271 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700272public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700273 static final String TAG = NetworkPolicyLogger.TAG;
274 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
275 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700276
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900277 /**
278 * No opportunistic quota could be calculated from user data plan or data settings.
279 */
280 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
281
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700282 private static final int VERSION_INIT = 1;
283 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700284 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800285 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800286 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800287 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700288 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700289 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700290 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700291 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600292 private static final int VERSION_ADDED_CYCLE = 11;
293 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800295 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400296 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800297 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400298 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800299 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400300 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900301 @VisibleForTesting
302 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700303
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 private static final String TAG_POLICY_LIST = "policy-list";
305 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600306 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700308 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800309 private static final String TAG_WHITELIST = "whitelist";
310 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800311 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
313 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700314 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
316 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700317 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600318 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
319 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
320 private static final String ATTR_CYCLE_START = "cycleStart";
321 private static final String ATTR_CYCLE_END = "cycleEnd";
322 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 private static final String ATTR_WARNING_BYTES = "warningBytes";
324 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700325 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800326 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
327 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800328 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700329 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700331 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600333 private static final String ATTR_SUB_ID = "subId";
334 private static final String ATTR_TITLE = "title";
335 private static final String ATTR_SUMMARY = "summary";
336 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
337 private static final String ATTR_USAGE_BYTES = "usageBytes";
338 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600339 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800341 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800342 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800343 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700345 private static final String ACTION_SNOOZE_RAPID =
346 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700347
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800348 /**
349 * Indicates the maximum wait time for admin data to be available;
350 */
351 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
352
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700353 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700354 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800355 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800356 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700357 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700358 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
359 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700360 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700361 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900362 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800363 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700364
Makoto Onuki8e777332017-03-28 11:25:47 -0700365 private static final int UID_MSG_STATE_CHANGED = 100;
366 private static final int UID_MSG_GONE = 101;
367
Jeff Sharkey75279902011-05-24 18:39:45 -0700368 private final Context mContext;
369 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700370 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700371 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700372 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700373 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700374 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700375 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700376
377 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700378 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700379 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800380 @GuardedBy("mUidRulesFirstLock")
381 private PowerSaveState mRestrictBackgroundPowerState;
382
383 // Store the status of restrict background before turning on battery saver.
384 // Used to restore mRestrictBackground when battery saver is turned off.
385 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700386
Sudheer Shanka543339f2017-07-28 15:18:07 -0700387 // Denotes the status of restrict background read from disk.
388 private boolean mLoadedRestrictBackground;
389
Felipe Lemef0823852016-06-08 13:43:08 -0700390 // See main javadoc for instructions on how to use these locks.
391 final Object mUidRulesFirstLock = new Object();
392 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700393
Felipe Lemef0823852016-06-08 13:43:08 -0700394 @GuardedBy("allLocks") volatile boolean mSystemReady;
395
Felipe Lemef0823852016-06-08 13:43:08 -0700396 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
397 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
398 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800399 // Store whether user flipped restrict background in battery saver mode
400 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700401
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700402 private final boolean mSuppressDefaultPolicy;
403
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800404 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
405
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700406 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600407 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800408 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700409
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600410 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600411 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600412 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600413 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600414 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600415 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600416
Jeff Sharkey9252b342018-01-19 07:58:35 +0900417 /** Map from subId to daily opportunistic quota. */
418 @GuardedBy("mNetworkPoliciesSecondLock")
419 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
420
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700421 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700422 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700423 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700425
Felipe Lemef0823852016-06-08 13:43:08 -0700426 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700427 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700429 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800431 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700432
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700433 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700434 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700435 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
436
Jeff Sharkey32566012014-12-02 18:30:14 -0800437 /**
438 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700439 * in power save mode, except device idle (doze) still applies.
440 * TODO: An int array might be sufficient
441 */
Felipe Lemef0823852016-06-08 13:43:08 -0700442 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700443 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
444
445 /**
446 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800447 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700448 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800449 */
Felipe Lemef0823852016-06-08 13:43:08 -0700450 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700451 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700452
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700454 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
455
Felipe Lemeb85a6372016-01-14 16:16:16 -0800456 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800457 * UIDs that have been initially white-listed by system to avoid restricted background.
458 */
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800460 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
461 new SparseBooleanArray();
462
463 /**
464 * UIDs that have been initially white-listed by system to avoid restricted background,
465 * but later revoked by user.
466 */
Felipe Lemef0823852016-06-08 13:43:08 -0700467 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800468 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
469 new SparseBooleanArray();
470
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700471 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700472 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800473 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700474 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700475 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800476 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700477
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700478 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700479 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400480 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700481
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700482 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700483 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800484 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700485
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600486 /** Map from network ID to last observed meteredness state */
487 @GuardedBy("mNetworkPoliciesSecondLock")
488 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
489
Jeff Sharkey9252b342018-01-19 07:58:35 +0900490 /** Map from netId to subId as of last update */
491 @GuardedBy("mNetworkPoliciesSecondLock")
492 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
493
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800494 /**
495 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
496 * userId to restricted uids which belong to that user.
497 */
498 @GuardedBy("mUidRulesFirstLock")
499 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
500
Jeff Sharkey32566012014-12-02 18:30:14 -0800501 private final RemoteCallbackList<INetworkPolicyListener>
502 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700503
Dianne Hackborn497175b2014-07-01 12:56:08 -0700504 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700505 @VisibleForTesting
506 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700507
508 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700509
Felipe Lemef0823852016-06-08 13:43:08 -0700510 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700511 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700512
Svet Ganov16a16892015-04-16 10:32:04 -0700513 private final AppOpsManager mAppOps;
514
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800515 private final IPackageManager mIPm;
516
Sudheer Shankae7361852017-03-07 11:51:46 -0800517 private ActivityManagerInternal mActivityManagerInternal;
518
Sudheer Shanka352dc572017-09-22 17:09:38 -0700519 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800520
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700521 // TODO: keep whitelist of system-critical services that should never have
522 // rules enforced, such as system, phone, and radio UIDs.
523
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700524 // TODO: migrate notifications to SystemUI
525
Jeff Sharkey75279902011-05-24 18:39:45 -0700526 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700527 INetworkManagementService networkManagement) {
528 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
529 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700530 }
531
Jeff Sharkey9911a282018-02-14 22:29:11 -0700532 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700533 return new File(Environment.getDataDirectory(), "system");
534 }
535
Jeff Sharkey9911a282018-02-14 22:29:11 -0700536 private static @NonNull Clock getDefaultClock() {
537 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
538 Clock.systemUTC());
539 }
540
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700541 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700542 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
543 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700544 mContext = checkNotNull(context, "missing context");
545 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700546 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700547 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700548 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700549 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700550 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700551 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700552 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700553
Amith Yamasani450a16b2013-09-18 16:28:50 -0700554 HandlerThread thread = new HandlerThread(TAG);
555 thread.start();
556 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700557
Makoto Onuki8e777332017-03-28 11:25:47 -0700558 // We create another thread for the UID events, which are more time-critical.
559 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
560 /*allowIo=*/ false);
561 mUidEventThread.start();
562 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
563
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700564 mSuppressDefaultPolicy = suppressDefaultPolicy;
565
Dianne Hackborne17b4452018-01-10 13:15:40 -0800566 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700567
568 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800569
Felipe Lemed17fda42016-04-29 11:12:45 -0700570 // Expose private service for system components to use.
571 LocalServices.addService(NetworkPolicyManagerInternal.class,
572 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700573 }
574
575 public void bindConnectivityManager(IConnectivityManager connManager) {
576 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700577 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700578
Felipe Lemef0823852016-06-08 13:43:08 -0700579 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700580 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700581 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
582 mPowerSaveWhitelistExceptIdleAppIds.clear();
583 if (whitelist != null) {
584 for (int uid : whitelist) {
585 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
586 }
587 }
588 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700589 mPowerSaveWhitelistAppIds.clear();
590 if (whitelist != null) {
591 for (int uid : whitelist) {
592 mPowerSaveWhitelistAppIds.put(uid, true);
593 }
594 }
595 } catch (RemoteException e) {
596 }
597 }
598
Felipe Lemea9505cc2016-02-26 10:28:41 -0800599 /**
600 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
601 * revoke the whitelist.
602 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700603 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800604 */
Felipe Lemef0823852016-06-08 13:43:08 -0700605 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800606 final List<UserInfo> users = mUserManager.getUsers();
607 final int numberUsers = users.size();
608
Felipe Lemea110eec2016-04-29 09:58:06 -0700609 boolean changed = false;
610 for (int i = 0; i < numberUsers; i++) {
611 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700612 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700613 }
614 return changed;
615 }
616
Felipe Lemef0823852016-06-08 13:43:08 -0700617 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700618 final SystemConfig sysConfig = SystemConfig.getInstance();
619 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800620 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
621 boolean changed = false;
622 for (int i = 0; i < allowDataUsage.size(); i++) {
623 final String pkg = allowDataUsage.valueAt(i);
624 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700625 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
626 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800627 final ApplicationInfo app;
628 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700629 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800630 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700631 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
632 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800633 continue;
634 }
635 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700636 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
637 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800638 continue;
639 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700640 final int uid = UserHandle.getUid(userId, app.uid);
641 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
642 if (LOGD)
643 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
644 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800645 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700646 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700647 if (LOGD)
648 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
649 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700650 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700651 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800652 }
653 }
654 return changed;
655 }
656
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800657 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700658 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800659 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700660 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800661 // Boost thread's priority during system server init
662 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700663 if (!isBandwidthControlEnabled()) {
664 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
665 return;
666 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700667
Felipe Leme873a83a2016-09-07 11:34:10 -0700668 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700669 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700670
Felipe Leme873a83a2016-09-07 11:34:10 -0700671 synchronized (mUidRulesFirstLock) {
672 synchronized (mNetworkPoliciesSecondLock) {
673 updatePowerSaveWhitelistUL();
674 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
675 mPowerManagerInternal.registerLowPowerModeObserver(
676 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800677 @Override
678 public int getServiceType() {
679 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700680 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800681
682 @Override
683 public void onLowPowerModeChanged(PowerSaveState result) {
684 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800685 if (LOGD) {
686 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
687 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800688 synchronized (mUidRulesFirstLock) {
689 if (mRestrictPower != enabled) {
690 mRestrictPower = enabled;
691 updateRulesForRestrictPowerUL();
692 }
693 }
694 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800695 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800696 mRestrictPower = mPowerManagerInternal.getLowPowerState(
697 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700698
699 mSystemReady = true;
700
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800701 waitForAdminData();
702
Felipe Leme873a83a2016-09-07 11:34:10 -0700703 // read policy from disk
704 readPolicyAL();
705
jackqdyulei29c82ab2017-03-10 14:09:16 -0800706 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700707 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800708 mRestrictBackgroundPowerState = mPowerManagerInternal
709 .getLowPowerState(ServiceType.DATA_SAVER);
710 final boolean localRestrictBackground =
711 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700712 if (localRestrictBackground && !mLoadedRestrictBackground) {
713 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800714 }
715 mPowerManagerInternal.registerLowPowerModeObserver(
716 new PowerManagerInternal.LowPowerModeListener() {
717 @Override
718 public int getServiceType() {
719 return ServiceType.DATA_SAVER;
720 }
721
722 @Override
723 public void onLowPowerModeChanged(PowerSaveState result) {
724 synchronized (mUidRulesFirstLock) {
725 updateRestrictBackgroundByLowPowerModeUL(result);
726 }
727 }
728 });
729
Felipe Leme873a83a2016-09-07 11:34:10 -0700730 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
731 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700732 }
Felipe Lemef0823852016-06-08 13:43:08 -0700733
Sudheer Shanka543339f2017-07-28 15:18:07 -0700734 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700735 updateRulesForGlobalChangeAL(false);
736 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700737 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800738 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700739
Sudheer Shankae7361852017-03-07 11:51:46 -0800740 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700741 try {
742 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000743 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800744 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700745 mNetworkManager.registerObserver(mAlertObserver);
746 } catch (RemoteException e) {
747 // ignored; both services live in system_server
748 }
749
750 // listen for changes to power save whitelist
751 final IntentFilter whitelistFilter = new IntentFilter(
752 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
753 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
754
Felipe Leme873a83a2016-09-07 11:34:10 -0700755 // watch for network interfaces to be claimed
756 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
757 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
758
759 // listen for package changes to update policy
760 final IntentFilter packageFilter = new IntentFilter();
761 packageFilter.addAction(ACTION_PACKAGE_ADDED);
762 packageFilter.addDataScheme("package");
763 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
764
765 // listen for UID changes to update policy
766 mContext.registerReceiver(
767 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
768
769 // listen for user changes to update policy
770 final IntentFilter userFilter = new IntentFilter();
771 userFilter.addAction(ACTION_USER_ADDED);
772 userFilter.addAction(ACTION_USER_REMOVED);
773 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
774
775 // listen for stats update events
776 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
777 mContext.registerReceiver(
778 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
779
780 // listen for restrict background changes from notifications
781 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
782 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
783
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700784 // Listen for snooze from notifications
785 mContext.registerReceiver(mSnoozeReceiver,
786 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
787 mContext.registerReceiver(mSnoozeReceiver,
788 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700789
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600790 // listen for configured wifi networks to be loaded
791 final IntentFilter wifiFilter =
792 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
793 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700794
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700795 // listen for carrier config changes to update data cycle information
796 final IntentFilter carrierConfigFilter = new IntentFilter(
797 ACTION_CARRIER_CONFIG_CHANGED);
798 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
799
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600800 // listen for meteredness changes
801 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
802 new NetworkRequest.Builder().build(), mNetworkCallback);
803
Felipe Leme873a83a2016-09-07 11:34:10 -0700804 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800805 // tell systemReady() that the service has been initialized
806 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700807 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800808 // Restore the default priority after init is done
809 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700810 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700811 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700812 }
813
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800814 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
815 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
816 mHandler.post(() -> initService(initCompleteSignal));
817 return initCompleteSignal;
818 }
819
820 public void systemReady(CountDownLatch initCompleteSignal) {
821 // wait for initService to complete
822 try {
823 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
824 throw new IllegalStateException("Service " + TAG +" init timeout");
825 }
826 } catch (InterruptedException e) {
827 Thread.currentThread().interrupt();
828 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
829 }
830 }
831
Sudheer Shankac9d94072017-02-22 22:13:55 +0000832 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700833 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700834 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
835 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700836 }
837
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700838 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700839 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700840 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700841
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700842 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700843 }
844
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700845 @Override public void onUidIdle(int uid, boolean disabled) {
846 }
847
848 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700849 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700850 };
851
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700852 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700853 @Override
854 public void onReceive(Context context, Intent intent) {
855 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700856 synchronized (mUidRulesFirstLock) {
857 updatePowerSaveWhitelistUL();
858 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700859 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700860 }
861 }
862 };
863
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700864 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700865 @Override
866 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700867 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700868
869 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700870 final int uid = intent.getIntExtra(EXTRA_UID, -1);
871 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700872
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700873 if (ACTION_PACKAGE_ADDED.equals(action)) {
874 // update rules for UID, since it might be subject to
875 // global background data policy
876 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700877 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700878 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700879 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700880 }
881 }
882 };
883
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700884 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700885 @Override
886 public void onReceive(Context context, Intent intent) {
887 // on background handler thread, and UID_REMOVED is protected
888
889 final int uid = intent.getIntExtra(EXTRA_UID, -1);
890 if (uid == -1) return;
891
892 // remove any policy and update rules to clean up
893 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700894 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700895 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700896 synchronized (mNetworkPoliciesSecondLock) {
897 writePolicyAL();
898 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700899 }
900 }
901 };
902
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700903 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700904 @Override
905 public void onReceive(Context context, Intent intent) {
906 // on background handler thread, and USER_ADDED and USER_REMOVED
907 // broadcasts are protected
908
909 final String action = intent.getAction();
910 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
911 if (userId == -1) return;
912
Amith Yamasani15e472352015-04-24 19:06:07 -0700913 switch (action) {
914 case ACTION_USER_REMOVED:
915 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700916 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800917 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700918 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700919 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800920 // Removing outside removeUserStateUL since that can also be called when
921 // user resets app preferences.
922 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700923 if (action == ACTION_USER_ADDED) {
924 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700925 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700926 }
927 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700928 synchronized (mNetworkPoliciesSecondLock) {
929 updateRulesForGlobalChangeAL(true);
930 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700931 }
932 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700933 }
934 }
935 };
936
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700937 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 * Receiver that watches for {@link INetworkStatsService} updates, which we
939 * use to check against {@link NetworkPolicy#warningBytes}.
940 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700942 @Override
943 public void onReceive(Context context, Intent intent) {
944 // on background handler thread, and verified
945 // READ_NETWORK_USAGE_HISTORY permission above.
946
Felipe Lemef0823852016-06-08 13:43:08 -0700947 synchronized (mNetworkPoliciesSecondLock) {
948 updateNetworkEnabledNL();
949 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700950 }
951 }
952 };
953
954 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700955 * Receiver that watches for {@link Notification} control of
956 * {@link #mRestrictBackground}.
957 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700958 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700959 @Override
960 public void onReceive(Context context, Intent intent) {
961 // on background handler thread, and verified MANAGE_NETWORK_POLICY
962 // permission above.
963
964 setRestrictBackground(false);
965 }
966 };
967
968 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800969 * Receiver that watches for {@link Notification} control of
970 * {@link NetworkPolicy#lastWarningSnooze}.
971 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700972 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800973 @Override
974 public void onReceive(Context context, Intent intent) {
975 // on background handler thread, and verified MANAGE_NETWORK_POLICY
976 // permission above.
977
978 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700979 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
980 performSnooze(template, TYPE_WARNING);
981 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
982 performSnooze(template, TYPE_RAPID);
983 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800984 }
985 };
986
987 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600988 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600989 * we can perform upgrade logic. After initial upgrade logic, it updates
990 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700991 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600992 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700993 @Override
994 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900995 synchronized (mUidRulesFirstLock) {
996 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600997 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600998 }
999 }
1000 // Only need to perform upgrade logic once
1001 mContext.unregisterReceiver(this);
1002 }
1003 };
1004
1005 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1006 @Override
1007 public void onCapabilitiesChanged(Network network,
1008 NetworkCapabilities networkCapabilities) {
1009 if (network == null || networkCapabilities == null) return;
1010
1011 synchronized (mNetworkPoliciesSecondLock) {
1012 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1013 final boolean newMetered = !networkCapabilities
1014 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1015
1016 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001017 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001018 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001019 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001020 }
1021 }
1022 }
1023 };
1024
1025 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 * Observer that watches for {@link INetworkManagementService} alerts.
1027 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001028 final private INetworkManagementEventObserver mAlertObserver
1029 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001030 @Override
1031 public void limitReached(String limitName, String iface) {
1032 // only someone like NMS should be calling us
1033 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1034
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001035 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1036 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 }
1038 }
1039 };
1040
1041 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1043 * to show visible notifications as needed.
1044 */
Felipe Lemef0823852016-06-08 13:43:08 -07001045 void updateNotificationsNL() {
1046 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001047
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001049 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001051
1052 // TODO: when switching to kernel notifications, compute next future
1053 // cycle boundary to recompute notifications.
1054
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001055 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001056 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001057 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1058 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001059 // ignore policies that aren't relevant to user
1060 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001061 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062
Jeff Sharkey53313d72017-07-13 16:47:32 -06001063 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1064 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001065 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1066 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1067 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001068
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001069 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001070 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001071 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1072 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001073 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001075 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001076 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 }
1078
Jeff Sharkey497e4432011-06-14 17:27:29 -07001079 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001080 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001081
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001082 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1083 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001084 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085 }
1086 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001087
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001088 // Warn if average usage over last 4 days is on track to blow pretty
1089 // far past the plan limits.
1090 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001091 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001092 final long recentStart = now - recentDuration;
1093 final long recentEnd = now;
1094 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001095
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001096 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001097 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001098 final long alertBytes = (policy.limitBytes * 3) / 2;
1099
1100 if (LOGD) {
1101 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1102 + projectedBytes + " alert " + alertBytes);
1103 }
1104
1105 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1106 - DateUtils.DAY_IN_MILLIS;
1107 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001108 enqueueNotification(policy, TYPE_RAPID, 0,
1109 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001110 }
1111 }
1112 }
1113
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001115 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001116 final NotificationId notificationId = beforeNotifs.valueAt(i);
1117 if (!mActiveNotifs.contains(notificationId)) {
1118 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 }
1120 }
1121 }
1122
1123 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001124 * Attempt to find a specific app to blame for rapid data usage during the
1125 * given time period.
1126 */
1127 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1128 long start, long end) {
1129 long totalBytes = 0;
1130 long maxBytes = 0;
1131 int maxUid = 0;
1132
1133 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1134 NetworkStats.Entry entry = null;
1135 for (int i = 0; i < stats.size(); i++) {
1136 entry = stats.getValues(i, entry);
1137 final long bytes = entry.rxBytes + entry.txBytes;
1138 totalBytes += bytes;
1139 if (bytes > maxBytes) {
1140 maxBytes = bytes;
1141 maxUid = entry.uid;
1142 }
1143 }
1144
1145 // Only point blame if the majority of usage was done by a single app.
1146 // TODO: support shared UIDs
1147 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1148 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001149 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001150 try {
1151 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1152 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1153 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1154 } catch (NameNotFoundException ignored) {
1155 }
1156 }
1157 }
1158
1159 return null;
1160 }
1161
1162 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001164 * current device state, such as when
1165 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1166 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001167 */
1168 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001169 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001170 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1171 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001172
Jeff Sharkey32566012014-12-02 18:30:14 -08001173 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001174 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001175 for (int subId : subIds) {
1176 final String subscriberId = tele.getSubscriberId(subId);
1177 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001178 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1179 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001180 if (template.matches(probeIdent)) {
1181 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001182 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001183 }
1184 return false;
1185 } else {
1186 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001187 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 }
1189
1190 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 * Notify that given {@link NetworkTemplate} is over
1192 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1193 */
Felipe Lemef0823852016-06-08 13:43:08 -07001194 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001196 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 mOverLimitNotified.add(template);
1198 }
1199 }
1200
Felipe Lemef0823852016-06-08 13:43:08 -07001201 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001202 mOverLimitNotified.remove(template);
1203 }
1204
1205 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 * Show notification for combined {@link NetworkPolicy} and specific type,
1207 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1208 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001209 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1210 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001211 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001212 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001213 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001214 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001215 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001216 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001217 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001218
1219 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001220 final CharSequence title;
1221 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001222 switch (type) {
1223 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001224 title = res.getText(R.string.data_usage_warning_title);
1225 body = res.getString(R.string.data_usage_warning_body,
1226 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001227
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001228 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001229
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001230 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1231 builder.setDeleteIntent(PendingIntent.getBroadcast(
1232 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1233
Wei Liu546cb772016-07-21 16:19:01 -07001234 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001235 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001236 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1237
Jeff Sharkey497e4432011-06-14 17:27:29 -07001238 break;
1239 }
1240 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001241 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001242 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001243 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001244 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001245 case MATCH_WIFI:
1246 title = res.getText(R.string.data_usage_wifi_limit_title);
1247 break;
1248 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001249 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001250 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001251 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001252
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001253 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001254 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001255
Wei Liu546cb772016-07-21 16:19:01 -07001256 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001257 builder.setContentIntent(PendingIntent.getActivity(
1258 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1259 break;
1260 }
1261 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001262 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001263 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001264 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1265 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001266 case MATCH_WIFI:
1267 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1268 break;
1269 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001270 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001271 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001272 final long overBytes = totalBytes - policy.limitBytes;
1273 body = res.getString(R.string.data_usage_limit_snoozed_body,
1274 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001275
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001276 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001277 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001278 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001279
Wei Liu546cb772016-07-21 16:19:01 -07001280 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001281 builder.setContentIntent(PendingIntent.getActivity(
1282 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001283 break;
1284 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001285 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001286 title = res.getText(R.string.data_usage_rapid_title);
1287 if (rapidBlame != null) {
1288 body = res.getString(R.string.data_usage_rapid_app_body,
1289 rapidBlame.loadLabel(mContext.getPackageManager()));
1290 } else {
1291 body = res.getString(R.string.data_usage_rapid_body);
1292 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001293
Jeff Sharkey2e471452018-01-19 18:02:47 +09001294 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001295
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001296 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1297 builder.setDeleteIntent(PendingIntent.getBroadcast(
1298 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1299
1300 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001301 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001302 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001303 break;
1304 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001305 default: {
1306 return;
1307 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001308 }
1309
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001310 builder.setTicker(title);
1311 builder.setContentTitle(title);
1312 builder.setContentText(body);
1313 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001314
1315 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1316 notificationId.getId(), builder.build(), UserHandle.ALL);
1317 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001318 }
1319
Chris Wren193ae6b2017-03-31 15:17:11 -04001320 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001321 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1322 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001323 }
1324
1325 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001327 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001329 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330 @Override
1331 public void onReceive(Context context, Intent intent) {
1332 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1333 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001334
Hugo Benichi446c9c92017-04-10 09:41:10 +09001335 synchronized (mUidRulesFirstLock) {
1336 synchronized (mNetworkPoliciesSecondLock) {
1337 ensureActiveMobilePolicyAL();
1338 normalizePoliciesNL();
1339 updateNetworkEnabledNL();
1340 updateNetworkRulesNL();
1341 updateNotificationsNL();
1342 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001343 }
1344 }
1345 };
1346
Jeff Sharkey2e471452018-01-19 18:02:47 +09001347 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001348 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001349 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001350 final CountDownLatch latch = new CountDownLatch(1);
1351 mHandler.post(() -> {
1352 latch.countDown();
1353 });
1354 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001355 }
1356
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001357 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001358 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1359 * if necessary.
1360 *
1361 * @param subId that has its associated NetworkPolicy updated if necessary
1362 * @return if any policies were updated
1363 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001364 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1365 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001366
1367 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001368 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1369 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001370
1371 // find and update the mobile NetworkPolicy for this subscriber id
1372 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001373 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001374 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1375 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1376 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001377 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1378 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001379 }
1380 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001381 return policyUpdated;
1382 }
1383
1384 /**
1385 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1386 *
1387 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1388 * to do so, it returns the fallback value.
1389 *
1390 * @param config The CarrierConfig to read the value from.
1391 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1392 * @return cycleDay to use in the mobile NetworkPolicy.
1393 */
1394 @VisibleForTesting
1395 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1396 int fallbackCycleDay) {
1397 if (config == null) {
1398 return fallbackCycleDay;
1399 }
1400 int cycleDay =
1401 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1402 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1403 return fallbackCycleDay;
1404 }
1405 // validate cycleDay value
1406 final Calendar cal = Calendar.getInstance();
1407 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1408 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1409 Slog.e(TAG, "Invalid date in "
1410 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1411 return fallbackCycleDay;
1412 }
1413 return cycleDay;
1414 }
1415
1416 /**
1417 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1418 *
1419 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1420 * to do so, it returns the fallback value.
1421 *
1422 * @param config The CarrierConfig to read the value from.
1423 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1424 * @return warningBytes to use in the mobile NetworkPolicy.
1425 */
1426 @VisibleForTesting
1427 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1428 long fallbackWarningBytes) {
1429 if (config == null) {
1430 return fallbackWarningBytes;
1431 }
1432 long warningBytes =
1433 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1434
1435 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1436 return WARNING_DISABLED;
1437 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1438 return getPlatformDefaultWarningBytes();
1439 } else if (warningBytes < 0) {
1440 Slog.e(TAG, "Invalid value in "
1441 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1442 + "non-negative value but got: " + warningBytes);
1443 return fallbackWarningBytes;
1444 }
1445
1446 return warningBytes;
1447 }
1448
1449 /**
1450 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1451 *
1452 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1453 * to do so, it returns the fallback value.
1454 *
1455 * @param config The CarrierConfig to read the value from.
1456 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1457 * @return limitBytes to use in the mobile NetworkPolicy.
1458 */
1459 @VisibleForTesting
1460 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1461 long fallbackLimitBytes) {
1462 if (config == null) {
1463 return fallbackLimitBytes;
1464 }
1465 long limitBytes =
1466 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1467
1468 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1469 return LIMIT_DISABLED;
1470 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1471 return getPlatformDefaultLimitBytes();
1472 } else if (limitBytes < 0) {
1473 Slog.e(TAG, "Invalid value in "
1474 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1475 + "non-negative value but got: " + limitBytes);
1476 return fallbackLimitBytes;
1477 }
1478 return limitBytes;
1479 }
1480
1481 /**
1482 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1483 */
1484 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1485 @Override
1486 public void onReceive(Context context, Intent intent) {
1487 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1488 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1489
1490 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1491 return;
1492 }
1493 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001494 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001495 final String subscriberId = tele.getSubscriberId(subId);
1496
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001497 synchronized (mUidRulesFirstLock) {
1498 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001499 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001500 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001501 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001502 if (!updated) return;
1503 // update network and notification rules, as the data cycle changed and it's
1504 // possible that we should be triggering warnings/limits now
1505 handleNetworkPoliciesUpdateAL(true);
1506 }
1507 }
1508 }
1509 };
1510
1511 /**
1512 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1513 * one has been updated.
1514 *
1515 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1516 * update.
1517 */
1518 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1519 if (shouldNormalizePolicies) {
1520 normalizePoliciesNL();
1521 }
1522 updateNetworkEnabledNL();
1523 updateNetworkRulesNL();
1524 updateNotificationsNL();
1525 writePolicyAL();
1526 }
1527
1528 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001529 * Proactively control network data connections when they exceed
1530 * {@link NetworkPolicy#limitBytes}.
1531 */
Felipe Lemef0823852016-06-08 13:43:08 -07001532 void updateNetworkEnabledNL() {
1533 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001534
1535 // TODO: reset any policy-disabled networks when any policy is removed
1536 // completely, which is currently rare case.
1537
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001538 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1539 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001540 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001541 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001542 setNetworkTemplateEnabled(policy.template, true);
1543 continue;
1544 }
1545
Jeff Sharkey53313d72017-07-13 16:47:32 -06001546 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1547 .cycleIterator(policy).next();
1548 final long start = cycle.first.toInstant().toEpochMilli();
1549 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001550 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001551
1552 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001553 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1554 && policy.lastLimitSnooze < start;
1555 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001556
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001557 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001558 }
1559 }
1560
1561 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001562 * Proactively disable networks that match the given
1563 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001564 */
1565 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001566 // TODO: reach into ConnectivityManager to proactively disable bringing
1567 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001568
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001569 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001570 // If mobile data usage hits the limit or if the user resumes the data, we need to
1571 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001572 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1573 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001574
Jeff Sharkey2e471452018-01-19 18:02:47 +09001575 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001576 for (int subId : subIds) {
1577 final String subscriberId = tm.getSubscriberId(subId);
1578 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001579 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1580 true);
Jack Yu8781b682016-07-08 14:28:51 -07001581 // Template is matched when subscriber id matches.
1582 if (template.matches(probeIdent)) {
1583 tm.setPolicyDataEnabled(enabled, subId);
1584 }
1585 }
1586 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001587 }
1588
1589 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001590 * Collect all ifaces from a {@link NetworkState} into the given set.
1591 */
1592 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1593 final String baseIface = state.linkProperties.getInterfaceName();
1594 if (baseIface != null) {
1595 ifaces.add(baseIface);
1596 }
1597 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1598 final String stackedIface = stackedLink.getInterfaceName();
1599 if (stackedIface != null) {
1600 ifaces.add(stackedIface);
1601 }
1602 }
1603 }
1604
1605 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001606 * Examine all connected {@link NetworkState}, looking for
1607 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1608 * remaining quota based on usage cycle and historical stats.
1609 */
Felipe Lemef0823852016-06-08 13:43:08 -07001610 void updateNetworkRulesNL() {
1611 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612
1613 final NetworkState[] states;
1614 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001615 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001616 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001617 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001618 return;
1619 }
1620
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001621 // First, generate identities of all connected networks so we can
1622 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001623 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001624 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001626 if (state.network != null) {
1627 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1628 }
Wei Liub8eaf452016-01-25 10:32:27 -08001629 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001630 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1631 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001632 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001633 }
1634 }
1635
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001636 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001637 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001638
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001639 // For every well-defined policy, compute remaining data based on
1640 // current cycle and historical stats, and push to kernel.
1641 final ArraySet<String> matchingIfaces = new ArraySet<>();
1642 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1643 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1644
1645 // Collect all ifaces that match this policy
1646 matchingIfaces.clear();
1647 for (int j = identified.size() - 1; j >= 0; j--) {
1648 if (policy.template.matches(identified.valueAt(j))) {
1649 collectIfaces(matchingIfaces, identified.keyAt(j));
1650 }
1651 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001653 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001654 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655 }
1656
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001657 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001658 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001659 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001660 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001661 if (hasLimit && policy.hasCycle()) {
1662 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1663 .cycleIterator(policy).next();
1664 final long start = cycle.first.toInstant().toEpochMilli();
1665 final long end = cycle.second.toInstant().toEpochMilli();
1666 final long totalBytes = getTotalBytes(policy.template, start, end);
1667
1668 if (policy.lastLimitSnooze >= start) {
1669 // snoozing past quota, but we still need to restrict apps,
1670 // so push really high quota.
1671 quotaBytes = Long.MAX_VALUE;
1672 } else {
1673 // remaining "quota" bytes are based on total usage in
1674 // current cycle. kernel doesn't like 0-byte rules, so we
1675 // set 1-byte quota and disable the radio later.
1676 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1677 }
1678 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001679 // metered network, but no policy limit; we still need to
1680 // restrict apps, so push really high quota.
1681 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001682 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001683
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001684 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001685 // TODO: switch to shared quota once NMS supports
1686 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001687 }
1688
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001689 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1690 final String iface = matchingIfaces.valueAt(j);
1691 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001692 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001693 }
1694 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001695
1696 // keep track of lowest warning or limit of active policies
1697 if (hasWarning && policy.warningBytes < lowestRule) {
1698 lowestRule = policy.warningBytes;
1699 }
1700 if (hasLimit && policy.limitBytes < lowestRule) {
1701 lowestRule = policy.limitBytes;
1702 }
1703 }
1704
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001705 // One final pass to catch any metered ifaces that don't have explicitly
1706 // defined policies; typically Wi-Fi networks.
1707 for (NetworkState state : states) {
1708 if (state.networkInfo != null && state.networkInfo.isConnected()
1709 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1710 matchingIfaces.clear();
1711 collectIfaces(matchingIfaces, state);
1712 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1713 final String iface = matchingIfaces.valueAt(j);
1714 if (!newMeteredIfaces.contains(iface)) {
1715 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1716 newMeteredIfaces.add(iface);
1717 }
1718 }
1719 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001720 }
1721
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001722 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001723 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1724 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001725 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001726 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001727 }
1728 }
1729 mMeteredIfaces = newMeteredIfaces;
1730
Jeff Sharkey9252b342018-01-19 07:58:35 +09001731 // Finally, calculate our opportunistic quotas
1732 // TODO: add experiments support to disable or tweak ratios
1733 mSubscriptionOpportunisticQuota.clear();
1734 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001735 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001736 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001737 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001738 if (plan == null) continue;
1739
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001740 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001741 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001742 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001743 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001744 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001745 // Unlimited data; let's use 20MiB/day (600MiB/month)
1746 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1747 } else {
1748 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001749 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001750 final long start = cycle.first.toInstant().toEpochMilli();
1751 final long end = cycle.second.toInstant().toEpochMilli();
1752 final long totalBytes = getTotalBytes(
1753 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1754 final long remainingBytes = limitBytes - totalBytes;
Jeff Sharkey9911a282018-02-14 22:29:11 -07001755 final long remainingDays = Math.max(1, (end - mClock.millis())
Jeff Sharkey9252b342018-01-19 07:58:35 +09001756 / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001757
1758 quotaBytes = Math.max(0, (remainingBytes / remainingDays) / 10);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001759 }
1760
1761 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1762 }
1763
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001764 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001765 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001766
1767 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001768 }
1769
1770 /**
1771 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1772 * have at least a default mobile policy defined.
1773 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001774 private void ensureActiveMobilePolicyAL() {
1775 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001776 if (mSuppressDefaultPolicy) return;
1777
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001778 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1779 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001780
Jeff Sharkey2e471452018-01-19 18:02:47 +09001781 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001782 for (int subId : subIds) {
1783 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001784 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001785 }
1786 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001787
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001788 /**
1789 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1790 * have at least a default mobile policy defined.
1791 *
1792 * @param subId to build a default policy for
1793 * @param subscriberId that we check for an existing policy
1794 * @return true if a mobile network policy was added, or false one already existed.
1795 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001796 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001797 // Poke around to see if we already have a policy
1798 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001799 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001800 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1801 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1802 if (template.matches(probeIdent)) {
1803 if (LOGD) {
1804 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1805 + NetworkIdentity.scrubSubscriberId(subscriberId));
1806 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001807 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001808 }
1809 }
1810
Jeff Sharkey32566012014-12-02 18:30:14 -08001811 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1812 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001813 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001814 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001815 return true;
1816 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001817
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001818 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001819 final int dataWarningConfig = mContext.getResources().getInteger(
1820 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001821 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001822 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001823 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001824 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001825 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001826 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001827
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001828 private long getPlatformDefaultLimitBytes() {
1829 return LIMIT_DISABLED;
1830 }
1831
1832 @VisibleForTesting
1833 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001834 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001835 final RecurrenceRule cycleRule = NetworkPolicy
1836 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001837 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001838 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1839 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1840 synchronized (mUidRulesFirstLock) {
1841 synchronized (mNetworkPoliciesSecondLock) {
1842 updateDefaultMobilePolicyAL(subId, policy);
1843 }
1844 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001845 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001846 }
1847
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001848 /**
1849 * Update the given {@link NetworkPolicy} based on any carrier-provided
1850 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1851 * Leaves policy untouched if the user has modified it.
1852 *
1853 * @return if the policy was modified
1854 */
1855 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1856 if (!policy.inferred) {
1857 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1858 return false;
1859 }
1860
1861 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1862 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1863 policy.lastLimitSnooze, policy.metered, policy.inferred);
1864
1865 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1866 if (!ArrayUtils.isEmpty(plans)) {
1867 final SubscriptionPlan plan = plans[0];
1868 policy.cycleRule = plan.getCycleRule();
1869 final long planLimitBytes = plan.getDataLimitBytes();
1870 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1871 policy.warningBytes = getPlatformDefaultWarningBytes();
1872 policy.limitBytes = getPlatformDefaultLimitBytes();
1873 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1874 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1875 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1876 } else {
1877 policy.warningBytes = (planLimitBytes * 9) / 10;
1878 switch (plan.getDataLimitBehavior()) {
1879 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1880 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1881 policy.limitBytes = planLimitBytes;
1882 break;
1883 default:
1884 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1885 break;
1886 }
1887 }
1888 } else {
1889 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1890 final int currentCycleDay;
1891 if (policy.cycleRule.isMonthly()) {
1892 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1893 } else {
1894 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1895 }
1896 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1897 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1898 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1899 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1900 }
1901
1902 if (policy.equals(original)) {
1903 return false;
1904 } else {
1905 Slog.d(TAG, "Updated " + original + " to " + policy);
1906 return true;
1907 }
1908 }
1909
Felipe Lemef0823852016-06-08 13:43:08 -07001910 private void readPolicyAL() {
1911 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001912
1913 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001914 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001915 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001916 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001917 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001918
1919 FileInputStream fis = null;
1920 try {
1921 fis = mPolicyFile.openRead();
1922 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001923 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001924
Felipe Leme46b451f2016-08-19 08:46:17 -07001925 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1926 // to skip UIDs that were explicitly blacklisted.
1927 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1928
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001929 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001930 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001931 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001932 while ((type = in.next()) != END_DOCUMENT) {
1933 final String tag = in.getName();
1934 if (type == START_TAG) {
1935 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001936 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001937 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001938 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1939 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001940 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1941 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1942 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001943 final String networkId;
1944 if (version >= VERSION_ADDED_NETWORK_ID) {
1945 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1946 } else {
1947 networkId = null;
1948 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001949 final RecurrenceRule cycleRule;
1950 if (version >= VERSION_ADDED_CYCLE) {
1951 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1952 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1953 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1954 cycleRule = new RecurrenceRule(
1955 RecurrenceRule.convertZonedDateTime(start),
1956 RecurrenceRule.convertZonedDateTime(end),
1957 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001958 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001959 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1960 final String cycleTimezone;
1961 if (version >= VERSION_ADDED_TIMEZONE) {
1962 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1963 } else {
1964 cycleTimezone = "UTC";
1965 }
1966 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001967 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001968 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1969 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001970 final long lastLimitSnooze;
1971 if (version >= VERSION_SPLIT_SNOOZE) {
1972 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1973 } else if (version >= VERSION_ADDED_SNOOZE) {
1974 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001975 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001976 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001977 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001978 final boolean metered;
1979 if (version >= VERSION_ADDED_METERED) {
1980 metered = readBooleanAttribute(in, ATTR_METERED);
1981 } else {
1982 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001983 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001984 metered = true;
1985 break;
1986 default:
1987 metered = false;
1988 }
1989 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001990 final long lastWarningSnooze;
1991 if (version >= VERSION_SPLIT_SNOOZE) {
1992 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1993 } else {
1994 lastWarningSnooze = SNOOZE_NEVER;
1995 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001996 final boolean inferred;
1997 if (version >= VERSION_ADDED_INFERRED) {
1998 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1999 } else {
2000 inferred = false;
2001 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002002
Jeff Sharkey32566012014-12-02 18:30:14 -08002003 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2004 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002005 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002006 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2007 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002008 lastLimitSnooze, metered, inferred));
2009 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002010
2011 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2012 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2013 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2014 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2015 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2016 RecurrenceRule.convertZonedDateTime(start),
2017 RecurrenceRule.convertZonedDateTime(end),
2018 RecurrenceRule.convertPeriod(period));
2019 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2020 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2021
2022 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2023 SubscriptionPlan.BYTES_UNKNOWN);
2024 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2025 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2026 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2027 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2028 builder.setDataLimit(limitBytes, limitBehavior);
2029 }
2030
2031 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2032 SubscriptionPlan.BYTES_UNKNOWN);
2033 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2034 SubscriptionPlan.TIME_UNKNOWN);
2035 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2036 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2037 builder.setDataUsage(usageBytes, usageTime);
2038 }
2039
2040 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2041 final SubscriptionPlan plan = builder.build();
2042 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2043 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2044
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002045 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2046 mSubscriptionPlansOwner.put(subId, ownerPackage);
2047
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002048 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002049 final int uid = readIntAttribute(in, ATTR_UID);
2050 final int policy = readIntAttribute(in, ATTR_POLICY);
2051
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002052 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002053 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002054 } else {
2055 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2056 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002057 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002058 final int appId = readIntAttribute(in, ATTR_APP_ID);
2059 final int policy = readIntAttribute(in, ATTR_POLICY);
2060
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002061 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002062 // app policy is deprecated so this is only used in pre system user split.
2063 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002064 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002065 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002066 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002067 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002068 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002069 } else if (TAG_WHITELIST.equals(tag)) {
2070 insideWhitelist = true;
2071 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2072 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002073 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002074 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2075 final int uid = readIntAttribute(in, ATTR_UID);
2076 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002077 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002078 } else if (type == END_TAG) {
2079 if (TAG_WHITELIST.equals(tag)) {
2080 insideWhitelist = false;
2081 }
2082
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083 }
2084 }
2085
Felipe Leme46b451f2016-08-19 08:46:17 -07002086 final int size = whitelistedRestrictBackground.size();
2087 for (int i = 0; i < size; i++) {
2088 final int uid = whitelistedRestrictBackground.keyAt(i);
2089 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2090 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2091 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2092 + " because its policy is " + uidPoliciesToString(policy));
2093 continue;
2094 }
2095 if (UserHandle.isApp(uid)) {
2096 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2097 if (LOGV)
2098 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2099 setUidPolicyUncheckedUL(uid, newPolicy, false);
2100 } else {
2101 Slog.w(TAG, "unable to update policy on UID " + uid);
2102 }
2103 }
2104
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002105 } catch (FileNotFoundException e) {
2106 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002107 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002108 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002109 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 } finally {
2111 IoUtils.closeQuietly(fis);
2112 }
2113 }
2114
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002115 /**
2116 * Upgrade legacy background data flags, notifying listeners of one last
2117 * change to always-true.
2118 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002119 private void upgradeDefaultBackgroundDataUL() {
2120 // This method is only called when we're unable to find the network policy flag, which
2121 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002122
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002123 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002124 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002125 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2126
2127 // NOTE: We used to read the legacy setting here :
2128 //
2129 // final int legacyFlagValue = Settings.Secure.getInt(
2130 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2131 //
2132 // This is no longer necessary because we will never upgrade directly from Gingerbread
2133 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2134 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002135 }
2136
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002137 /**
2138 * Perform upgrade step of moving any user-defined meterness overrides over
2139 * into {@link WifiConfiguration}.
2140 */
2141 private void upgradeWifiMeteredOverrideAL() {
2142 boolean modified = false;
2143 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2144 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2145 for (int i = 0; i < mNetworkPolicy.size(); ) {
2146 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2147 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2148 && !policy.inferred) {
2149 mNetworkPolicy.removeAt(i);
2150 modified = true;
2151
2152 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2153 for (WifiConfiguration config : configs) {
2154 if (Objects.equals(resolveNetworkId(config), networkId)) {
2155 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2156 config.meteredOverride = policy.metered
2157 ? WifiConfiguration.METERED_OVERRIDE_METERED
2158 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2159 wm.updateNetwork(config);
2160 }
2161 }
2162 } else {
2163 i++;
2164 }
2165 }
2166 if (modified) {
2167 writePolicyAL();
2168 }
2169 }
2170
Felipe Lemef0823852016-06-08 13:43:08 -07002171 void writePolicyAL() {
2172 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173
2174 FileOutputStream fos = null;
2175 try {
2176 fos = mPolicyFile.startWrite();
2177
2178 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002179 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002180 out.startDocument(null, true);
2181
2182 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002183 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002184 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002185
2186 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002187 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2188 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002189 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002190 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002191
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002192 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002193 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2194 final String subscriberId = template.getSubscriberId();
2195 if (subscriberId != null) {
2196 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002197 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002198 final String networkId = template.getNetworkId();
2199 if (networkId != null) {
2200 out.attribute(null, ATTR_NETWORK_ID, networkId);
2201 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002202 writeStringAttribute(out, ATTR_CYCLE_START,
2203 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2204 writeStringAttribute(out, ATTR_CYCLE_END,
2205 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2206 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2207 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002208 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2209 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002210 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2211 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002212 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002213 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002214 out.endTag(null, TAG_NETWORK_POLICY);
2215 }
2216
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002217 // write all known subscription plans
2218 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2219 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002220 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002221 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2222 if (ArrayUtils.isEmpty(plans)) continue;
2223
2224 for (SubscriptionPlan plan : plans) {
2225 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2226 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002227 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002228 final RecurrenceRule cycleRule = plan.getCycleRule();
2229 writeStringAttribute(out, ATTR_CYCLE_START,
2230 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2231 writeStringAttribute(out, ATTR_CYCLE_END,
2232 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2233 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2234 RecurrenceRule.convertPeriod(cycleRule.period));
2235 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2236 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2237 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2238 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2239 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2240 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2241 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2242 }
2243 }
2244
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002245 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002246 for (int i = 0; i < mUidPolicy.size(); i++) {
2247 final int uid = mUidPolicy.keyAt(i);
2248 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002249
Jeff Sharkey497e4432011-06-14 17:27:29 -07002250 // skip writing empty policies
2251 if (policy == POLICY_NONE) continue;
2252
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002253 out.startTag(null, TAG_UID_POLICY);
2254 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002255 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002257 }
2258
2259 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002260
2261 // write all whitelists
2262 out.startTag(null, TAG_WHITELIST);
2263
Felipe Lemea9505cc2016-02-26 10:28:41 -08002264 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002265 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002266 for (int i = 0; i < size; i++) {
2267 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2268 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2269 writeIntAttribute(out, ATTR_UID, uid);
2270 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2271 }
2272
Felipe Lemeb85a6372016-01-14 16:16:16 -08002273 out.endTag(null, TAG_WHITELIST);
2274
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002275 out.endDocument();
2276
2277 mPolicyFile.finishWrite(fos);
2278 } catch (IOException e) {
2279 if (fos != null) {
2280 mPolicyFile.failWrite(fos);
2281 }
2282 }
2283 }
2284
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002285 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002286 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002287 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002288
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002289 if (!UserHandle.isApp(uid)) {
2290 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002291 }
Felipe Lemef0823852016-06-08 13:43:08 -07002292 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002293 final long token = Binder.clearCallingIdentity();
2294 try {
2295 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2296 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002297 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002298 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002299 }
2300 } finally {
2301 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002302 }
2303 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002304 }
2305
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002306 @Override
2307 public void addUidPolicy(int uid, int policy) {
2308 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002309
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002310 if (!UserHandle.isApp(uid)) {
2311 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2312 }
2313
Felipe Lemef0823852016-06-08 13:43:08 -07002314 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002315 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2316 policy |= oldPolicy;
2317 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002318 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002319 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002320 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002321 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002322 }
2323
2324 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002325 public void removeUidPolicy(int uid, int policy) {
2326 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2327
2328 if (!UserHandle.isApp(uid)) {
2329 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2330 }
2331
Felipe Lemef0823852016-06-08 13:43:08 -07002332 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002333 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2334 policy = oldPolicy & ~policy;
2335 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002336 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002337 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002338 }
2339 }
2340 }
2341
Felipe Lemef0823852016-06-08 13:43:08 -07002342 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2343 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002344
Felipe Leme57e3d312016-08-23 14:42:52 -07002345 final boolean notifyApp;
2346 if (!isUidValidForWhitelistRules(uid)) {
2347 notifyApp = false;
2348 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002349 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2350 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2351 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2352 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002353 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2354 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002355 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2356 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2357 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2358 if (LOGD)
2359 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2360 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2361 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002362 notifyApp = wasBlocked != isBlocked;
2363 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002364 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2365 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002366 }
2367
Felipe Lemef0823852016-06-08 13:43:08 -07002368 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002369 if (policy == POLICY_NONE) {
2370 mUidPolicy.delete(uid);
2371 } else {
2372 mUidPolicy.put(uid, policy);
2373 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002374
2375 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002376 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002377 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002378 synchronized (mNetworkPoliciesSecondLock) {
2379 writePolicyAL();
2380 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002381 }
2382 }
2383
2384 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002385 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002386 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2387
Felipe Lemef0823852016-06-08 13:43:08 -07002388 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002389 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002390 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002391 }
2392
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002393 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002394 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002395 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2396
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002397 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002398 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002399 for (int i = 0; i < mUidPolicy.size(); i++) {
2400 final int uid = mUidPolicy.keyAt(i);
2401 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002402 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2403 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002404 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002405 }
2406 }
2407 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002408 return uids;
2409 }
2410
2411 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002412 * Removes any persistable state associated with given {@link UserHandle}, persisting
2413 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002414 */
Felipe Lemef0823852016-06-08 13:43:08 -07002415 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002416
Sudheer Shanka352dc572017-09-22 17:09:38 -07002417 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002418 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002419
Felipe Lemea110eec2016-04-29 09:58:06 -07002420 // Remove entries from revoked default restricted background UID whitelist
2421 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2422 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2423 if (UserHandle.getUserId(uid) == userId) {
2424 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002425 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002426 }
2427 }
2428
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002429 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002430 int[] uids = new int[0];
2431 for (int i = 0; i < mUidPolicy.size(); i++) {
2432 final int uid = mUidPolicy.keyAt(i);
2433 if (UserHandle.getUserId(uid) == userId) {
2434 uids = appendInt(uids, uid);
2435 }
2436 }
2437
2438 if (uids.length > 0) {
2439 for (int uid : uids) {
2440 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002441 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002442 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002443 }
Felipe Lemef0823852016-06-08 13:43:08 -07002444 synchronized (mNetworkPoliciesSecondLock) {
2445 updateRulesForGlobalChangeAL(true);
2446 if (writePolicy && changed) {
2447 writePolicyAL();
2448 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002449 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002450 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002451 }
2452
2453 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002454 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002455 // TODO: create permission for observing network policy
2456 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002457 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002458 }
2459
2460 @Override
2461 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002462 // TODO: create permission for observing network policy
2463 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002464 mListeners.unregister(listener);
2465 }
2466
Jeff Sharkey1b861272011-05-22 00:34:52 -07002467 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002468 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002469 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2470
Felipe Leme6a05eee2016-02-19 14:43:51 -08002471 final long token = Binder.clearCallingIdentity();
2472 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002473 synchronized (mUidRulesFirstLock) {
2474 synchronized (mNetworkPoliciesSecondLock) {
2475 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002476 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002477 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002478 }
2479 } finally {
2480 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002481 }
2482 }
2483
Hugo Benichi446c9c92017-04-10 09:41:10 +09002484 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002485 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002486 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2487 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002488 }
2489
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002490 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002491 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002492 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002493 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002494 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2495 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2496 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002497 } catch (SecurityException e) {
2498 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002499
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002500 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2501 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2502 return new NetworkPolicy[0];
2503 }
Svet Ganov16a16892015-04-16 10:32:04 -07002504 }
2505
Felipe Lemef0823852016-06-08 13:43:08 -07002506 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002507 final int size = mNetworkPolicy.size();
2508 final NetworkPolicy[] policies = new NetworkPolicy[size];
2509 for (int i = 0; i < size; i++) {
2510 policies[i] = mNetworkPolicy.valueAt(i);
2511 }
2512 return policies;
2513 }
2514 }
2515
Felipe Lemef0823852016-06-08 13:43:08 -07002516 private void normalizePoliciesNL() {
2517 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002518 }
2519
Felipe Lemef0823852016-06-08 13:43:08 -07002520 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002521 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002522 final String[] merged = tele.getMergedSubscriberIds();
2523
2524 mNetworkPolicy.clear();
2525 for (NetworkPolicy policy : policies) {
2526 // When two normalized templates conflict, prefer the most
2527 // restrictive policy
2528 policy.template = NetworkTemplate.normalize(policy.template, merged);
2529 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2530 if (existing == null || existing.compareTo(policy) > 0) {
2531 if (existing != null) {
2532 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2533 }
2534 mNetworkPolicy.put(policy.template, policy);
2535 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002536 }
2537 }
2538
2539 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002540 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002541 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002542
2543 final long token = Binder.clearCallingIdentity();
2544 try {
2545 performSnooze(template, TYPE_LIMIT);
2546 } finally {
2547 Binder.restoreCallingIdentity(token);
2548 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002549 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002550
Dianne Hackborn497175b2014-07-01 12:56:08 -07002551 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002552 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002553 synchronized (mUidRulesFirstLock) {
2554 synchronized (mNetworkPoliciesSecondLock) {
2555 // find and snooze local policy that matches
2556 final NetworkPolicy policy = mNetworkPolicy.get(template);
2557 if (policy == null) {
2558 throw new IllegalArgumentException("unable to find policy for " + template);
2559 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002560
Felipe Lemef0823852016-06-08 13:43:08 -07002561 switch (type) {
2562 case TYPE_WARNING:
2563 policy.lastWarningSnooze = currentTime;
2564 break;
2565 case TYPE_LIMIT:
2566 policy.lastLimitSnooze = currentTime;
2567 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002568 case TYPE_RAPID:
2569 policy.lastRapidSnooze = currentTime;
2570 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002571 default:
2572 throw new IllegalArgumentException("unexpected type");
2573 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002574
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002575 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002576 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002577 }
2578 }
2579
2580 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002581 public void onTetheringChanged(String iface, boolean tethering) {
2582 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002583 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002584 if (mRestrictBackground && tethering) {
2585 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2586 setRestrictBackground(false);
2587 }
2588 }
2589 }
2590
2591 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002592 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002593 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002594 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002595 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2596 final long token = Binder.clearCallingIdentity();
2597 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002598 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002599 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002600 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002601 } finally {
2602 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002603 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002604 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002605 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002606 }
2607 }
2608
Felipe Lemef0823852016-06-08 13:43:08 -07002609 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002610 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002611 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002612 if (restrictBackground == mRestrictBackground) {
2613 // Ideally, UI should never allow this scenario...
2614 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002615 return;
2616 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002617 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2618 final boolean oldRestrictBackground = mRestrictBackground;
2619 mRestrictBackground = restrictBackground;
2620 // Must whitelist foreground apps before turning data saver mode on.
2621 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2622 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2623 updateRulesForRestrictBackgroundUL();
2624 try {
2625 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2626 Slog.e(TAG,
2627 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2628 mRestrictBackground = oldRestrictBackground;
2629 // TODO: if it knew the foreground apps (see TODO above), it could call
2630 // updateRulesForRestrictBackgroundUL() again to restore state.
2631 return;
2632 }
2633 } catch (RemoteException e) {
2634 // ignored; service lives in system_server
2635 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002636
Sudheer Shanka543339f2017-07-28 15:18:07 -07002637 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002638 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002639
2640 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2641 mRestrictBackgroundChangedInBsm = true;
2642 }
2643 synchronized (mNetworkPoliciesSecondLock) {
2644 updateNotificationsNL();
2645 writePolicyAL();
2646 }
2647 } finally {
2648 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002649 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002650 }
2651
2652 private void sendRestrictBackgroundChangedMsg() {
2653 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2654 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2655 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002656 }
2657
Felipe Lemeb85a6372016-01-14 16:16:16 -08002658 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002659 public int getRestrictBackgroundByCaller() {
2660 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2661 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002662
Felipe Lemef0823852016-06-08 13:43:08 -07002663 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002664 // Must clear identity because getUidPolicy() is restricted to system.
2665 final long token = Binder.clearCallingIdentity();
2666 final int policy;
2667 try {
2668 policy = getUidPolicy(uid);
2669 } finally {
2670 Binder.restoreCallingIdentity(token);
2671 }
2672 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2673 // App is blacklisted.
2674 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2675 }
Felipe Leme1b103232016-01-22 09:44:57 -08002676 if (!mRestrictBackground) {
2677 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2678 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002679 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002680 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2681 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2682 }
2683 }
2684
2685 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002686 public boolean getRestrictBackground() {
2687 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2688
Felipe Lemef0823852016-06-08 13:43:08 -07002689 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002690 return mRestrictBackground;
2691 }
2692 }
2693
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002694 @Override
2695 public void setDeviceIdleMode(boolean enabled) {
2696 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002697 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2698 try {
2699 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002700 if (mDeviceIdleMode == enabled) {
2701 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002702 }
Felipe Lemeea014392016-09-06 13:59:54 -07002703 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002704 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002705 if (mSystemReady) {
2706 // Device idle change means we need to rebuild rules for all
2707 // known apps, so do a global refresh.
2708 updateRulesForRestrictPowerUL();
2709 }
2710 }
2711 if (enabled) {
2712 EventLogTags.writeDeviceIdleOnPhase("net");
2713 } else {
2714 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002715 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002716 } finally {
2717 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002718 }
2719 }
2720
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002721 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002722 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2723 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002724 final long token = Binder.clearCallingIdentity();
2725 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002726 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2727 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2728 for (WifiConfiguration config : configs) {
2729 if (Objects.equals(resolveNetworkId(config), networkId)) {
2730 config.meteredOverride = meteredOverride;
2731 wm.updateNetwork(config);
2732 }
2733 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002734 } finally {
2735 Binder.restoreCallingIdentity(token);
2736 }
2737 }
2738
Jeff Sharkey46645002011-07-27 21:11:21 -07002739 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002740 @Deprecated
2741 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2742 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2743 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2744 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002745 }
2746
Jeff Sharkey53313d72017-07-13 16:47:32 -06002747 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2748 // Verify they're not lying about package name
2749 mAppOps.checkPackage(callingUid, callingPackage);
2750
Jeff Sharkey53313d72017-07-13 16:47:32 -06002751 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002752 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002753 final long token = Binder.clearCallingIdentity();
2754 try {
2755 si = mContext.getSystemService(SubscriptionManager.class)
2756 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002757 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002758 } finally {
2759 Binder.restoreCallingIdentity(token);
2760 }
2761
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002762 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002763 if (si != null) {
2764 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2765 return;
2766 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002767 }
2768
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002769 // Second check: has the CarrierService delegated access?
2770 if (config != null) {
2771 final String overridePackage = config
2772 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2773 if (!TextUtils.isEmpty(overridePackage)
2774 && Objects.equals(overridePackage, callingPackage)) {
2775 return;
2776 }
2777 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002778
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002779 // Third check: is caller the fallback/default CarrierService?
2780 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2781 if (!TextUtils.isEmpty(defaultPackage)
2782 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002783 return;
2784 }
2785
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002786 // Fourth check: is caller a testing app on a debug build?
2787 final boolean enableDebug = Build.IS_USERDEBUG || Build.IS_ENG;
2788 if (enableDebug && callingPackage
2789 .equals(SystemProperties.get("fw.sub_plan_owner." + subId, null))) {
2790 return;
2791 }
2792
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002793 // Final check: does the caller hold a permission?
2794 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002795 }
2796
2797 @Override
2798 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2799 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2800
Jeff Sharkey53313d72017-07-13 16:47:32 -06002801 final String fake = SystemProperties.get("fw.fake_plan");
2802 if (!TextUtils.isEmpty(fake)) {
2803 final List<SubscriptionPlan> plans = new ArrayList<>();
2804 if ("month_hard".equals(fake)) {
2805 plans.add(SubscriptionPlan.Builder
2806 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2807 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002808 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2809 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2810 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2811 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2812 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002813 plans.add(SubscriptionPlan.Builder
2814 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2815 .setTitle("G-Mobile Happy")
2816 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2817 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2818 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2819 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2820 .build());
2821 plans.add(SubscriptionPlan.Builder
2822 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2823 .setTitle("G-Mobile, Charged after limit")
2824 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2825 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2826 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2827 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2828 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002829 } else if ("month_soft".equals(fake)) {
2830 plans.add(SubscriptionPlan.Builder
2831 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2832 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2833 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2834 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002835 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2836 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2837 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2838 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2839 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002840 plans.add(SubscriptionPlan.Builder
2841 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2842 .setTitle("G-Mobile, Throttled after limit")
2843 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2844 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2845 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2846 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2847 .build());
2848 plans.add(SubscriptionPlan.Builder
2849 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2850 .setTitle("G-Mobile, No data connection after limit")
2851 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2852 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2853 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2854 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2855 .build());
2856
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002857 } else if ("month_over".equals(fake)) {
2858 plans.add(SubscriptionPlan.Builder
2859 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2860 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2861 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2862 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2863 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2864 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2865 .build());
2866 plans.add(SubscriptionPlan.Builder
2867 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2868 .setTitle("G-Mobile, Throttled after limit")
2869 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2870 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2871 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2872 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2873 .build());
2874 plans.add(SubscriptionPlan.Builder
2875 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2876 .setTitle("G-Mobile, No data connection after limit")
2877 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2878 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2879 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2880 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2881 .build());
2882
Jeff Sharkey53313d72017-07-13 16:47:32 -06002883 } else if ("month_none".equals(fake)) {
2884 plans.add(SubscriptionPlan.Builder
2885 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2886 .setTitle("G-Mobile")
2887 .build());
2888 } else if ("prepaid".equals(fake)) {
2889 plans.add(SubscriptionPlan.Builder
2890 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2891 ZonedDateTime.now().plusDays(10))
2892 .setTitle("G-Mobile")
2893 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2894 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2895 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2896 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2897 .build());
2898 } else if ("prepaid_crazy".equals(fake)) {
2899 plans.add(SubscriptionPlan.Builder
2900 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2901 ZonedDateTime.now().plusDays(10))
2902 .setTitle("G-Mobile Anytime")
2903 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2904 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2905 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2906 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2907 .build());
2908 plans.add(SubscriptionPlan.Builder
2909 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2910 ZonedDateTime.now().plusDays(20))
2911 .setTitle("G-Mobile Nickel Nights")
2912 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002913 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2914 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002915 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2916 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2917 .build());
2918 plans.add(SubscriptionPlan.Builder
2919 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2920 ZonedDateTime.now().plusDays(20))
2921 .setTitle("G-Mobile Bonus 3G")
2922 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002923 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002924 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2925 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2926 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2927 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002928 } else if ("unlimited".equals(fake)) {
2929 plans.add(SubscriptionPlan.Builder
2930 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2931 ZonedDateTime.now().plusDays(10))
2932 .setTitle("G-Mobile Awesome")
2933 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2934 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2935 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2936 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2937 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002938 }
2939 return plans.toArray(new SubscriptionPlan[plans.size()]);
2940 }
2941
Jeff Sharkey4635f102017-09-01 11:27:13 -06002942 synchronized (mNetworkPoliciesSecondLock) {
2943 // Only give out plan details to the package that defined them,
2944 // so that we don't risk leaking plans between apps. We always
2945 // let in core system components (like the Settings app).
2946 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2947 if (Objects.equals(ownerPackage, callingPackage)
2948 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2949 return mSubscriptionPlans.get(subId);
2950 } else {
2951 Log.w(TAG, "Not returning plans because caller " + callingPackage
2952 + " doesn't match owner " + ownerPackage);
2953 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002954 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002955 }
2956 }
2957
2958 @Override
2959 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2960 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2961
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002962 for (SubscriptionPlan plan : plans) {
2963 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002964 }
2965
2966 final long token = Binder.clearCallingIdentity();
2967 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002968 synchronized (mUidRulesFirstLock) {
2969 synchronized (mNetworkPoliciesSecondLock) {
2970 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002971 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002972
2973 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2974 .getSubscriberId(subId);
2975 ensureActiveMobilePolicyAL(subId, subscriberId);
2976 maybeUpdateMobilePolicyCycleAL(subId);
2977 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002978 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002979 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002980
2981 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2982 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2983 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2984 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002985 } finally {
2986 Binder.restoreCallingIdentity(token);
2987 }
2988 }
2989
2990 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002991 public String getSubscriptionPlansOwner(int subId) {
2992 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2993 throw new SecurityException();
2994 }
2995
2996 synchronized (mNetworkPoliciesSecondLock) {
2997 return mSubscriptionPlansOwner.get(subId);
2998 }
2999 }
3000
3001 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003002 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3003 long timeoutMillis, String callingPackage) {
3004 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3005
3006 // We can only override when carrier told us about plans
3007 synchronized (mNetworkPoliciesSecondLock) {
3008 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3009 throw new IllegalStateException(
3010 "Must provide SubscriptionPlan information before overriding");
3011 }
3012 }
3013
3014 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3015 overrideMask, overrideValue, subId));
3016 if (timeoutMillis > 0) {
3017 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3018 overrideMask, 0, subId), timeoutMillis);
3019 }
3020 }
3021
3022 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003023 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003024 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003025
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003026 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3027
Dianne Hackborn497175b2014-07-01 12:56:08 -07003028 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003029 for (String arg : args) {
3030 argSet.add(arg);
3031 }
3032
Felipe Lemef0823852016-06-08 13:43:08 -07003033 synchronized (mUidRulesFirstLock) {
3034 synchronized (mNetworkPoliciesSecondLock) {
3035 if (argSet.contains("--unsnooze")) {
3036 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3037 mNetworkPolicy.valueAt(i).clearSnooze();
3038 }
3039
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003040 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003041
3042 fout.println("Cleared snooze timestamps");
3043 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003044 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003045
Felipe Lemef0823852016-06-08 13:43:08 -07003046 fout.print("System ready: "); fout.println(mSystemReady);
3047 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3048 fout.print("Restrict power: "); fout.println(mRestrictPower);
3049 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003050 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3051
3052 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003053 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003054 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003055 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3056 fout.println(mNetworkPolicy.valueAt(i).toString());
3057 }
3058 fout.decreaseIndent();
3059
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003060 fout.println();
3061 fout.println("Subscription plans:");
3062 fout.increaseIndent();
3063 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3064 final int subId = mSubscriptionPlans.keyAt(i);
3065 fout.println("Subscriber ID " + subId + ":");
3066 fout.increaseIndent();
3067 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3068 if (!ArrayUtils.isEmpty(plans)) {
3069 for (SubscriptionPlan plan : plans) {
3070 fout.println(plan);
3071 }
3072 }
3073 fout.decreaseIndent();
3074 }
3075 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003076
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003077 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003078 fout.println("Policy for UIDs:");
3079 fout.increaseIndent();
3080 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003081 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003082 final int uid = mUidPolicy.keyAt(i);
3083 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003084 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003085 fout.print(uid);
3086 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003087 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003088 fout.println();
3089 }
3090 fout.decreaseIndent();
3091
3092 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3093 if (size > 0) {
3094 fout.println("Power save whitelist (except idle) app ids:");
3095 fout.increaseIndent();
3096 for (int i = 0; i < size; i++) {
3097 fout.print("UID=");
3098 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3099 fout.print(": ");
3100 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3101 fout.println();
3102 }
3103 fout.decreaseIndent();
3104 }
3105
3106 size = mPowerSaveWhitelistAppIds.size();
3107 if (size > 0) {
3108 fout.println("Power save whitelist app ids:");
3109 fout.increaseIndent();
3110 for (int i = 0; i < size; i++) {
3111 fout.print("UID=");
3112 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3113 fout.print(": ");
3114 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3115 fout.println();
3116 }
3117 fout.decreaseIndent();
3118 }
3119
Felipe Lemef0823852016-06-08 13:43:08 -07003120 size = mDefaultRestrictBackgroundWhitelistUids.size();
3121 if (size > 0) {
3122 fout.println("Default restrict background whitelist uids:");
3123 fout.increaseIndent();
3124 for (int i = 0; i < size; i++) {
3125 fout.print("UID=");
3126 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3127 fout.println();
3128 }
3129 fout.decreaseIndent();
3130 }
3131
3132 size = mRestrictBackgroundWhitelistRevokedUids.size();
3133 if (size > 0) {
3134 fout.println("Default restrict background whitelist uids revoked by users:");
3135 fout.increaseIndent();
3136 for (int i = 0; i < size; i++) {
3137 fout.print("UID=");
3138 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3139 fout.println();
3140 }
3141 fout.decreaseIndent();
3142 }
3143
3144 final SparseBooleanArray knownUids = new SparseBooleanArray();
3145 collectKeys(mUidState, knownUids);
3146 collectKeys(mUidRules, knownUids);
3147
3148 fout.println("Status for all known UIDs:");
3149 fout.increaseIndent();
3150 size = knownUids.size();
3151 for (int i = 0; i < size; i++) {
3152 final int uid = knownUids.keyAt(i);
3153 fout.print("UID=");
3154 fout.print(uid);
3155
3156 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3157 fout.print(" state=");
3158 fout.print(state);
3159 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3160 fout.print(" (fg)");
3161 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003162 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003163 ? " (fg svc)" : " (bg)");
3164 }
3165
3166 final int uidRules = mUidRules.get(uid, RULE_NONE);
3167 fout.print(" rules=");
3168 fout.print(uidRulesToString(uidRules));
3169 fout.println();
3170 }
3171 fout.decreaseIndent();
3172
3173 fout.println("Status for just UIDs with rules:");
3174 fout.increaseIndent();
3175 size = mUidRules.size();
3176 for (int i = 0; i < size; i++) {
3177 final int uid = mUidRules.keyAt(i);
3178 fout.print("UID=");
3179 fout.print(uid);
3180 final int uidRules = mUidRules.get(uid, RULE_NONE);
3181 fout.print(" rules=");
3182 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003183 fout.println();
3184 }
3185 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003186
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003187 fout.println("Admin restricted uids for metered data:");
3188 fout.increaseIndent();
3189 size = mMeteredRestrictedUids.size();
3190 for (int i = 0; i < size; ++i) {
3191 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3192 fout.println(mMeteredRestrictedUids.valueAt(i));
3193 }
3194 fout.decreaseIndent();
3195
Sudheer Shanka352dc572017-09-22 17:09:38 -07003196 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003197 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003198 }
3199 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003200
3201 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003202 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003203 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003204 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003205 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003206 }
3207
3208 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003209 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003210 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3211
Felipe Lemef0823852016-06-08 13:43:08 -07003212 synchronized (mUidRulesFirstLock) {
3213 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003214 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003215 }
3216
Felipe Lemef0823852016-06-08 13:43:08 -07003217 private boolean isUidForegroundUL(int uid) {
3218 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003219 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3220 }
3221
Felipe Lemef0823852016-06-08 13:43:08 -07003222 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003223 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003224 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003225 }
3226
Felipe Lemef0823852016-06-08 13:43:08 -07003227 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003228 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3229 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3230 }
3231
Felipe Lemef0823852016-06-08 13:43:08 -07003232 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003233 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003234 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003235 }
3236
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003237 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003238 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003239 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3240 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003241 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003242 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003243 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3244 try {
3245 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3246 if (oldUidState != uidState) {
3247 // state changed, push updated rules
3248 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003249 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3250 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3251 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003252 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003253 if (mDeviceIdleMode) {
3254 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003255 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003256 if (mRestrictPower) {
3257 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003258 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003259 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003260 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003261 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003262 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003263 } finally {
3264 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003265 }
3266 }
3267
Felipe Lemef0823852016-06-08 13:43:08 -07003268 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003269 final int index = mUidState.indexOfKey(uid);
3270 if (index >= 0) {
3271 final int oldUidState = mUidState.valueAt(index);
3272 mUidState.removeAt(index);
3273 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003274 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003275 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003276 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003277 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003278 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003279 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003280 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003281 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003282 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003283 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003284 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003285 }
3286 }
3287
Felipe Lemef28983d2016-03-25 12:18:23 -07003288 // adjust stats accounting based on foreground status
3289 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003290 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3291 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3292 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3293 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003294 try {
3295 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003296 } finally {
3297 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003298 }
3299 }
3300
Sudheer Shankac9d94072017-02-22 22:13:55 +00003301 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3302 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003303 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003304 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003305 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003306 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003307 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003308 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003309 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003310 }
3311
Felipe Lemef0823852016-06-08 13:43:08 -07003312 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003313 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3314 try {
3315 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3316 mUidFirewallPowerSaveRules);
3317 } finally {
3318 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3319 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003320 }
3321
Felipe Lemef0823852016-06-08 13:43:08 -07003322 void updateRuleForRestrictPowerUL(int uid) {
3323 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003324 }
3325
Felipe Lemef0823852016-06-08 13:43:08 -07003326 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003327 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3328 try {
3329 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3330 mUidFirewallDozableRules);
3331 } finally {
3332 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3333 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003334 }
3335
Felipe Lemef0823852016-06-08 13:43:08 -07003336 void updateRuleForDeviceIdleUL(int uid) {
3337 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003338 }
3339
Felipe Lemef28983d2016-03-25 12:18:23 -07003340 // NOTE: since both fw_dozable and fw_powersave uses the same map
3341 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003342 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003343 SparseIntArray rules) {
3344 if (enabled) {
3345 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003346 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003347 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003348 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003349 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003350 for (int ui = users.size() - 1; ui >= 0; ui--) {
3351 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003352 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3353 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3354 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3355 updateRulesForWhitelistedAppIds(uidRules,
3356 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003357 }
3358 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003359 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003360 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003361 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3362 }
3363 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003364 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003365 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003366 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003367 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003368 }
3369
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003370 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3371 final SparseBooleanArray whitelistedAppIds, int userId) {
3372 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3373 if (whitelistedAppIds.valueAt(i)) {
3374 final int appId = whitelistedAppIds.keyAt(i);
3375 final int uid = UserHandle.getUid(userId, appId);
3376 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3377 }
3378 }
3379 }
3380
3381 /**
3382 * @param deviceIdleMode if true then we don't consider
3383 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3384 * whitelisted.
3385 */
3386 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003387 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003388 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3389 || mPowerSaveWhitelistAppIds.get(appId);
3390 if (!deviceIdleMode) {
3391 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3392 }
3393 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003394 }
3395
Felipe Lemef28983d2016-03-25 12:18:23 -07003396 // NOTE: since both fw_dozable and fw_powersave uses the same map
3397 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003398 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003399 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003400 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3401 chain == FIREWALL_CHAIN_DOZABLE);
3402 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003403 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003404 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003405 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003406 }
3407 }
3408 }
3409
Felipe Lemef0823852016-06-08 13:43:08 -07003410 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003411 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3412 try {
3413 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3414 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003415
Felipe Leme873a83a2016-09-07 11:34:10 -07003416 // Fully update the app idle firewall chain.
3417 final List<UserInfo> users = mUserManager.getUsers();
3418 for (int ui = users.size() - 1; ui >= 0; ui--) {
3419 UserInfo user = users.get(ui);
3420 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3421 for (int uid : idleUids) {
3422 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3423 // quick check: if this uid doesn't have INTERNET permission, it
3424 // doesn't have network access anyway, so it is a waste to mess
3425 // with it here.
3426 if (hasInternetPermissions(uid)) {
3427 uidRules.put(uid, FIREWALL_RULE_DENY);
3428 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003429 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003430 }
3431 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003432
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003433 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003434 } finally {
3435 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3436 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003437 }
3438
Felipe Lemef0823852016-06-08 13:43:08 -07003439 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003440 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003441
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003442 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3443 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3444 }
3445 try {
3446 int appId = UserHandle.getAppId(uid);
3447 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3448 && !isUidForegroundOnRestrictPowerUL(uid)) {
3449 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3450 } else {
3451 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3452 }
3453 } finally {
3454 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003455 }
3456 }
3457
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003458 /**
3459 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3460 * changed.
3461 */
Felipe Lemef0823852016-06-08 13:43:08 -07003462 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003463 boolean paroled = mUsageStats.isAppIdleParoleOn();
3464 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003465 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003466
3467 int ruleCount = mUidFirewallStandbyRules.size();
3468 for (int i = 0; i < ruleCount; i++) {
3469 int uid = mUidFirewallStandbyRules.keyAt(i);
3470 int oldRules = mUidRules.get(uid);
3471 if (enableChain) {
3472 // Chain wasn't enabled before and the other power-related
3473 // chains are whitelists, so we can clear the
3474 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3475 // the effective rules result in blocking network access.
3476 oldRules &= MASK_METERED_NETWORKS;
3477 } else {
3478 // Skip if it had no restrictions to begin with
3479 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3480 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003481 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3482 if (newUidRules == RULE_NONE) {
3483 mUidRules.delete(uid);
3484 } else {
3485 mUidRules.put(uid, newUidRules);
3486 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003487 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003488 }
3489
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003490 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003491 * Update rules that might be changed by {@link #mRestrictBackground},
3492 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003493 */
Felipe Lemef0823852016-06-08 13:43:08 -07003494 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003495 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3496 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3497 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3498 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003499 try {
Felipe Leme09700462016-09-08 09:33:48 -07003500 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003501 updateRulesForRestrictPowerUL();
3502 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003503
Felipe Leme873a83a2016-09-07 11:34:10 -07003504 // If the set of restricted networks may have changed, re-evaluate those.
3505 if (restrictedNetworksChanged) {
3506 normalizePoliciesNL();
3507 updateNetworkRulesNL();
3508 }
3509 } finally {
3510 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003511 }
3512 }
3513
Felipe Leme09700462016-09-08 09:33:48 -07003514 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003515 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003516 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3517 try {
3518 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003519 updateRulesForPowerSaveUL();
3520 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3521 } finally {
3522 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3523 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003524 }
3525
Felipe Lemef0823852016-06-08 13:43:08 -07003526 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003527 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3528 try {
3529 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3530 } finally {
3531 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3532 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003533 }
3534
3535 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3536 private static final int TYPE_RESTRICT_POWER = 2;
3537 @Retention(RetentionPolicy.SOURCE)
3538 @IntDef(flag = false, value = {
3539 TYPE_RESTRICT_BACKGROUND,
3540 TYPE_RESTRICT_POWER,
3541 })
3542 public @interface RestrictType {
3543 }
3544
3545 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003546 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003547 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3548 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3549 }
3550 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003551 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003552
3553 final PackageManager pm = mContext.getPackageManager();
3554 final List<UserInfo> users;
3555 final List<ApplicationInfo> apps;
3556
3557 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3558 try {
3559 users = mUserManager.getUsers();
3560 } finally {
3561 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3562 }
3563 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3564 try {
3565 apps = pm.getInstalledApplications(
3566 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3567 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3568 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3569 } finally {
3570 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3571 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003572
Felipe Leme873a83a2016-09-07 11:34:10 -07003573 final int usersSize = users.size();
3574 final int appsSize = apps.size();
3575 for (int i = 0; i < usersSize; i++) {
3576 final UserInfo user = users.get(i);
3577 for (int j = 0; j < appsSize; j++) {
3578 final ApplicationInfo app = apps.get(j);
3579 final int uid = UserHandle.getUid(user.id, app.uid);
3580 switch (type) {
3581 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003582 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003583 break;
3584 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003585 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003586 break;
3587 default:
3588 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3589 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003590 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003591 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003592 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003593 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003594 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003595 }
3596
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003597 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003598 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003599 final int numUsers = users.size();
3600 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003601 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003602 int uid = UserHandle.getUid(user.id, appId);
3603 // Update external firewall rules.
3604 updateRuleForAppIdleUL(uid);
3605 updateRuleForDeviceIdleUL(uid);
3606 updateRuleForRestrictPowerUL(uid);
3607 // Update internal rules.
3608 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003609 }
3610 }
3611
Felipe Leme70c57c22016-03-29 10:45:13 -07003612 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3613 // methods below could be merged into a isUidValidForRules() method.
3614 private boolean isUidValidForBlacklistRules(int uid) {
3615 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003616 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003617 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003618 return true;
3619 }
3620
3621 return false;
3622 }
3623
Felipe Leme70c57c22016-03-29 10:45:13 -07003624 private boolean isUidValidForWhitelistRules(int uid) {
3625 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3626 }
3627
Amith Yamasani15e472352015-04-24 19:06:07 -07003628 private boolean isUidIdle(int uid) {
3629 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3630 final int userId = UserHandle.getUserId(uid);
3631
songjinshi0655edd2016-05-18 19:55:32 +08003632 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003633 for (String packageName : packages) {
3634 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3635 return false;
3636 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003637 }
3638 }
3639 return true;
3640 }
3641
3642 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003643 * Checks if an uid has INTERNET permissions.
3644 * <p>
3645 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003646 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003647 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003648 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003649 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003650 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003651 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003652 }
3653 } catch (RemoteException e) {
3654 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003655 return true;
3656 }
3657
3658 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003659 * Clears all state - internal and external - associated with an UID.
3660 */
3661 private void onUidDeletedUL(int uid) {
3662 // First cleanup in-memory state synchronously...
3663 mUidRules.delete(uid);
3664 mUidPolicy.delete(uid);
3665 mUidFirewallStandbyRules.delete(uid);
3666 mUidFirewallDozableRules.delete(uid);
3667 mUidFirewallPowerSaveRules.delete(uid);
3668 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3669 mPowerSaveWhitelistAppIds.delete(uid);
3670 mPowerSaveTempWhitelistAppIds.delete(uid);
3671
3672 // ...then update iptables asynchronously.
3673 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3674 }
3675
3676 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003677 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003678 *
Felipe Leme781ba142016-05-09 16:24:48 -07003679 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003680 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003681 * <li>Doze mode
3682 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003683 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003684 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003685 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003686 *
3687 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003688 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003689 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003690 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003691 updateRuleForDeviceIdleUL(uid);
3692 updateRuleForAppIdleUL(uid);
3693 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003694
3695 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003696 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003697
3698 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003699 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003700 }
3701
Felipe Leme70c57c22016-03-29 10:45:13 -07003702 /**
3703 * Applies network rules to bandwidth controllers based on process state and user-defined
3704 * restrictions (blacklist / whitelist).
3705 *
3706 * <p>
3707 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3708 * networks:
3709 * <ul>
3710 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3711 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3712 * also blacklisted.
3713 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3714 * no UIDs other those whitelisted will have access.
3715 * <ul>
3716 *
3717 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3718 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3719 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3720 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003721 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003722 * {@link INetworkManagementService}, but this method should also be called in events (like
3723 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3724 * following rules should also be applied:
3725 *
3726 * <ul>
3727 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3728 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3729 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3730 * {@code bw_penalty_box}.
3731 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3732 * </ul>
3733 *
3734 * <p>For optimization, the rules are only applied on user apps that have internet access
3735 * permission, since there is no need to change the {@code iptables} rule if the app does not
3736 * have permission to use the internet.
3737 *
3738 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003739 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003740 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003741 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003742 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3743 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3744 "updateRulesForDataUsageRestrictionsUL: " + uid);
3745 }
3746 try {
3747 updateRulesForDataUsageRestrictionsULInner(uid);
3748 } finally {
3749 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3750 }
3751 }
3752
3753 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003754 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003755 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003756 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003757 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003758
Dianne Hackborn497175b2014-07-01 12:56:08 -07003759 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003760 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003761 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003762 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003763
Felipe Leme781ba142016-05-09 16:24:48 -07003764 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003765 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003766 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3767 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003768
Felipe Leme70c57c22016-03-29 10:45:13 -07003769 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003770 if (isRestrictedByAdmin) {
3771 newRule = RULE_REJECT_METERED;
3772 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003773 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3774 newRule = RULE_TEMPORARY_ALLOW_METERED;
3775 } else if (isWhitelisted) {
3776 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003777 }
3778 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003779 if (isBlacklisted) {
3780 newRule = RULE_REJECT_METERED;
3781 } else if (mRestrictBackground && isWhitelisted) {
3782 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003783 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003784 }
Felipe Leme781ba142016-05-09 16:24:48 -07003785 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003786
Felipe Lemef28983d2016-03-25 12:18:23 -07003787 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003788 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003789 + ": isForeground=" +isForeground
3790 + ", isBlacklisted=" + isBlacklisted
3791 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003792 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003793 + ", oldRule=" + uidRulesToString(oldRule)
3794 + ", newRule=" + uidRulesToString(newRule)
3795 + ", newUidRules=" + uidRulesToString(newUidRules)
3796 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003797 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003798
Felipe Leme46c4fc32016-05-04 09:21:43 -07003799 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003800 mUidRules.delete(uid);
3801 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003802 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003803 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003804
Felipe Leme70c57c22016-03-29 10:45:13 -07003805 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003806 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003807 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003808 // Temporarily whitelist foreground app, removing from blacklist if necessary
3809 // (since bw_penalty_box prevails over bw_happy_box).
3810
3811 setMeteredNetworkWhitelist(uid, true);
3812 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3813 // but ideally it should be just:
3814 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003815 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003816 setMeteredNetworkBlacklist(uid, false);
3817 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003818 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003819 // Remove temporary whitelist from app that is not on foreground anymore.
3820
3821 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3822 // but ideally they should be just:
3823 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3824 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003825 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003826 setMeteredNetworkWhitelist(uid, false);
3827 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003828 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003829 setMeteredNetworkBlacklist(uid, true);
3830 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003831 } else if (hasRule(newRule, RULE_REJECT_METERED)
3832 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003833 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003834 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003835 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003836 // Since blacklist prevails over whitelist, we need to handle the special case
3837 // where app is whitelisted and blacklisted at the same time (although such
3838 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003839 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003840 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003841 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3842 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003843 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003844 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003845 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003846 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003847 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3848 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003849 + ", whitelisted=" + isWhitelisted
3850 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003851 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003852 + ", newRule=" + uidRulesToString(newUidRules)
3853 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003854 }
Felipe Leme781ba142016-05-09 16:24:48 -07003855
Sudheer Shankac9d94072017-02-22 22:13:55 +00003856 // Dispatch changed rule to existing listeners.
3857 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003858 }
3859 }
3860
3861 /**
3862 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3863 * listeners in case of change.
3864 * <p>
3865 * There are 3 power-related rules that affects whether an app has background access on
3866 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3867 * restriction, it's added to the equivalent firewall chain:
3868 * <ul>
3869 * <li>App is idle: {@code fw_standby} firewall chain.
3870 * <li>Device is idle: {@code fw_dozable} firewall chain.
3871 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3872 * </ul>
3873 * <p>
3874 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3875 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3876 * <p>
3877 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3878 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003879 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003880 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3881
Sudheer Shankac9d94072017-02-22 22:13:55 +00003882 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003883
Sudheer Shankac9d94072017-02-22 22:13:55 +00003884 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003885 mUidRules.delete(uid);
3886 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003887 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003888 }
3889 }
3890
3891 /**
3892 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3893 *
3894 * @param uid the uid of the app to update rules for
3895 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3896 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3897 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003898 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003899 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003900 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003901 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3902 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3903 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3904 + (paroled ? "P" : "-"));
3905 }
3906 try {
3907 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3908 } finally {
3909 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3910 }
3911 }
3912
3913 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003914 if (!isUidValidForBlacklistRules(uid)) {
3915 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003916 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003917 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003918
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003919 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003920 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003921 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003922
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003923 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003924 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3925 int newRule = RULE_NONE;
3926
3927 // First step: define the new rule based on user restrictions and foreground state.
3928
3929 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3930 // by considering the foreground and non-foreground states.
3931 if (isForeground) {
3932 if (restrictMode) {
3933 newRule = RULE_ALLOW_ALL;
3934 }
3935 } else if (restrictMode) {
3936 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3937 }
3938
3939 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3940
3941 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003942 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003943 + ", isIdle: " + isIdle
3944 + ", mRestrictPower: " + mRestrictPower
3945 + ", mDeviceIdleMode: " + mDeviceIdleMode
3946 + ", isForeground=" + isForeground
3947 + ", isWhitelisted=" + isWhitelisted
3948 + ", oldRule=" + uidRulesToString(oldRule)
3949 + ", newRule=" + uidRulesToString(newRule)
3950 + ", newUidRules=" + uidRulesToString(newUidRules)
3951 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3952 }
3953
Felipe Leme781ba142016-05-09 16:24:48 -07003954 // Second step: notify listeners if state changed.
3955 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003956 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003957 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003958 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003959 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3960 } else {
3961 // All scenarios should have been covered above
3962 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3963 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003964 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003965 + ", newRule=" + uidRulesToString(newUidRules)
3966 + ", oldRule=" + uidRulesToString(oldUidRules));
3967 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003968 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003969 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003970
Sudheer Shankac9d94072017-02-22 22:13:55 +00003971 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003972 }
3973
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003974 private class AppIdleStateChangeListener
3975 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3976
3977 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08003978 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
3979 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003980 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003981 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3982 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003983 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003984 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003985 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003986 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003987 }
3988 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003989 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003990 }
3991
3992 @Override
3993 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003994 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003995 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003996 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003997 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003998 }
3999 }
4000
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004001 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4002 if (listener != null) {
4003 try {
4004 listener.onUidRulesChanged(uid, uidRules);
4005 } catch (RemoteException ignored) {
4006 }
4007 }
4008 }
4009
4010 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4011 String[] meteredIfaces) {
4012 if (listener != null) {
4013 try {
4014 listener.onMeteredIfacesChanged(meteredIfaces);
4015 } catch (RemoteException ignored) {
4016 }
4017 }
4018 }
4019
4020 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4021 boolean restrictBackground) {
4022 if (listener != null) {
4023 try {
4024 listener.onRestrictBackgroundChanged(restrictBackground);
4025 } catch (RemoteException ignored) {
4026 }
4027 }
4028 }
4029
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004030 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4031 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004032 if (listener != null) {
4033 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004034 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004035 } catch (RemoteException ignored) {
4036 }
4037 }
4038 }
4039
Jeff Sharkey9252b342018-01-19 07:58:35 +09004040 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4041 int overrideMask, int overrideValue) {
4042 if (listener != null) {
4043 try {
4044 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4045 } catch (RemoteException ignored) {
4046 }
4047 }
4048 }
4049
Makoto Onuki8e777332017-03-28 11:25:47 -07004050 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004051 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004052 public boolean handleMessage(Message msg) {
4053 switch (msg.what) {
4054 case MSG_RULES_CHANGED: {
4055 final int uid = msg.arg1;
4056 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004057 final int length = mListeners.beginBroadcast();
4058 for (int i = 0; i < length; i++) {
4059 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4060 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004061 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004062 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004063 return true;
4064 }
4065 case MSG_METERED_IFACES_CHANGED: {
4066 final String[] meteredIfaces = (String[]) msg.obj;
4067 final int length = mListeners.beginBroadcast();
4068 for (int i = 0; i < length; i++) {
4069 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004070 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004071 }
4072 mListeners.finishBroadcast();
4073 return true;
4074 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004075 case MSG_LIMIT_REACHED: {
4076 final String iface = (String) msg.obj;
4077
Felipe Lemef0823852016-06-08 13:43:08 -07004078 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004079 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004080 // force stats update to make sure we have
4081 // numbers that caused alert to trigger.
4082 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004083
Felipe Lemef0823852016-06-08 13:43:08 -07004084 updateNetworkEnabledNL();
4085 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004086 }
4087 }
4088 return true;
4089 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004090 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4091 final boolean restrictBackground = msg.arg1 != 0;
4092 final int length = mListeners.beginBroadcast();
4093 for (int i = 0; i < length; i++) {
4094 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004095 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004096 }
4097 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004098 final Intent intent =
4099 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4100 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4101 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4102 return true;
4103 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004104 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004105 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004106 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004107 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004108 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004109 final int length = mListeners.beginBroadcast();
4110 for (int i = 0; i < length; i++) {
4111 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004112 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004113 }
4114 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004115 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4116 if (notifyApp.booleanValue()) {
4117 broadcastRestrictBackgroundChanged(uid, notifyApp);
4118 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004119 return true;
4120 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004121 case MSG_ADVISE_PERSIST_THRESHOLD: {
4122 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004123 // make sure stats are recorded frequently enough; we aim
4124 // for 2MB threshold for 2GB/month rules.
4125 final long persistThreshold = lowestRule / 1000;
4126 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004127 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004128 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004129 case MSG_UPDATE_INTERFACE_QUOTA: {
4130 removeInterfaceQuota((String) msg.obj);
4131 // int params need to be stitched back into a long
4132 setInterfaceQuota((String) msg.obj,
4133 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4134 return true;
4135 }
4136 case MSG_REMOVE_INTERFACE_QUOTA: {
4137 removeInterfaceQuota((String) msg.obj);
4138 return true;
4139 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004140 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4141 resetUidFirewallRules(msg.arg1);
4142 return true;
4143 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004144 case MSG_SUBSCRIPTION_OVERRIDE: {
4145 final int overrideMask = msg.arg1;
4146 final int overrideValue = msg.arg2;
4147 final int subId = (int) msg.obj;
4148 final int length = mListeners.beginBroadcast();
4149 for (int i = 0; i < length; i++) {
4150 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4151 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4152 }
4153 mListeners.finishBroadcast();
4154 return true;
4155 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004156 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4157 final int userId = msg.arg1;
4158 final Set<String> packageNames = (Set<String>) msg.obj;
4159 setMeteredRestrictedPackagesInternal(packageNames, userId);
4160 return true;
4161 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004162 default: {
4163 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004164 }
4165 }
4166 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004167 };
4168
4169 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4170 @Override
4171 public boolean handleMessage(Message msg) {
4172 switch (msg.what) {
4173 case UID_MSG_STATE_CHANGED: {
4174 final int uid = msg.arg1;
4175 final int procState = msg.arg2;
4176 final long procStateSeq = (Long) msg.obj;
4177
4178 handleUidChanged(uid, procState, procStateSeq);
4179 return true;
4180 }
4181 case UID_MSG_GONE: {
4182 final int uid = msg.arg1;
4183 handleUidGone(uid);
4184 return true;
4185 }
4186 default: {
4187 return false;
4188 }
4189 }
4190 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004191
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004192 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004193
Makoto Onuki8e777332017-03-28 11:25:47 -07004194 void handleUidChanged(int uid, int procState, long procStateSeq) {
4195 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4196 try {
4197 synchronized (mUidRulesFirstLock) {
4198 // We received a uid state change callback, add it to the history so that it
4199 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004200 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004201 // Now update the network policy rules as per the updated uid state.
4202 updateUidStateUL(uid, procState);
4203 // Updating the network rules is done, so notify AMS about this.
4204 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4205 }
4206 } finally {
4207 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4208 }
4209 }
4210
4211 void handleUidGone(int uid) {
4212 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4213 try {
4214 synchronized (mUidRulesFirstLock) {
4215 removeUidStateUL(uid);
4216 }
4217 } finally {
4218 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4219 }
4220 }
4221
Felipe Leme57e3d312016-08-23 14:42:52 -07004222 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4223 final PackageManager pm = mContext.getPackageManager();
4224 final String[] packages = pm.getPackagesForUid(uid);
4225 if (packages != null) {
4226 final int userId = UserHandle.getUserId(uid);
4227 for (String packageName : packages) {
4228 final Intent intent =
4229 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4230 intent.setPackage(packageName);
4231 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4232 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4233 }
4234 }
4235 }
4236
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004237 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4238 // long quotaBytes split up into two ints to fit in message
4239 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4240 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4241 }
4242
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004243 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004244 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004245 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004246 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004247 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004248 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004249 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004250 }
4251 }
4252
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004253 private void removeInterfaceQuotaAsync(String iface) {
4254 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4255 }
4256
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004257 private void removeInterfaceQuota(String iface) {
4258 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004259 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004260 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004261 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004262 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004263 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004264 }
4265 }
4266
Felipe Leme70c57c22016-03-29 10:45:13 -07004267 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4268 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004269 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004270 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004271 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004272 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4273 } catch (RemoteException e) {
4274 // ignored; service lives in system_server
4275 }
4276 }
4277
4278 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4279 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4280 try {
4281 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4282 } catch (IllegalStateException e) {
4283 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004284 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004285 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004286 }
4287 }
4288
Felipe Lemebc853dd2016-09-08 13:26:55 -07004289 private static final int CHAIN_TOGGLE_NONE = 0;
4290 private static final int CHAIN_TOGGLE_ENABLE = 1;
4291 private static final int CHAIN_TOGGLE_DISABLE = 2;
4292 @Retention(RetentionPolicy.SOURCE)
4293 @IntDef(flag = false, value = {
4294 CHAIN_TOGGLE_NONE,
4295 CHAIN_TOGGLE_ENABLE,
4296 CHAIN_TOGGLE_DISABLE
4297 })
4298 public @interface ChainToggleType {
4299 }
4300
4301 /**
4302 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004303 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004304 *
4305 * @param chain firewall chain.
4306 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4307 * @param toggle whether the chain should be enabled, disabled, or not changed.
4308 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004309 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004310 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004311 if (uidRules != null) {
4312 setUidFirewallRulesUL(chain, uidRules);
4313 }
4314 if (toggle != CHAIN_TOGGLE_NONE) {
4315 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4316 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004317 }
4318
Amith Yamasani15e472352015-04-24 19:06:07 -07004319 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004320 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4321 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4322 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004323 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004324 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004325 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004326 int size = uidRules.size();
4327 int[] uids = new int[size];
4328 int[] rules = new int[size];
4329 for(int index = size - 1; index >= 0; --index) {
4330 uids[index] = uidRules.keyAt(index);
4331 rules[index] = uidRules.valueAt(index);
4332 }
4333 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004334 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004335 } catch (IllegalStateException e) {
4336 Log.wtf(TAG, "problem setting firewall uid rules", e);
4337 } catch (RemoteException e) {
4338 // ignored; service lives in system_server
4339 }
4340 }
4341
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004342 /**
4343 * Add or remove a uid to the firewall blacklist for all network ifaces.
4344 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004345 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004346 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4347 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4348 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004349 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004350 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004351 if (chain == FIREWALL_CHAIN_DOZABLE) {
4352 mUidFirewallDozableRules.put(uid, rule);
4353 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4354 mUidFirewallStandbyRules.put(uid, rule);
4355 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4356 mUidFirewallPowerSaveRules.put(uid, rule);
4357 }
4358
4359 try {
4360 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004361 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004362 } catch (IllegalStateException e) {
4363 Log.wtf(TAG, "problem setting firewall uid rules", e);
4364 } catch (RemoteException e) {
4365 // ignored; service lives in system_server
4366 }
4367 } finally {
4368 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004369 }
4370 }
4371
4372 /**
4373 * Add or remove a uid to the firewall blacklist for all network ifaces.
4374 */
Felipe Lemef0823852016-06-08 13:43:08 -07004375 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004376 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4377 mFirewallChainStates.get(chain) == enable) {
4378 // All is the same, nothing to do.
4379 return;
4380 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004381 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004382 try {
4383 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004384 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004385 } catch (IllegalStateException e) {
4386 Log.wtf(TAG, "problem enable firewall chain", e);
4387 } catch (RemoteException e) {
4388 // ignored; service lives in system_server
4389 }
4390 }
4391
Felipe Leme03e95e22016-09-09 09:25:31 -07004392 /**
4393 * Resets all firewall rules associated with an UID.
4394 */
4395 private void resetUidFirewallRules(int uid) {
4396 try {
4397 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4398 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4399 mNetworkManager
4400 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4401 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4402 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4403 } catch (IllegalStateException e) {
4404 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4405 } catch (RemoteException e) {
4406 // ignored; service lives in system_server
4407 }
4408 }
4409
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004410 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004411 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004412 return getNetworkTotalBytes(template, start, end);
4413 }
4414
4415 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004416 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004417 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004418 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004419 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004420 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004421 }
4422 }
4423
4424 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4425 try {
4426 return mNetworkStats.getNetworkUidBytes(template, start, end);
4427 } catch (RuntimeException e) {
4428 Slog.w(TAG, "Failed to read network stats: " + e);
4429 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004430 }
4431 }
4432
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004433 private boolean isBandwidthControlEnabled() {
4434 final long token = Binder.clearCallingIdentity();
4435 try {
4436 return mNetworkManager.isBandwidthControlEnabled();
4437 } catch (RemoteException e) {
4438 // ignored; service lives in system_server
4439 return false;
4440 } finally {
4441 Binder.restoreCallingIdentity(token);
4442 }
4443 }
4444
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004445 private static Intent buildAllowBackgroundDataIntent() {
4446 return new Intent(ACTION_ALLOW_BACKGROUND);
4447 }
4448
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004449 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4450 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004451 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4452 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4453 return intent;
4454 }
4455
4456 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4457 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4458 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004459 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4460 return intent;
4461 }
4462
Wei Liu546cb772016-07-21 16:19:01 -07004463 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004464 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004465 intent.setComponent(ComponentName.unflattenFromString(
4466 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004467 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4468 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4469 return intent;
4470 }
4471
Wei Liu546cb772016-07-21 16:19:01 -07004472 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004473 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004474 intent.setComponent(ComponentName.unflattenFromString(
4475 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004476 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4477 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4478 return intent;
4479 }
4480
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004481 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004482 public void addIdleHandler(IdleHandler handler) {
4483 mHandler.getLooper().getQueue().addIdleHandler(handler);
4484 }
4485
jackqdyulei29c82ab2017-03-10 14:09:16 -08004486 @VisibleForTesting
4487 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4488 mRestrictBackgroundPowerState = result;
4489
4490 boolean restrictBackground = result.batterySaverEnabled;
4491 boolean shouldInvokeRestrictBackground;
4492 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4493 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4494
4495 if (result.globalBatterySaverEnabled) {
4496 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4497 // turn it on.
4498 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4499 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4500 localRestrictBgChangedInBsm = false;
4501 } else {
4502 // Try to restore the restrictBackground if it doesn't change in bsm
4503 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4504 restrictBackground = mRestrictBackgroundBeforeBsm;
4505 }
4506
4507 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004508 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004509 }
4510
4511 // Change it at last so setRestrictBackground() won't affect this variable
4512 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4513 }
4514
Jeff Sharkey1b861272011-05-22 00:34:52 -07004515 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4516 final int size = source.size();
4517 for (int i = 0; i < size; i++) {
4518 target.put(source.keyAt(i), true);
4519 }
4520 }
4521
Stuart Scottf1fb3972015-04-02 18:00:02 -07004522 @Override
4523 public void factoryReset(String subscriber) {
4524 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4525
Stuart Scotte3e314d2015-04-20 14:07:45 -07004526 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4527 return;
4528 }
4529
Stuart Scottf1fb3972015-04-02 18:00:02 -07004530 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004531 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004532 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4533 for (NetworkPolicy policy : policies) {
4534 if (policy.template.equals(template)) {
4535 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4536 policy.inferred = false;
4537 policy.clearSnooze();
4538 }
4539 }
4540 setNetworkPolicies(policies);
4541
4542 // Turn restrict background data off
4543 setRestrictBackground(false);
4544
Stuart Scotte3e314d2015-04-20 14:07:45 -07004545 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4546 // Remove app's "restrict background data" flag
4547 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4548 setUidPolicy(uid, POLICY_NONE);
4549 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004550 }
4551 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004552
Sudheer Shankab8f23162017-08-04 13:30:10 -07004553 @Override
4554 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4555 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4556 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4557 }
4558
4559 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4560 final int uidRules;
4561 final boolean isBackgroundRestricted;
4562 synchronized (mUidRulesFirstLock) {
4563 uidRules = mUidRules.get(uid, RULE_NONE);
4564 isBackgroundRestricted = mRestrictBackground;
4565 }
4566 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004567 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004568 return true;
4569 }
4570 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004571 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004572 return false;
4573 }
4574 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004575 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004576 return true;
4577 }
4578 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004579 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004580 return false;
4581 }
4582 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004583 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004584 return false;
4585 }
4586 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004587 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004588 return true;
4589 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004590 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004591 return false;
4592 }
4593
Felipe Lemed17fda42016-04-29 11:12:45 -07004594 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4595
4596 @Override
4597 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004598 synchronized (mUidRulesFirstLock) {
4599 boolean changed = removeUserStateUL(userId, false);
4600 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004601 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004602 synchronized (mNetworkPoliciesSecondLock) {
4603 writePolicyAL();
4604 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004605 }
4606 }
4607 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004608
4609 /**
4610 * @return true if the given uid is restricted from doing networking on metered networks.
4611 */
4612 @Override
4613 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4614 final int uidRules;
4615 final boolean isBackgroundRestricted;
4616 synchronized (mUidRulesFirstLock) {
4617 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4618 isBackgroundRestricted = mRestrictBackground;
4619 }
4620 return isBackgroundRestricted
4621 && !hasRule(uidRules, RULE_ALLOW_METERED)
4622 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4623 }
4624
4625 /**
4626 * @return true if networking is blocked on the given interface for the given uid according
4627 * to current networking policies.
4628 */
4629 @Override
4630 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004631 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004632 synchronized (mNetworkPoliciesSecondLock) {
4633 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004634 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004635 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004636 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004637
4638 @Override
4639 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4640 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004641 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004642 if (added) {
4643 mPowerSaveTempWhitelistAppIds.put(appId, true);
4644 } else {
4645 mPowerSaveTempWhitelistAppIds.delete(appId);
4646 }
4647 updateRulesForTempWhitelistChangeUL(appId);
4648 }
4649 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004650
4651 @Override
4652 public SubscriptionPlan getSubscriptionPlan(Network network) {
4653 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004654 final int subId = getSubIdLocked(network);
4655 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004656 }
4657 }
4658
4659 @Override
4660 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4661 synchronized (mNetworkPoliciesSecondLock) {
4662 // TODO: handle splitting quota between use-cases
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004663 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
4664 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004665 }
4666 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004667
4668 @Override
4669 public void onAdminDataAvailable() {
4670 mAdminDataAvailableLatch.countDown();
4671 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004672
4673 @Override
4674 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4675 setMeteredRestrictedPackagesInternal(packageNames, userId);
4676 }
4677
4678 @Override
4679 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4680 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4681 userId, 0, packageNames).sendToTarget();
4682 }
4683 }
4684
4685 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4686 synchronized (mUidRulesFirstLock) {
4687 final Set<Integer> newRestrictedUids = new ArraySet<>();
4688 for (String packageName : packageNames) {
4689 final int uid = getUidForPackage(packageName, userId);
4690 if (uid >= 0) {
4691 newRestrictedUids.add(uid);
4692 }
4693 }
4694 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4695 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4696 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4697 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4698 }
4699 }
4700
4701 private int getUidForPackage(String packageName, int userId) {
4702 try {
4703 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4704 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4705 } catch (NameNotFoundException e) {
4706 return -1;
4707 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004708 }
4709
4710 private int parseSubId(NetworkState state) {
4711 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4712 int subId = INVALID_SUBSCRIPTION_ID;
4713 if (state != null && state.networkCapabilities != null
4714 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4715 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4716 if (spec instanceof StringNetworkSpecifier) {
4717 try {
4718 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4719 } catch (NumberFormatException e) {
4720 }
4721 }
4722 }
4723 return subId;
4724 }
4725
Andreas Gampea36dc622018-02-05 17:19:22 -08004726 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004727 private int getSubIdLocked(Network network) {
4728 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004729 }
4730
Andreas Gampea36dc622018-02-05 17:19:22 -08004731 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004732 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4733 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4734 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4735 }
4736
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004737 /**
4738 * This will only ever be called once - during device boot.
4739 */
4740 private void waitForAdminData() {
4741 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4742 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4743 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4744 }
4745 }
4746
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004747 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4748 Set<Integer> newRestrictedUids) {
4749 if (oldRestrictedUids == null) {
4750 for (int uid : newRestrictedUids) {
4751 updateRulesForDataUsageRestrictionsUL(uid);
4752 }
4753 return;
4754 }
4755 for (int uid : oldRestrictedUids) {
4756 if (!newRestrictedUids.contains(uid)) {
4757 updateRulesForDataUsageRestrictionsUL(uid);
4758 }
4759 }
4760 for (int uid : newRestrictedUids) {
4761 if (!oldRestrictedUids.contains(uid)) {
4762 updateRulesForDataUsageRestrictionsUL(uid);
4763 }
4764 }
4765 }
4766
4767 private boolean isRestrictedByAdminUL(int uid) {
4768 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4769 UserHandle.getUserId(uid));
4770 return restrictedUids != null && restrictedUids.contains(uid);
4771 }
4772
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004773 private static boolean hasRule(int uidRules, int rule) {
4774 return (uidRules & rule) != 0;
4775 }
4776
Jeff Sharkey2e471452018-01-19 18:02:47 +09004777 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4778 return (val != null) ? val : new NetworkState[0];
4779 }
4780
Chris Wren193ae6b2017-03-31 15:17:11 -04004781 private class NotificationId {
4782 private final String mTag;
4783 private final int mId;
4784
4785 NotificationId(NetworkPolicy policy, int type) {
4786 mTag = buildNotificationTag(policy, type);
4787 mId = type;
4788 }
4789
4790 @Override
4791 public boolean equals(Object o) {
4792 if (this == o) return true;
4793 if (!(o instanceof NotificationId)) return false;
4794 NotificationId that = (NotificationId) o;
4795 return Objects.equals(mTag, that.mTag);
4796 }
4797
4798 @Override
4799 public int hashCode() {
4800 return Objects.hash(mTag);
4801 }
4802
4803 /**
4804 * Build unique tag that identifies an active {@link NetworkPolicy}
4805 * notification of a specific type, like {@link #TYPE_LIMIT}.
4806 */
4807 private String buildNotificationTag(NetworkPolicy policy, int type) {
4808 return TAG + ":" + policy.template.hashCode() + ":" + type;
4809 }
4810
4811 public String getTag() {
4812 return mTag;
4813 }
4814
4815 public int getId() {
4816 return mId;
4817 }
4818 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004819}