blob: ebcc54bfc61761ec2643fd50c28e77a7523eaf65 [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;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900233import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600234import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700235import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600236import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900237import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700239import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600240import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400241import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800242import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800243import java.util.concurrent.CountDownLatch;
244import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700246/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700247 * Service that maintains low-level network policy rules, using
248 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700249 * <p>
250 * Derives active rules by combining a given policy with other system status,
251 * and delivers to listeners, such as {@link ConnectivityManager}, for
252 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700253 *
254 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000255 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700256 * <ul>
257 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
258 * rules).
259 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
260 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000261 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
262 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700263 * </ul>
264 *
265 * <p>
266 * As such, methods that require synchronization have the following prefixes:
267 * <ul>
268 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
269 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000270 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
271 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700272 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700273 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700274public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700275 static final String TAG = NetworkPolicyLogger.TAG;
276 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
277 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700278
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900279 /**
280 * No opportunistic quota could be calculated from user data plan or data settings.
281 */
282 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 private static final int VERSION_INIT = 1;
285 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700286 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800287 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800288 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800289 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700290 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700291 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700293 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600294 private static final int VERSION_ADDED_CYCLE = 11;
295 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700296
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800297 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400298 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800299 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400300 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800301 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400302 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900303 @VisibleForTesting
304 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700305
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 private static final String TAG_POLICY_LIST = "policy-list";
307 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700310 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800311 private static final String TAG_WHITELIST = "whitelist";
312 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800313 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
315 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700316 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
318 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700319 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600320 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
321 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
322 private static final String ATTR_CYCLE_START = "cycleStart";
323 private static final String ATTR_CYCLE_END = "cycleEnd";
324 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String ATTR_WARNING_BYTES = "warningBytes";
326 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700327 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800328 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
329 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800330 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700331 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700333 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600335 private static final String ATTR_SUB_ID = "subId";
336 private static final String ATTR_TITLE = "title";
337 private static final String ATTR_SUMMARY = "summary";
338 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
339 private static final String ATTR_USAGE_BYTES = "usageBytes";
340 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600341 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800343 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800344 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800345 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800346 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700347 private static final String ACTION_SNOOZE_RAPID =
348 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700349
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800350 /**
351 * Indicates the maximum wait time for admin data to be available;
352 */
353 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
354
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700355 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700356 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800357 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800358 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700359 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700360 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
361 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700362 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700363 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900364 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800365 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700366
Makoto Onuki8e777332017-03-28 11:25:47 -0700367 private static final int UID_MSG_STATE_CHANGED = 100;
368 private static final int UID_MSG_GONE = 101;
369
Jeff Sharkey75279902011-05-24 18:39:45 -0700370 private final Context mContext;
371 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700372 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700373 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700374 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700375 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700376 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700377 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700378
379 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700380 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700381 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800382 @GuardedBy("mUidRulesFirstLock")
383 private PowerSaveState mRestrictBackgroundPowerState;
384
385 // Store the status of restrict background before turning on battery saver.
386 // Used to restore mRestrictBackground when battery saver is turned off.
387 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700388
Sudheer Shanka543339f2017-07-28 15:18:07 -0700389 // Denotes the status of restrict background read from disk.
390 private boolean mLoadedRestrictBackground;
391
Felipe Lemef0823852016-06-08 13:43:08 -0700392 // See main javadoc for instructions on how to use these locks.
393 final Object mUidRulesFirstLock = new Object();
394 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700395
Felipe Lemef0823852016-06-08 13:43:08 -0700396 @GuardedBy("allLocks") volatile boolean mSystemReady;
397
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
399 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
400 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800401 // Store whether user flipped restrict background in battery saver mode
402 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700403
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700404 private final boolean mSuppressDefaultPolicy;
405
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800406 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
407
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700408 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600409 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800410 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700411
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600412 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600413 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600414 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600415 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600416 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600417 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600418
Jeff Sharkey9252b342018-01-19 07:58:35 +0900419 /** Map from subId to daily opportunistic quota. */
420 @GuardedBy("mNetworkPoliciesSecondLock")
421 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
422
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700423 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700425 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700426 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700427
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700429 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700431 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700432 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800433 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700434
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700435 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700436 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700437 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
438
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 /**
440 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700441 * in power save mode, except device idle (doze) still applies.
442 * TODO: An int array might be sufficient
443 */
Felipe Lemef0823852016-06-08 13:43:08 -0700444 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700445 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
446
447 /**
448 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800449 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700450 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800451 */
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700453 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700454
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700456 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
457
Felipe Lemeb85a6372016-01-14 16:16:16 -0800458 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800459 * UIDs that have been initially white-listed by system to avoid restricted background.
460 */
Felipe Lemef0823852016-06-08 13:43:08 -0700461 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800462 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
463 new SparseBooleanArray();
464
465 /**
466 * UIDs that have been initially white-listed by system to avoid restricted background,
467 * but later revoked by user.
468 */
Felipe Lemef0823852016-06-08 13:43:08 -0700469 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800470 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
471 new SparseBooleanArray();
472
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700473 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800475 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700476 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700477 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800478 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700479
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700480 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700481 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400482 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700483
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700484 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700485 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800486 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700487
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600488 /** Map from network ID to last observed meteredness state */
489 @GuardedBy("mNetworkPoliciesSecondLock")
490 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
491
Jeff Sharkey9252b342018-01-19 07:58:35 +0900492 /** Map from netId to subId as of last update */
493 @GuardedBy("mNetworkPoliciesSecondLock")
494 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
495
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800496 /**
497 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
498 * userId to restricted uids which belong to that user.
499 */
500 @GuardedBy("mUidRulesFirstLock")
501 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
502
Jeff Sharkey32566012014-12-02 18:30:14 -0800503 private final RemoteCallbackList<INetworkPolicyListener>
504 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700505
Dianne Hackborn497175b2014-07-01 12:56:08 -0700506 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700507 @VisibleForTesting
508 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700509
510 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700511
Felipe Lemef0823852016-06-08 13:43:08 -0700512 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700513 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700514
Svet Ganov16a16892015-04-16 10:32:04 -0700515 private final AppOpsManager mAppOps;
516
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800517 private final IPackageManager mIPm;
518
Sudheer Shankae7361852017-03-07 11:51:46 -0800519 private ActivityManagerInternal mActivityManagerInternal;
520
Sudheer Shanka352dc572017-09-22 17:09:38 -0700521 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800522
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700523 // TODO: keep whitelist of system-critical services that should never have
524 // rules enforced, such as system, phone, and radio UIDs.
525
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700526 // TODO: migrate notifications to SystemUI
527
Jeff Sharkey75279902011-05-24 18:39:45 -0700528 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700529 INetworkManagementService networkManagement) {
530 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
531 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700532 }
533
Jeff Sharkey9911a282018-02-14 22:29:11 -0700534 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700535 return new File(Environment.getDataDirectory(), "system");
536 }
537
Jeff Sharkey9911a282018-02-14 22:29:11 -0700538 private static @NonNull Clock getDefaultClock() {
539 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
540 Clock.systemUTC());
541 }
542
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700543 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700544 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
545 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700546 mContext = checkNotNull(context, "missing context");
547 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700548 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700549 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700550 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700551 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700552 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700553 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700554 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700555
Amith Yamasani450a16b2013-09-18 16:28:50 -0700556 HandlerThread thread = new HandlerThread(TAG);
557 thread.start();
558 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700559
Makoto Onuki8e777332017-03-28 11:25:47 -0700560 // We create another thread for the UID events, which are more time-critical.
561 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
562 /*allowIo=*/ false);
563 mUidEventThread.start();
564 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
565
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700566 mSuppressDefaultPolicy = suppressDefaultPolicy;
567
Dianne Hackborne17b4452018-01-10 13:15:40 -0800568 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700569
570 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800571
Felipe Lemed17fda42016-04-29 11:12:45 -0700572 // Expose private service for system components to use.
573 LocalServices.addService(NetworkPolicyManagerInternal.class,
574 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700575 }
576
577 public void bindConnectivityManager(IConnectivityManager connManager) {
578 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700580
Felipe Lemef0823852016-06-08 13:43:08 -0700581 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700582 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700583 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
584 mPowerSaveWhitelistExceptIdleAppIds.clear();
585 if (whitelist != null) {
586 for (int uid : whitelist) {
587 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
588 }
589 }
590 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700591 mPowerSaveWhitelistAppIds.clear();
592 if (whitelist != null) {
593 for (int uid : whitelist) {
594 mPowerSaveWhitelistAppIds.put(uid, true);
595 }
596 }
597 } catch (RemoteException e) {
598 }
599 }
600
Felipe Lemea9505cc2016-02-26 10:28:41 -0800601 /**
602 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
603 * revoke the whitelist.
604 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700605 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800606 */
Felipe Lemef0823852016-06-08 13:43:08 -0700607 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800608 final List<UserInfo> users = mUserManager.getUsers();
609 final int numberUsers = users.size();
610
Felipe Lemea110eec2016-04-29 09:58:06 -0700611 boolean changed = false;
612 for (int i = 0; i < numberUsers; i++) {
613 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700614 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700615 }
616 return changed;
617 }
618
Felipe Lemef0823852016-06-08 13:43:08 -0700619 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700620 final SystemConfig sysConfig = SystemConfig.getInstance();
621 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800622 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
623 boolean changed = false;
624 for (int i = 0; i < allowDataUsage.size(); i++) {
625 final String pkg = allowDataUsage.valueAt(i);
626 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700627 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
628 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800629 final ApplicationInfo app;
630 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700631 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800632 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700633 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
634 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800635 continue;
636 }
637 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700638 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
639 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800640 continue;
641 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700642 final int uid = UserHandle.getUid(userId, app.uid);
643 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
644 if (LOGD)
645 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
646 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800647 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700648 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700649 if (LOGD)
650 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
651 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700652 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700653 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800654 }
655 }
656 return changed;
657 }
658
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800659 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700660 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800661 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700662 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800663 // Boost thread's priority during system server init
664 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700665 if (!isBandwidthControlEnabled()) {
666 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
667 return;
668 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700669
Felipe Leme873a83a2016-09-07 11:34:10 -0700670 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700671 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700672
Felipe Leme873a83a2016-09-07 11:34:10 -0700673 synchronized (mUidRulesFirstLock) {
674 synchronized (mNetworkPoliciesSecondLock) {
675 updatePowerSaveWhitelistUL();
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mPowerManagerInternal.registerLowPowerModeObserver(
678 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800679 @Override
680 public int getServiceType() {
681 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700682 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800683
684 @Override
685 public void onLowPowerModeChanged(PowerSaveState result) {
686 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800687 if (LOGD) {
688 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
689 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800690 synchronized (mUidRulesFirstLock) {
691 if (mRestrictPower != enabled) {
692 mRestrictPower = enabled;
693 updateRulesForRestrictPowerUL();
694 }
695 }
696 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800697 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800698 mRestrictPower = mPowerManagerInternal.getLowPowerState(
699 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700700
701 mSystemReady = true;
702
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800703 waitForAdminData();
704
Felipe Leme873a83a2016-09-07 11:34:10 -0700705 // read policy from disk
706 readPolicyAL();
707
jackqdyulei29c82ab2017-03-10 14:09:16 -0800708 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700709 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800710 mRestrictBackgroundPowerState = mPowerManagerInternal
711 .getLowPowerState(ServiceType.DATA_SAVER);
712 final boolean localRestrictBackground =
713 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700714 if (localRestrictBackground && !mLoadedRestrictBackground) {
715 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800716 }
717 mPowerManagerInternal.registerLowPowerModeObserver(
718 new PowerManagerInternal.LowPowerModeListener() {
719 @Override
720 public int getServiceType() {
721 return ServiceType.DATA_SAVER;
722 }
723
724 @Override
725 public void onLowPowerModeChanged(PowerSaveState result) {
726 synchronized (mUidRulesFirstLock) {
727 updateRestrictBackgroundByLowPowerModeUL(result);
728 }
729 }
730 });
731
Felipe Leme873a83a2016-09-07 11:34:10 -0700732 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
733 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700734 }
Felipe Lemef0823852016-06-08 13:43:08 -0700735
Sudheer Shanka543339f2017-07-28 15:18:07 -0700736 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700737 updateRulesForGlobalChangeAL(false);
738 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700739 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800740 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700741
Sudheer Shankae7361852017-03-07 11:51:46 -0800742 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700743 try {
744 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000745 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800746 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700747 mNetworkManager.registerObserver(mAlertObserver);
748 } catch (RemoteException e) {
749 // ignored; both services live in system_server
750 }
751
752 // listen for changes to power save whitelist
753 final IntentFilter whitelistFilter = new IntentFilter(
754 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
755 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
756
Felipe Leme873a83a2016-09-07 11:34:10 -0700757 // watch for network interfaces to be claimed
758 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
759 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
760
761 // listen for package changes to update policy
762 final IntentFilter packageFilter = new IntentFilter();
763 packageFilter.addAction(ACTION_PACKAGE_ADDED);
764 packageFilter.addDataScheme("package");
765 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
766
767 // listen for UID changes to update policy
768 mContext.registerReceiver(
769 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
770
771 // listen for user changes to update policy
772 final IntentFilter userFilter = new IntentFilter();
773 userFilter.addAction(ACTION_USER_ADDED);
774 userFilter.addAction(ACTION_USER_REMOVED);
775 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
776
777 // listen for stats update events
778 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
779 mContext.registerReceiver(
780 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
781
782 // listen for restrict background changes from notifications
783 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
784 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
785
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700786 // Listen for snooze from notifications
787 mContext.registerReceiver(mSnoozeReceiver,
788 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
789 mContext.registerReceiver(mSnoozeReceiver,
790 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700791
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600792 // listen for configured wifi networks to be loaded
793 final IntentFilter wifiFilter =
794 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
795 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700796
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700797 // listen for carrier config changes to update data cycle information
798 final IntentFilter carrierConfigFilter = new IntentFilter(
799 ACTION_CARRIER_CONFIG_CHANGED);
800 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
801
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600802 // listen for meteredness changes
803 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
804 new NetworkRequest.Builder().build(), mNetworkCallback);
805
Felipe Leme873a83a2016-09-07 11:34:10 -0700806 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800807 // tell systemReady() that the service has been initialized
808 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700809 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800810 // Restore the default priority after init is done
811 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700813 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700814 }
815
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800816 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
817 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
818 mHandler.post(() -> initService(initCompleteSignal));
819 return initCompleteSignal;
820 }
821
822 public void systemReady(CountDownLatch initCompleteSignal) {
823 // wait for initService to complete
824 try {
825 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
826 throw new IllegalStateException("Service " + TAG +" init timeout");
827 }
828 } catch (InterruptedException e) {
829 Thread.currentThread().interrupt();
830 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
831 }
832 }
833
Sudheer Shankac9d94072017-02-22 22:13:55 +0000834 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700835 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700836 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
837 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700838 }
839
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700840 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700841 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700842 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700843
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700844 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700845 }
846
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700847 @Override public void onUidIdle(int uid, boolean disabled) {
848 }
849
850 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700851 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700852 };
853
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700854 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700855 @Override
856 public void onReceive(Context context, Intent intent) {
857 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700858 synchronized (mUidRulesFirstLock) {
859 updatePowerSaveWhitelistUL();
860 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700861 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700862 }
863 }
864 };
865
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700866 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700867 @Override
868 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700869 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700870
871 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700872 final int uid = intent.getIntExtra(EXTRA_UID, -1);
873 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700874
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700875 if (ACTION_PACKAGE_ADDED.equals(action)) {
876 // update rules for UID, since it might be subject to
877 // global background data policy
878 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700879 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700880 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700881 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700882 }
883 }
884 };
885
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700886 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700887 @Override
888 public void onReceive(Context context, Intent intent) {
889 // on background handler thread, and UID_REMOVED is protected
890
891 final int uid = intent.getIntExtra(EXTRA_UID, -1);
892 if (uid == -1) return;
893
894 // remove any policy and update rules to clean up
895 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700896 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700897 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700898 synchronized (mNetworkPoliciesSecondLock) {
899 writePolicyAL();
900 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700901 }
902 }
903 };
904
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700905 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700906 @Override
907 public void onReceive(Context context, Intent intent) {
908 // on background handler thread, and USER_ADDED and USER_REMOVED
909 // broadcasts are protected
910
911 final String action = intent.getAction();
912 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
913 if (userId == -1) return;
914
Amith Yamasani15e472352015-04-24 19:06:07 -0700915 switch (action) {
916 case ACTION_USER_REMOVED:
917 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700918 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800919 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700920 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700921 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800922 // Removing outside removeUserStateUL since that can also be called when
923 // user resets app preferences.
924 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700925 if (action == ACTION_USER_ADDED) {
926 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700927 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700928 }
929 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700930 synchronized (mNetworkPoliciesSecondLock) {
931 updateRulesForGlobalChangeAL(true);
932 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700933 }
934 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700935 }
936 }
937 };
938
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700939 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700940 * Receiver that watches for {@link INetworkStatsService} updates, which we
941 * use to check against {@link NetworkPolicy#warningBytes}.
942 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700943 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700944 @Override
945 public void onReceive(Context context, Intent intent) {
946 // on background handler thread, and verified
947 // READ_NETWORK_USAGE_HISTORY permission above.
948
Felipe Lemef0823852016-06-08 13:43:08 -0700949 synchronized (mNetworkPoliciesSecondLock) {
950 updateNetworkEnabledNL();
951 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700952 }
953 }
954 };
955
956 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700957 * Receiver that watches for {@link Notification} control of
958 * {@link #mRestrictBackground}.
959 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700960 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700961 @Override
962 public void onReceive(Context context, Intent intent) {
963 // on background handler thread, and verified MANAGE_NETWORK_POLICY
964 // permission above.
965
966 setRestrictBackground(false);
967 }
968 };
969
970 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800971 * Receiver that watches for {@link Notification} control of
972 * {@link NetworkPolicy#lastWarningSnooze}.
973 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700974 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800975 @Override
976 public void onReceive(Context context, Intent intent) {
977 // on background handler thread, and verified MANAGE_NETWORK_POLICY
978 // permission above.
979
980 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700981 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
982 performSnooze(template, TYPE_WARNING);
983 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
984 performSnooze(template, TYPE_RAPID);
985 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800986 }
987 };
988
989 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600990 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600991 * we can perform upgrade logic. After initial upgrade logic, it updates
992 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700993 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600994 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700995 @Override
996 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900997 synchronized (mUidRulesFirstLock) {
998 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600999 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001000 }
1001 }
1002 // Only need to perform upgrade logic once
1003 mContext.unregisterReceiver(this);
1004 }
1005 };
1006
1007 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1008 @Override
1009 public void onCapabilitiesChanged(Network network,
1010 NetworkCapabilities networkCapabilities) {
1011 if (network == null || networkCapabilities == null) return;
1012
1013 synchronized (mNetworkPoliciesSecondLock) {
1014 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1015 final boolean newMetered = !networkCapabilities
1016 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1017
1018 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001019 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001020 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001021 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001022 }
1023 }
1024 }
1025 };
1026
1027 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001028 * Observer that watches for {@link INetworkManagementService} alerts.
1029 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001030 final private INetworkManagementEventObserver mAlertObserver
1031 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 @Override
1033 public void limitReached(String limitName, String iface) {
1034 // only someone like NMS should be calling us
1035 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1036
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001037 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1038 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001039 }
1040 }
1041 };
1042
1043 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001044 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1045 * to show visible notifications as needed.
1046 */
Felipe Lemef0823852016-06-08 13:43:08 -07001047 void updateNotificationsNL() {
1048 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001051 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001053
1054 // TODO: when switching to kernel notifications, compute next future
1055 // cycle boundary to recompute notifications.
1056
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001057 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001058 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001059 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1060 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001061 // ignore policies that aren't relevant to user
1062 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001063 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001064
Jeff Sharkey53313d72017-07-13 16:47:32 -06001065 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1066 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001067 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1068 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1069 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001071 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001072 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001073 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1074 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001075 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001077 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001078 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 }
1080
Jeff Sharkey497e4432011-06-14 17:27:29 -07001081 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001082 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001084 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1085 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001086 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087 }
1088 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001089
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001090 // Warn if average usage over last 4 days is on track to blow pretty
1091 // far past the plan limits.
1092 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001093 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001094 final long recentStart = now - recentDuration;
1095 final long recentEnd = now;
1096 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001097
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001098 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001099 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001100 final long alertBytes = (policy.limitBytes * 3) / 2;
1101
1102 if (LOGD) {
1103 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1104 + projectedBytes + " alert " + alertBytes);
1105 }
1106
1107 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1108 - DateUtils.DAY_IN_MILLIS;
1109 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001110 enqueueNotification(policy, TYPE_RAPID, 0,
1111 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001112 }
1113 }
1114 }
1115
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001116 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001117 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001118 final NotificationId notificationId = beforeNotifs.valueAt(i);
1119 if (!mActiveNotifs.contains(notificationId)) {
1120 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001121 }
1122 }
1123 }
1124
1125 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001126 * Attempt to find a specific app to blame for rapid data usage during the
1127 * given time period.
1128 */
1129 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1130 long start, long end) {
1131 long totalBytes = 0;
1132 long maxBytes = 0;
1133 int maxUid = 0;
1134
1135 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1136 NetworkStats.Entry entry = null;
1137 for (int i = 0; i < stats.size(); i++) {
1138 entry = stats.getValues(i, entry);
1139 final long bytes = entry.rxBytes + entry.txBytes;
1140 totalBytes += bytes;
1141 if (bytes > maxBytes) {
1142 maxBytes = bytes;
1143 maxUid = entry.uid;
1144 }
1145 }
1146
1147 // Only point blame if the majority of usage was done by a single app.
1148 // TODO: support shared UIDs
1149 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1150 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001151 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001152 try {
1153 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1154 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1155 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1156 } catch (NameNotFoundException ignored) {
1157 }
1158 }
1159 }
1160
1161 return null;
1162 }
1163
1164 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001165 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001166 * current device state, such as when
1167 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1168 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 */
1170 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001171 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001172 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1173 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001174
Jeff Sharkey32566012014-12-02 18:30:14 -08001175 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001176 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001177 for (int subId : subIds) {
1178 final String subscriberId = tele.getSubscriberId(subId);
1179 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001180 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1181 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001182 if (template.matches(probeIdent)) {
1183 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001184 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001185 }
1186 return false;
1187 } else {
1188 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001190 }
1191
1192 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193 * Notify that given {@link NetworkTemplate} is over
1194 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1195 */
Felipe Lemef0823852016-06-08 13:43:08 -07001196 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001198 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001199 mOverLimitNotified.add(template);
1200 }
1201 }
1202
Felipe Lemef0823852016-06-08 13:43:08 -07001203 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001204 mOverLimitNotified.remove(template);
1205 }
1206
1207 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001208 * Show notification for combined {@link NetworkPolicy} and specific type,
1209 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1210 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001211 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1212 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001213 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001214 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001215 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001216 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001217 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001218 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001219 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001220
1221 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001222 final CharSequence title;
1223 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001224 switch (type) {
1225 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001226 title = res.getText(R.string.data_usage_warning_title);
1227 body = res.getString(R.string.data_usage_warning_body,
1228 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001229
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001230 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001231
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001232 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1233 builder.setDeleteIntent(PendingIntent.getBroadcast(
1234 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1235
Wei Liu546cb772016-07-21 16:19:01 -07001236 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001237 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001238 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1239
Jeff Sharkey497e4432011-06-14 17:27:29 -07001240 break;
1241 }
1242 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001243 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001244 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001245 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001246 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001247 case MATCH_WIFI:
1248 title = res.getText(R.string.data_usage_wifi_limit_title);
1249 break;
1250 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001251 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001252 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001253 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001254
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001255 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001256 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001257
Wei Liu546cb772016-07-21 16:19:01 -07001258 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001259 builder.setContentIntent(PendingIntent.getActivity(
1260 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1261 break;
1262 }
1263 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001264 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001265 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001266 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1267 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001268 case MATCH_WIFI:
1269 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1270 break;
1271 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001272 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001273 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001274 final long overBytes = totalBytes - policy.limitBytes;
1275 body = res.getString(R.string.data_usage_limit_snoozed_body,
1276 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001277
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001278 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001279 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001280 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001281
Wei Liu546cb772016-07-21 16:19:01 -07001282 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001283 builder.setContentIntent(PendingIntent.getActivity(
1284 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001285 break;
1286 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001287 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001288 title = res.getText(R.string.data_usage_rapid_title);
1289 if (rapidBlame != null) {
1290 body = res.getString(R.string.data_usage_rapid_app_body,
1291 rapidBlame.loadLabel(mContext.getPackageManager()));
1292 } else {
1293 body = res.getString(R.string.data_usage_rapid_body);
1294 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001295
Jeff Sharkey2e471452018-01-19 18:02:47 +09001296 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001297
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001298 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1299 builder.setDeleteIntent(PendingIntent.getBroadcast(
1300 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1301
1302 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001303 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001304 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001305 break;
1306 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001307 default: {
1308 return;
1309 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001310 }
1311
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001312 builder.setTicker(title);
1313 builder.setContentTitle(title);
1314 builder.setContentText(body);
1315 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001316
1317 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1318 notificationId.getId(), builder.build(), UserHandle.ALL);
1319 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001320 }
1321
Chris Wren193ae6b2017-03-31 15:17:11 -04001322 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001323 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1324 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001325 }
1326
1327 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001329 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001331 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 @Override
1333 public void onReceive(Context context, Intent intent) {
1334 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1335 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001336
Hugo Benichi446c9c92017-04-10 09:41:10 +09001337 synchronized (mUidRulesFirstLock) {
1338 synchronized (mNetworkPoliciesSecondLock) {
1339 ensureActiveMobilePolicyAL();
1340 normalizePoliciesNL();
1341 updateNetworkEnabledNL();
1342 updateNetworkRulesNL();
1343 updateNotificationsNL();
1344 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 }
1346 }
1347 };
1348
Jeff Sharkey2e471452018-01-19 18:02:47 +09001349 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001350 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001351 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001352 final CountDownLatch latch = new CountDownLatch(1);
1353 mHandler.post(() -> {
1354 latch.countDown();
1355 });
1356 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001357 }
1358
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001359 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001360 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1361 * if necessary.
1362 *
1363 * @param subId that has its associated NetworkPolicy updated if necessary
1364 * @return if any policies were updated
1365 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001366 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1367 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001368
1369 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001370 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1371 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001372
1373 // find and update the mobile NetworkPolicy for this subscriber id
1374 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001375 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001376 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1377 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1378 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001379 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1380 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001381 }
1382 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001383 return policyUpdated;
1384 }
1385
1386 /**
1387 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1388 *
1389 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1390 * to do so, it returns the fallback value.
1391 *
1392 * @param config The CarrierConfig to read the value from.
1393 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1394 * @return cycleDay to use in the mobile NetworkPolicy.
1395 */
1396 @VisibleForTesting
1397 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1398 int fallbackCycleDay) {
1399 if (config == null) {
1400 return fallbackCycleDay;
1401 }
1402 int cycleDay =
1403 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1404 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1405 return fallbackCycleDay;
1406 }
1407 // validate cycleDay value
1408 final Calendar cal = Calendar.getInstance();
1409 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1410 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1411 Slog.e(TAG, "Invalid date in "
1412 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1413 return fallbackCycleDay;
1414 }
1415 return cycleDay;
1416 }
1417
1418 /**
1419 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1420 *
1421 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1422 * to do so, it returns the fallback value.
1423 *
1424 * @param config The CarrierConfig to read the value from.
1425 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1426 * @return warningBytes to use in the mobile NetworkPolicy.
1427 */
1428 @VisibleForTesting
1429 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1430 long fallbackWarningBytes) {
1431 if (config == null) {
1432 return fallbackWarningBytes;
1433 }
1434 long warningBytes =
1435 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1436
1437 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1438 return WARNING_DISABLED;
1439 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1440 return getPlatformDefaultWarningBytes();
1441 } else if (warningBytes < 0) {
1442 Slog.e(TAG, "Invalid value in "
1443 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1444 + "non-negative value but got: " + warningBytes);
1445 return fallbackWarningBytes;
1446 }
1447
1448 return warningBytes;
1449 }
1450
1451 /**
1452 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1453 *
1454 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1455 * to do so, it returns the fallback value.
1456 *
1457 * @param config The CarrierConfig to read the value from.
1458 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1459 * @return limitBytes to use in the mobile NetworkPolicy.
1460 */
1461 @VisibleForTesting
1462 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1463 long fallbackLimitBytes) {
1464 if (config == null) {
1465 return fallbackLimitBytes;
1466 }
1467 long limitBytes =
1468 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1469
1470 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1471 return LIMIT_DISABLED;
1472 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1473 return getPlatformDefaultLimitBytes();
1474 } else if (limitBytes < 0) {
1475 Slog.e(TAG, "Invalid value in "
1476 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1477 + "non-negative value but got: " + limitBytes);
1478 return fallbackLimitBytes;
1479 }
1480 return limitBytes;
1481 }
1482
1483 /**
1484 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1485 */
1486 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1487 @Override
1488 public void onReceive(Context context, Intent intent) {
1489 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1490 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1491
1492 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1493 return;
1494 }
1495 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001496 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001497 final String subscriberId = tele.getSubscriberId(subId);
1498
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001499 synchronized (mUidRulesFirstLock) {
1500 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001501 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001502 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001503 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001504 if (!updated) return;
1505 // update network and notification rules, as the data cycle changed and it's
1506 // possible that we should be triggering warnings/limits now
1507 handleNetworkPoliciesUpdateAL(true);
1508 }
1509 }
1510 }
1511 };
1512
1513 /**
1514 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1515 * one has been updated.
1516 *
1517 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1518 * update.
1519 */
1520 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1521 if (shouldNormalizePolicies) {
1522 normalizePoliciesNL();
1523 }
1524 updateNetworkEnabledNL();
1525 updateNetworkRulesNL();
1526 updateNotificationsNL();
1527 writePolicyAL();
1528 }
1529
1530 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001531 * Proactively control network data connections when they exceed
1532 * {@link NetworkPolicy#limitBytes}.
1533 */
Felipe Lemef0823852016-06-08 13:43:08 -07001534 void updateNetworkEnabledNL() {
1535 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001536
1537 // TODO: reset any policy-disabled networks when any policy is removed
1538 // completely, which is currently rare case.
1539
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001540 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1541 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001542 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001543 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001544 setNetworkTemplateEnabled(policy.template, true);
1545 continue;
1546 }
1547
Jeff Sharkey53313d72017-07-13 16:47:32 -06001548 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1549 .cycleIterator(policy).next();
1550 final long start = cycle.first.toInstant().toEpochMilli();
1551 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001552 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001553
1554 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001555 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1556 && policy.lastLimitSnooze < start;
1557 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001558
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001559 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001560 }
1561 }
1562
1563 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001564 * Proactively disable networks that match the given
1565 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566 */
1567 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001568 // TODO: reach into ConnectivityManager to proactively disable bringing
1569 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001570
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001571 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001572 // If mobile data usage hits the limit or if the user resumes the data, we need to
1573 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001574 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1575 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001576
Jeff Sharkey2e471452018-01-19 18:02:47 +09001577 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001578 for (int subId : subIds) {
1579 final String subscriberId = tm.getSubscriberId(subId);
1580 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001581 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1582 true);
Jack Yu8781b682016-07-08 14:28:51 -07001583 // Template is matched when subscriber id matches.
1584 if (template.matches(probeIdent)) {
1585 tm.setPolicyDataEnabled(enabled, subId);
1586 }
1587 }
1588 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001589 }
1590
1591 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001592 * Collect all ifaces from a {@link NetworkState} into the given set.
1593 */
1594 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1595 final String baseIface = state.linkProperties.getInterfaceName();
1596 if (baseIface != null) {
1597 ifaces.add(baseIface);
1598 }
1599 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1600 final String stackedIface = stackedLink.getInterfaceName();
1601 if (stackedIface != null) {
1602 ifaces.add(stackedIface);
1603 }
1604 }
1605 }
1606
1607 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608 * Examine all connected {@link NetworkState}, looking for
1609 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1610 * remaining quota based on usage cycle and historical stats.
1611 */
Felipe Lemef0823852016-06-08 13:43:08 -07001612 void updateNetworkRulesNL() {
1613 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001614
1615 final NetworkState[] states;
1616 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001617 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001618 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001619 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 return;
1621 }
1622
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001623 // First, generate identities of all connected networks so we can
1624 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001625 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001626 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001627 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001628 if (state.network != null) {
1629 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1630 }
Wei Liub8eaf452016-01-25 10:32:27 -08001631 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001632 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1633 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001634 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001635 }
1636 }
1637
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001638 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001639 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001640
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001641 // For every well-defined policy, compute remaining data based on
1642 // current cycle and historical stats, and push to kernel.
1643 final ArraySet<String> matchingIfaces = new ArraySet<>();
1644 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1645 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1646
1647 // Collect all ifaces that match this policy
1648 matchingIfaces.clear();
1649 for (int j = identified.size() - 1; j >= 0; j--) {
1650 if (policy.template.matches(identified.valueAt(j))) {
1651 collectIfaces(matchingIfaces, identified.keyAt(j));
1652 }
1653 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001656 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001657 }
1658
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001659 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001660 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001661 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001662 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001663 if (hasLimit && policy.hasCycle()) {
1664 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1665 .cycleIterator(policy).next();
1666 final long start = cycle.first.toInstant().toEpochMilli();
1667 final long end = cycle.second.toInstant().toEpochMilli();
1668 final long totalBytes = getTotalBytes(policy.template, start, end);
1669
1670 if (policy.lastLimitSnooze >= start) {
1671 // snoozing past quota, but we still need to restrict apps,
1672 // so push really high quota.
1673 quotaBytes = Long.MAX_VALUE;
1674 } else {
1675 // remaining "quota" bytes are based on total usage in
1676 // current cycle. kernel doesn't like 0-byte rules, so we
1677 // set 1-byte quota and disable the radio later.
1678 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1679 }
1680 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001681 // metered network, but no policy limit; we still need to
1682 // restrict apps, so push really high quota.
1683 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001684 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001685
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001686 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001687 // TODO: switch to shared quota once NMS supports
1688 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001689 }
1690
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001691 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1692 final String iface = matchingIfaces.valueAt(j);
1693 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001694 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001695 }
1696 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001697
1698 // keep track of lowest warning or limit of active policies
1699 if (hasWarning && policy.warningBytes < lowestRule) {
1700 lowestRule = policy.warningBytes;
1701 }
1702 if (hasLimit && policy.limitBytes < lowestRule) {
1703 lowestRule = policy.limitBytes;
1704 }
1705 }
1706
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001707 // One final pass to catch any metered ifaces that don't have explicitly
1708 // defined policies; typically Wi-Fi networks.
1709 for (NetworkState state : states) {
1710 if (state.networkInfo != null && state.networkInfo.isConnected()
1711 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1712 matchingIfaces.clear();
1713 collectIfaces(matchingIfaces, state);
1714 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1715 final String iface = matchingIfaces.valueAt(j);
1716 if (!newMeteredIfaces.contains(iface)) {
1717 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1718 newMeteredIfaces.add(iface);
1719 }
1720 }
1721 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001722 }
1723
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001724 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001725 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1726 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001727 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001728 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001729 }
1730 }
1731 mMeteredIfaces = newMeteredIfaces;
1732
Jeff Sharkey9252b342018-01-19 07:58:35 +09001733 // Finally, calculate our opportunistic quotas
1734 // TODO: add experiments support to disable or tweak ratios
1735 mSubscriptionOpportunisticQuota.clear();
1736 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001737 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001738 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001739 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001740 if (plan == null) continue;
1741
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001742 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001743 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001744 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001745 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001746 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001747 // Unlimited data; let's use 20MiB/day (600MiB/month)
1748 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1749 } else {
1750 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001751 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001752 final long start = cycle.first.toInstant().toEpochMilli();
1753 final long end = cycle.second.toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001754 final Instant now = mClock.instant();
1755 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.first.getZone())
1756 .truncatedTo(ChronoUnit.DAYS)
1757 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001758 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001759 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1760 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001761 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001762 // Number of remaining days including current day
1763 final long remainingDays =
1764 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001765
1766 quotaBytes = Math.max(0, (remainingBytes / remainingDays) / 10);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001767 }
1768
1769 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1770 }
1771
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001772 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001773 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001774
1775 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001776 }
1777
1778 /**
1779 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1780 * have at least a default mobile policy defined.
1781 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001782 private void ensureActiveMobilePolicyAL() {
1783 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001784 if (mSuppressDefaultPolicy) return;
1785
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001786 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1787 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001788
Jeff Sharkey2e471452018-01-19 18:02:47 +09001789 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001790 for (int subId : subIds) {
1791 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001792 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001793 }
1794 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001795
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001796 /**
1797 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1798 * have at least a default mobile policy defined.
1799 *
1800 * @param subId to build a default policy for
1801 * @param subscriberId that we check for an existing policy
1802 * @return true if a mobile network policy was added, or false one already existed.
1803 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001804 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001805 // Poke around to see if we already have a policy
1806 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001807 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001808 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1809 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1810 if (template.matches(probeIdent)) {
1811 if (LOGD) {
1812 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1813 + NetworkIdentity.scrubSubscriberId(subscriberId));
1814 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001815 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001816 }
1817 }
1818
Jeff Sharkey32566012014-12-02 18:30:14 -08001819 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1820 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001821 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001822 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001823 return true;
1824 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001825
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001826 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001827 final int dataWarningConfig = mContext.getResources().getInteger(
1828 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001829 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001830 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001831 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001832 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001833 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001834 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001835
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001836 private long getPlatformDefaultLimitBytes() {
1837 return LIMIT_DISABLED;
1838 }
1839
1840 @VisibleForTesting
1841 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001842 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001843 final RecurrenceRule cycleRule = NetworkPolicy
1844 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001845 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001846 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1847 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1848 synchronized (mUidRulesFirstLock) {
1849 synchronized (mNetworkPoliciesSecondLock) {
1850 updateDefaultMobilePolicyAL(subId, policy);
1851 }
1852 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001853 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001854 }
1855
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001856 /**
1857 * Update the given {@link NetworkPolicy} based on any carrier-provided
1858 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1859 * Leaves policy untouched if the user has modified it.
1860 *
1861 * @return if the policy was modified
1862 */
1863 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1864 if (!policy.inferred) {
1865 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1866 return false;
1867 }
1868
1869 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1870 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1871 policy.lastLimitSnooze, policy.metered, policy.inferred);
1872
1873 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1874 if (!ArrayUtils.isEmpty(plans)) {
1875 final SubscriptionPlan plan = plans[0];
1876 policy.cycleRule = plan.getCycleRule();
1877 final long planLimitBytes = plan.getDataLimitBytes();
1878 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1879 policy.warningBytes = getPlatformDefaultWarningBytes();
1880 policy.limitBytes = getPlatformDefaultLimitBytes();
1881 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1882 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1883 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1884 } else {
1885 policy.warningBytes = (planLimitBytes * 9) / 10;
1886 switch (plan.getDataLimitBehavior()) {
1887 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1888 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1889 policy.limitBytes = planLimitBytes;
1890 break;
1891 default:
1892 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1893 break;
1894 }
1895 }
1896 } else {
1897 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1898 final int currentCycleDay;
1899 if (policy.cycleRule.isMonthly()) {
1900 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1901 } else {
1902 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1903 }
1904 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1905 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1906 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1907 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1908 }
1909
1910 if (policy.equals(original)) {
1911 return false;
1912 } else {
1913 Slog.d(TAG, "Updated " + original + " to " + policy);
1914 return true;
1915 }
1916 }
1917
Felipe Lemef0823852016-06-08 13:43:08 -07001918 private void readPolicyAL() {
1919 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001920
1921 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001922 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001923 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001924 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001925 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001926
1927 FileInputStream fis = null;
1928 try {
1929 fis = mPolicyFile.openRead();
1930 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001931 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001932
Felipe Leme46b451f2016-08-19 08:46:17 -07001933 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1934 // to skip UIDs that were explicitly blacklisted.
1935 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1936
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001937 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001938 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001939 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001940 while ((type = in.next()) != END_DOCUMENT) {
1941 final String tag = in.getName();
1942 if (type == START_TAG) {
1943 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001944 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001945 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001946 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1947 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001948 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1949 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1950 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001951 final String networkId;
1952 if (version >= VERSION_ADDED_NETWORK_ID) {
1953 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1954 } else {
1955 networkId = null;
1956 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001957 final RecurrenceRule cycleRule;
1958 if (version >= VERSION_ADDED_CYCLE) {
1959 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1960 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1961 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1962 cycleRule = new RecurrenceRule(
1963 RecurrenceRule.convertZonedDateTime(start),
1964 RecurrenceRule.convertZonedDateTime(end),
1965 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001966 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001967 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1968 final String cycleTimezone;
1969 if (version >= VERSION_ADDED_TIMEZONE) {
1970 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1971 } else {
1972 cycleTimezone = "UTC";
1973 }
1974 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001975 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001976 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1977 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001978 final long lastLimitSnooze;
1979 if (version >= VERSION_SPLIT_SNOOZE) {
1980 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1981 } else if (version >= VERSION_ADDED_SNOOZE) {
1982 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001983 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001984 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001985 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001986 final boolean metered;
1987 if (version >= VERSION_ADDED_METERED) {
1988 metered = readBooleanAttribute(in, ATTR_METERED);
1989 } else {
1990 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001991 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001992 metered = true;
1993 break;
1994 default:
1995 metered = false;
1996 }
1997 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001998 final long lastWarningSnooze;
1999 if (version >= VERSION_SPLIT_SNOOZE) {
2000 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2001 } else {
2002 lastWarningSnooze = SNOOZE_NEVER;
2003 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002004 final boolean inferred;
2005 if (version >= VERSION_ADDED_INFERRED) {
2006 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2007 } else {
2008 inferred = false;
2009 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002010
Jeff Sharkey32566012014-12-02 18:30:14 -08002011 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2012 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002013 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002014 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2015 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002016 lastLimitSnooze, metered, inferred));
2017 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002018
2019 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2020 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2021 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2022 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2023 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2024 RecurrenceRule.convertZonedDateTime(start),
2025 RecurrenceRule.convertZonedDateTime(end),
2026 RecurrenceRule.convertPeriod(period));
2027 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2028 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2029
2030 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2031 SubscriptionPlan.BYTES_UNKNOWN);
2032 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2033 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2034 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2035 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2036 builder.setDataLimit(limitBytes, limitBehavior);
2037 }
2038
2039 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2040 SubscriptionPlan.BYTES_UNKNOWN);
2041 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2042 SubscriptionPlan.TIME_UNKNOWN);
2043 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2044 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2045 builder.setDataUsage(usageBytes, usageTime);
2046 }
2047
2048 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2049 final SubscriptionPlan plan = builder.build();
2050 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2051 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2052
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002053 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2054 mSubscriptionPlansOwner.put(subId, ownerPackage);
2055
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002056 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002057 final int uid = readIntAttribute(in, ATTR_UID);
2058 final int policy = readIntAttribute(in, ATTR_POLICY);
2059
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002060 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002061 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002062 } else {
2063 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2064 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002065 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002066 final int appId = readIntAttribute(in, ATTR_APP_ID);
2067 final int policy = readIntAttribute(in, ATTR_POLICY);
2068
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002069 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002070 // app policy is deprecated so this is only used in pre system user split.
2071 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002072 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002073 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002074 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002075 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002076 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002077 } else if (TAG_WHITELIST.equals(tag)) {
2078 insideWhitelist = true;
2079 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2080 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002081 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002082 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2083 final int uid = readIntAttribute(in, ATTR_UID);
2084 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002085 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002086 } else if (type == END_TAG) {
2087 if (TAG_WHITELIST.equals(tag)) {
2088 insideWhitelist = false;
2089 }
2090
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002091 }
2092 }
2093
Felipe Leme46b451f2016-08-19 08:46:17 -07002094 final int size = whitelistedRestrictBackground.size();
2095 for (int i = 0; i < size; i++) {
2096 final int uid = whitelistedRestrictBackground.keyAt(i);
2097 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2098 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2099 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2100 + " because its policy is " + uidPoliciesToString(policy));
2101 continue;
2102 }
2103 if (UserHandle.isApp(uid)) {
2104 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2105 if (LOGV)
2106 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2107 setUidPolicyUncheckedUL(uid, newPolicy, false);
2108 } else {
2109 Slog.w(TAG, "unable to update policy on UID " + uid);
2110 }
2111 }
2112
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002113 } catch (FileNotFoundException e) {
2114 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002115 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002116 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002117 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002118 } finally {
2119 IoUtils.closeQuietly(fis);
2120 }
2121 }
2122
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002123 /**
2124 * Upgrade legacy background data flags, notifying listeners of one last
2125 * change to always-true.
2126 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002127 private void upgradeDefaultBackgroundDataUL() {
2128 // This method is only called when we're unable to find the network policy flag, which
2129 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002130
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002131 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002132 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002133 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2134
2135 // NOTE: We used to read the legacy setting here :
2136 //
2137 // final int legacyFlagValue = Settings.Secure.getInt(
2138 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2139 //
2140 // This is no longer necessary because we will never upgrade directly from Gingerbread
2141 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2142 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002143 }
2144
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002145 /**
2146 * Perform upgrade step of moving any user-defined meterness overrides over
2147 * into {@link WifiConfiguration}.
2148 */
2149 private void upgradeWifiMeteredOverrideAL() {
2150 boolean modified = false;
2151 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2152 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2153 for (int i = 0; i < mNetworkPolicy.size(); ) {
2154 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2155 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2156 && !policy.inferred) {
2157 mNetworkPolicy.removeAt(i);
2158 modified = true;
2159
2160 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2161 for (WifiConfiguration config : configs) {
2162 if (Objects.equals(resolveNetworkId(config), networkId)) {
2163 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2164 config.meteredOverride = policy.metered
2165 ? WifiConfiguration.METERED_OVERRIDE_METERED
2166 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2167 wm.updateNetwork(config);
2168 }
2169 }
2170 } else {
2171 i++;
2172 }
2173 }
2174 if (modified) {
2175 writePolicyAL();
2176 }
2177 }
2178
Felipe Lemef0823852016-06-08 13:43:08 -07002179 void writePolicyAL() {
2180 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002181
2182 FileOutputStream fos = null;
2183 try {
2184 fos = mPolicyFile.startWrite();
2185
2186 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002187 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002188 out.startDocument(null, true);
2189
2190 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002191 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002192 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002193
2194 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002195 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2196 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002197 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002198 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002199
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002200 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002201 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2202 final String subscriberId = template.getSubscriberId();
2203 if (subscriberId != null) {
2204 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002205 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002206 final String networkId = template.getNetworkId();
2207 if (networkId != null) {
2208 out.attribute(null, ATTR_NETWORK_ID, networkId);
2209 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002210 writeStringAttribute(out, ATTR_CYCLE_START,
2211 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2212 writeStringAttribute(out, ATTR_CYCLE_END,
2213 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2214 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2215 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002216 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2217 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002218 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2219 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002220 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002221 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002222 out.endTag(null, TAG_NETWORK_POLICY);
2223 }
2224
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002225 // write all known subscription plans
2226 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2227 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002228 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002229 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2230 if (ArrayUtils.isEmpty(plans)) continue;
2231
2232 for (SubscriptionPlan plan : plans) {
2233 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2234 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002235 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002236 final RecurrenceRule cycleRule = plan.getCycleRule();
2237 writeStringAttribute(out, ATTR_CYCLE_START,
2238 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2239 writeStringAttribute(out, ATTR_CYCLE_END,
2240 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2241 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2242 RecurrenceRule.convertPeriod(cycleRule.period));
2243 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2244 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2245 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2246 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2247 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2248 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2249 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2250 }
2251 }
2252
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002253 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002254 for (int i = 0; i < mUidPolicy.size(); i++) {
2255 final int uid = mUidPolicy.keyAt(i);
2256 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002257
Jeff Sharkey497e4432011-06-14 17:27:29 -07002258 // skip writing empty policies
2259 if (policy == POLICY_NONE) continue;
2260
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002261 out.startTag(null, TAG_UID_POLICY);
2262 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002263 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002264 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002265 }
2266
2267 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002268
2269 // write all whitelists
2270 out.startTag(null, TAG_WHITELIST);
2271
Felipe Lemea9505cc2016-02-26 10:28:41 -08002272 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002273 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002274 for (int i = 0; i < size; i++) {
2275 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2276 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2277 writeIntAttribute(out, ATTR_UID, uid);
2278 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2279 }
2280
Felipe Lemeb85a6372016-01-14 16:16:16 -08002281 out.endTag(null, TAG_WHITELIST);
2282
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002283 out.endDocument();
2284
2285 mPolicyFile.finishWrite(fos);
2286 } catch (IOException e) {
2287 if (fos != null) {
2288 mPolicyFile.failWrite(fos);
2289 }
2290 }
2291 }
2292
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002293 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002294 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002295 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002296
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002297 if (!UserHandle.isApp(uid)) {
2298 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002299 }
Felipe Lemef0823852016-06-08 13:43:08 -07002300 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002301 final long token = Binder.clearCallingIdentity();
2302 try {
2303 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2304 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002305 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002306 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002307 }
2308 } finally {
2309 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002310 }
2311 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002312 }
2313
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002314 @Override
2315 public void addUidPolicy(int uid, int policy) {
2316 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002317
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002318 if (!UserHandle.isApp(uid)) {
2319 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2320 }
2321
Felipe Lemef0823852016-06-08 13:43:08 -07002322 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002323 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2324 policy |= oldPolicy;
2325 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002326 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002327 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002328 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002329 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002330 }
2331
2332 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002333 public void removeUidPolicy(int uid, int policy) {
2334 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2335
2336 if (!UserHandle.isApp(uid)) {
2337 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2338 }
2339
Felipe Lemef0823852016-06-08 13:43:08 -07002340 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002341 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2342 policy = oldPolicy & ~policy;
2343 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002344 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002345 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002346 }
2347 }
2348 }
2349
Felipe Lemef0823852016-06-08 13:43:08 -07002350 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2351 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002352
Felipe Leme57e3d312016-08-23 14:42:52 -07002353 final boolean notifyApp;
2354 if (!isUidValidForWhitelistRules(uid)) {
2355 notifyApp = false;
2356 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002357 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2358 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2359 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2360 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002361 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2362 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002363 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2364 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2365 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2366 if (LOGD)
2367 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2368 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2369 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002370 notifyApp = wasBlocked != isBlocked;
2371 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002372 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2373 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002374 }
2375
Felipe Lemef0823852016-06-08 13:43:08 -07002376 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002377 if (policy == POLICY_NONE) {
2378 mUidPolicy.delete(uid);
2379 } else {
2380 mUidPolicy.put(uid, policy);
2381 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002382
2383 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002384 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002385 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002386 synchronized (mNetworkPoliciesSecondLock) {
2387 writePolicyAL();
2388 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002389 }
2390 }
2391
2392 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002393 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002394 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2395
Felipe Lemef0823852016-06-08 13:43:08 -07002396 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002397 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002398 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002399 }
2400
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002401 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002402 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002403 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2404
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002405 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002406 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002407 for (int i = 0; i < mUidPolicy.size(); i++) {
2408 final int uid = mUidPolicy.keyAt(i);
2409 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002410 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2411 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002412 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002413 }
2414 }
2415 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002416 return uids;
2417 }
2418
2419 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002420 * Removes any persistable state associated with given {@link UserHandle}, persisting
2421 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002422 */
Felipe Lemef0823852016-06-08 13:43:08 -07002423 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002424
Sudheer Shanka352dc572017-09-22 17:09:38 -07002425 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002426 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002427
Felipe Lemea110eec2016-04-29 09:58:06 -07002428 // Remove entries from revoked default restricted background UID whitelist
2429 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2430 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2431 if (UserHandle.getUserId(uid) == userId) {
2432 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002433 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002434 }
2435 }
2436
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002437 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002438 int[] uids = new int[0];
2439 for (int i = 0; i < mUidPolicy.size(); i++) {
2440 final int uid = mUidPolicy.keyAt(i);
2441 if (UserHandle.getUserId(uid) == userId) {
2442 uids = appendInt(uids, uid);
2443 }
2444 }
2445
2446 if (uids.length > 0) {
2447 for (int uid : uids) {
2448 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002449 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002450 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002451 }
Felipe Lemef0823852016-06-08 13:43:08 -07002452 synchronized (mNetworkPoliciesSecondLock) {
2453 updateRulesForGlobalChangeAL(true);
2454 if (writePolicy && changed) {
2455 writePolicyAL();
2456 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002457 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002458 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002459 }
2460
2461 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002462 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002463 // TODO: create permission for observing network policy
2464 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002465 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002466 }
2467
2468 @Override
2469 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002470 // TODO: create permission for observing network policy
2471 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002472 mListeners.unregister(listener);
2473 }
2474
Jeff Sharkey1b861272011-05-22 00:34:52 -07002475 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002476 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002477 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2478
Felipe Leme6a05eee2016-02-19 14:43:51 -08002479 final long token = Binder.clearCallingIdentity();
2480 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002481 synchronized (mUidRulesFirstLock) {
2482 synchronized (mNetworkPoliciesSecondLock) {
2483 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002484 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002485 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002486 }
2487 } finally {
2488 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002489 }
2490 }
2491
Hugo Benichi446c9c92017-04-10 09:41:10 +09002492 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002493 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002494 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2495 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002496 }
2497
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002498 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002499 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002500 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002501 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002502 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2503 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2504 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002505 } catch (SecurityException e) {
2506 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002507
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002508 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2509 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2510 return new NetworkPolicy[0];
2511 }
Svet Ganov16a16892015-04-16 10:32:04 -07002512 }
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002515 final int size = mNetworkPolicy.size();
2516 final NetworkPolicy[] policies = new NetworkPolicy[size];
2517 for (int i = 0; i < size; i++) {
2518 policies[i] = mNetworkPolicy.valueAt(i);
2519 }
2520 return policies;
2521 }
2522 }
2523
Felipe Lemef0823852016-06-08 13:43:08 -07002524 private void normalizePoliciesNL() {
2525 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002526 }
2527
Felipe Lemef0823852016-06-08 13:43:08 -07002528 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002529 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002530 final String[] merged = tele.getMergedSubscriberIds();
2531
2532 mNetworkPolicy.clear();
2533 for (NetworkPolicy policy : policies) {
2534 // When two normalized templates conflict, prefer the most
2535 // restrictive policy
2536 policy.template = NetworkTemplate.normalize(policy.template, merged);
2537 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2538 if (existing == null || existing.compareTo(policy) > 0) {
2539 if (existing != null) {
2540 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2541 }
2542 mNetworkPolicy.put(policy.template, policy);
2543 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002544 }
2545 }
2546
2547 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002548 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002550
2551 final long token = Binder.clearCallingIdentity();
2552 try {
2553 performSnooze(template, TYPE_LIMIT);
2554 } finally {
2555 Binder.restoreCallingIdentity(token);
2556 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002557 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002558
Dianne Hackborn497175b2014-07-01 12:56:08 -07002559 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002560 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002561 synchronized (mUidRulesFirstLock) {
2562 synchronized (mNetworkPoliciesSecondLock) {
2563 // find and snooze local policy that matches
2564 final NetworkPolicy policy = mNetworkPolicy.get(template);
2565 if (policy == null) {
2566 throw new IllegalArgumentException("unable to find policy for " + template);
2567 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002568
Felipe Lemef0823852016-06-08 13:43:08 -07002569 switch (type) {
2570 case TYPE_WARNING:
2571 policy.lastWarningSnooze = currentTime;
2572 break;
2573 case TYPE_LIMIT:
2574 policy.lastLimitSnooze = currentTime;
2575 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002576 case TYPE_RAPID:
2577 policy.lastRapidSnooze = currentTime;
2578 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002579 default:
2580 throw new IllegalArgumentException("unexpected type");
2581 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002582
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002583 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002584 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002585 }
2586 }
2587
2588 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002589 public void onTetheringChanged(String iface, boolean tethering) {
2590 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002591 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002592 if (mRestrictBackground && tethering) {
2593 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2594 setRestrictBackground(false);
2595 }
2596 }
2597 }
2598
2599 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002600 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002601 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002602 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002603 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2604 final long token = Binder.clearCallingIdentity();
2605 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002606 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002607 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002608 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002609 } finally {
2610 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002611 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002612 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002613 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002614 }
2615 }
2616
Felipe Lemef0823852016-06-08 13:43:08 -07002617 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002618 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002619 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002620 if (restrictBackground == mRestrictBackground) {
2621 // Ideally, UI should never allow this scenario...
2622 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002623 return;
2624 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002625 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2626 final boolean oldRestrictBackground = mRestrictBackground;
2627 mRestrictBackground = restrictBackground;
2628 // Must whitelist foreground apps before turning data saver mode on.
2629 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2630 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2631 updateRulesForRestrictBackgroundUL();
2632 try {
2633 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2634 Slog.e(TAG,
2635 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2636 mRestrictBackground = oldRestrictBackground;
2637 // TODO: if it knew the foreground apps (see TODO above), it could call
2638 // updateRulesForRestrictBackgroundUL() again to restore state.
2639 return;
2640 }
2641 } catch (RemoteException e) {
2642 // ignored; service lives in system_server
2643 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002644
Sudheer Shanka543339f2017-07-28 15:18:07 -07002645 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002646 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002647
2648 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2649 mRestrictBackgroundChangedInBsm = true;
2650 }
2651 synchronized (mNetworkPoliciesSecondLock) {
2652 updateNotificationsNL();
2653 writePolicyAL();
2654 }
2655 } finally {
2656 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002657 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002658 }
2659
2660 private void sendRestrictBackgroundChangedMsg() {
2661 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2662 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2663 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002664 }
2665
Felipe Lemeb85a6372016-01-14 16:16:16 -08002666 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002667 public int getRestrictBackgroundByCaller() {
2668 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2669 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002670
Felipe Lemef0823852016-06-08 13:43:08 -07002671 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002672 // Must clear identity because getUidPolicy() is restricted to system.
2673 final long token = Binder.clearCallingIdentity();
2674 final int policy;
2675 try {
2676 policy = getUidPolicy(uid);
2677 } finally {
2678 Binder.restoreCallingIdentity(token);
2679 }
2680 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2681 // App is blacklisted.
2682 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2683 }
Felipe Leme1b103232016-01-22 09:44:57 -08002684 if (!mRestrictBackground) {
2685 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2686 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002687 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002688 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2689 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2690 }
2691 }
2692
2693 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002694 public boolean getRestrictBackground() {
2695 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2696
Felipe Lemef0823852016-06-08 13:43:08 -07002697 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002698 return mRestrictBackground;
2699 }
2700 }
2701
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002702 @Override
2703 public void setDeviceIdleMode(boolean enabled) {
2704 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002705 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2706 try {
2707 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002708 if (mDeviceIdleMode == enabled) {
2709 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002710 }
Felipe Lemeea014392016-09-06 13:59:54 -07002711 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002712 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002713 if (mSystemReady) {
2714 // Device idle change means we need to rebuild rules for all
2715 // known apps, so do a global refresh.
2716 updateRulesForRestrictPowerUL();
2717 }
2718 }
2719 if (enabled) {
2720 EventLogTags.writeDeviceIdleOnPhase("net");
2721 } else {
2722 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002723 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002724 } finally {
2725 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002726 }
2727 }
2728
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002729 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002730 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2731 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002732 final long token = Binder.clearCallingIdentity();
2733 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002734 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2735 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2736 for (WifiConfiguration config : configs) {
2737 if (Objects.equals(resolveNetworkId(config), networkId)) {
2738 config.meteredOverride = meteredOverride;
2739 wm.updateNetwork(config);
2740 }
2741 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002742 } finally {
2743 Binder.restoreCallingIdentity(token);
2744 }
2745 }
2746
Jeff Sharkey46645002011-07-27 21:11:21 -07002747 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002748 @Deprecated
2749 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2750 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2751 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2752 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002753 }
2754
Jeff Sharkey53313d72017-07-13 16:47:32 -06002755 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2756 // Verify they're not lying about package name
2757 mAppOps.checkPackage(callingUid, callingPackage);
2758
Jeff Sharkey53313d72017-07-13 16:47:32 -06002759 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002760 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002761 final long token = Binder.clearCallingIdentity();
2762 try {
2763 si = mContext.getSystemService(SubscriptionManager.class)
2764 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002765 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002766 } finally {
2767 Binder.restoreCallingIdentity(token);
2768 }
2769
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002770 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002771 if (si != null) {
2772 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2773 return;
2774 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002775 }
2776
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002777 // Second check: has the CarrierService delegated access?
2778 if (config != null) {
2779 final String overridePackage = config
2780 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2781 if (!TextUtils.isEmpty(overridePackage)
2782 && Objects.equals(overridePackage, callingPackage)) {
2783 return;
2784 }
2785 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002786
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002787 // Third check: is caller the fallback/default CarrierService?
2788 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2789 if (!TextUtils.isEmpty(defaultPackage)
2790 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002791 return;
2792 }
2793
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002794 // Fourth check: is caller a testing app on a debug build?
2795 final boolean enableDebug = Build.IS_USERDEBUG || Build.IS_ENG;
2796 if (enableDebug && callingPackage
2797 .equals(SystemProperties.get("fw.sub_plan_owner." + subId, null))) {
2798 return;
2799 }
2800
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002801 // Final check: does the caller hold a permission?
2802 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002803 }
2804
2805 @Override
2806 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2807 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2808
Jeff Sharkey53313d72017-07-13 16:47:32 -06002809 final String fake = SystemProperties.get("fw.fake_plan");
2810 if (!TextUtils.isEmpty(fake)) {
2811 final List<SubscriptionPlan> plans = new ArrayList<>();
2812 if ("month_hard".equals(fake)) {
2813 plans.add(SubscriptionPlan.Builder
2814 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2815 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002816 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2817 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2818 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2819 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2820 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002821 plans.add(SubscriptionPlan.Builder
2822 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2823 .setTitle("G-Mobile Happy")
2824 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2825 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2826 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2827 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2828 .build());
2829 plans.add(SubscriptionPlan.Builder
2830 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2831 .setTitle("G-Mobile, Charged after limit")
2832 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2833 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2834 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2835 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2836 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002837 } else if ("month_soft".equals(fake)) {
2838 plans.add(SubscriptionPlan.Builder
2839 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2840 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2841 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2842 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002843 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2844 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2845 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2846 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2847 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002848 plans.add(SubscriptionPlan.Builder
2849 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2850 .setTitle("G-Mobile, Throttled after limit")
2851 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2852 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2853 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2854 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2855 .build());
2856 plans.add(SubscriptionPlan.Builder
2857 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2858 .setTitle("G-Mobile, No data connection after limit")
2859 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2860 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2861 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2862 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2863 .build());
2864
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002865 } else if ("month_over".equals(fake)) {
2866 plans.add(SubscriptionPlan.Builder
2867 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2868 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2869 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2870 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2871 .setDataUsage(6 * 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, Throttled after limit")
2877 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2878 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2879 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2880 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2881 .build());
2882 plans.add(SubscriptionPlan.Builder
2883 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2884 .setTitle("G-Mobile, No data connection after limit")
2885 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2886 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2887 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2888 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2889 .build());
2890
Jeff Sharkey53313d72017-07-13 16:47:32 -06002891 } else if ("month_none".equals(fake)) {
2892 plans.add(SubscriptionPlan.Builder
2893 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2894 .setTitle("G-Mobile")
2895 .build());
2896 } else if ("prepaid".equals(fake)) {
2897 plans.add(SubscriptionPlan.Builder
2898 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2899 ZonedDateTime.now().plusDays(10))
2900 .setTitle("G-Mobile")
2901 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2902 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2903 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2904 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2905 .build());
2906 } else if ("prepaid_crazy".equals(fake)) {
2907 plans.add(SubscriptionPlan.Builder
2908 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2909 ZonedDateTime.now().plusDays(10))
2910 .setTitle("G-Mobile Anytime")
2911 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2912 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2913 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2914 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2915 .build());
2916 plans.add(SubscriptionPlan.Builder
2917 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2918 ZonedDateTime.now().plusDays(20))
2919 .setTitle("G-Mobile Nickel Nights")
2920 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002921 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2922 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002923 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2924 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2925 .build());
2926 plans.add(SubscriptionPlan.Builder
2927 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2928 ZonedDateTime.now().plusDays(20))
2929 .setTitle("G-Mobile Bonus 3G")
2930 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002931 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002932 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2933 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2934 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2935 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002936 } else if ("unlimited".equals(fake)) {
2937 plans.add(SubscriptionPlan.Builder
2938 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2939 ZonedDateTime.now().plusDays(10))
2940 .setTitle("G-Mobile Awesome")
2941 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2942 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2943 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2944 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2945 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002946 }
2947 return plans.toArray(new SubscriptionPlan[plans.size()]);
2948 }
2949
Jeff Sharkey4635f102017-09-01 11:27:13 -06002950 synchronized (mNetworkPoliciesSecondLock) {
2951 // Only give out plan details to the package that defined them,
2952 // so that we don't risk leaking plans between apps. We always
2953 // let in core system components (like the Settings app).
2954 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2955 if (Objects.equals(ownerPackage, callingPackage)
2956 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2957 return mSubscriptionPlans.get(subId);
2958 } else {
2959 Log.w(TAG, "Not returning plans because caller " + callingPackage
2960 + " doesn't match owner " + ownerPackage);
2961 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002962 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002963 }
2964 }
2965
2966 @Override
2967 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2968 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2969
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002970 for (SubscriptionPlan plan : plans) {
2971 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002972 }
2973
2974 final long token = Binder.clearCallingIdentity();
2975 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002976 synchronized (mUidRulesFirstLock) {
2977 synchronized (mNetworkPoliciesSecondLock) {
2978 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002979 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002980
2981 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2982 .getSubscriberId(subId);
2983 ensureActiveMobilePolicyAL(subId, subscriberId);
2984 maybeUpdateMobilePolicyCycleAL(subId);
2985 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002986 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002987 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002988
2989 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2990 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2991 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2992 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002993 } finally {
2994 Binder.restoreCallingIdentity(token);
2995 }
2996 }
2997
2998 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002999 public String getSubscriptionPlansOwner(int subId) {
3000 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3001 throw new SecurityException();
3002 }
3003
3004 synchronized (mNetworkPoliciesSecondLock) {
3005 return mSubscriptionPlansOwner.get(subId);
3006 }
3007 }
3008
3009 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003010 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3011 long timeoutMillis, String callingPackage) {
3012 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3013
3014 // We can only override when carrier told us about plans
3015 synchronized (mNetworkPoliciesSecondLock) {
3016 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3017 throw new IllegalStateException(
3018 "Must provide SubscriptionPlan information before overriding");
3019 }
3020 }
3021
3022 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3023 overrideMask, overrideValue, subId));
3024 if (timeoutMillis > 0) {
3025 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3026 overrideMask, 0, subId), timeoutMillis);
3027 }
3028 }
3029
3030 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003031 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003032 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003033
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003034 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3035
Dianne Hackborn497175b2014-07-01 12:56:08 -07003036 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003037 for (String arg : args) {
3038 argSet.add(arg);
3039 }
3040
Felipe Lemef0823852016-06-08 13:43:08 -07003041 synchronized (mUidRulesFirstLock) {
3042 synchronized (mNetworkPoliciesSecondLock) {
3043 if (argSet.contains("--unsnooze")) {
3044 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3045 mNetworkPolicy.valueAt(i).clearSnooze();
3046 }
3047
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003048 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003049
3050 fout.println("Cleared snooze timestamps");
3051 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003052 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003053
Felipe Lemef0823852016-06-08 13:43:08 -07003054 fout.print("System ready: "); fout.println(mSystemReady);
3055 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3056 fout.print("Restrict power: "); fout.println(mRestrictPower);
3057 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003058 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3059
3060 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003061 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003062 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003063 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3064 fout.println(mNetworkPolicy.valueAt(i).toString());
3065 }
3066 fout.decreaseIndent();
3067
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003068 fout.println();
3069 fout.println("Subscription plans:");
3070 fout.increaseIndent();
3071 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3072 final int subId = mSubscriptionPlans.keyAt(i);
3073 fout.println("Subscriber ID " + subId + ":");
3074 fout.increaseIndent();
3075 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3076 if (!ArrayUtils.isEmpty(plans)) {
3077 for (SubscriptionPlan plan : plans) {
3078 fout.println(plan);
3079 }
3080 }
3081 fout.decreaseIndent();
3082 }
3083 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003084
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003085 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003086 fout.println("Policy for UIDs:");
3087 fout.increaseIndent();
3088 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003089 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003090 final int uid = mUidPolicy.keyAt(i);
3091 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003092 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003093 fout.print(uid);
3094 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003095 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003096 fout.println();
3097 }
3098 fout.decreaseIndent();
3099
3100 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3101 if (size > 0) {
3102 fout.println("Power save whitelist (except idle) app ids:");
3103 fout.increaseIndent();
3104 for (int i = 0; i < size; i++) {
3105 fout.print("UID=");
3106 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3107 fout.print(": ");
3108 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3109 fout.println();
3110 }
3111 fout.decreaseIndent();
3112 }
3113
3114 size = mPowerSaveWhitelistAppIds.size();
3115 if (size > 0) {
3116 fout.println("Power save whitelist app ids:");
3117 fout.increaseIndent();
3118 for (int i = 0; i < size; i++) {
3119 fout.print("UID=");
3120 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3121 fout.print(": ");
3122 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3123 fout.println();
3124 }
3125 fout.decreaseIndent();
3126 }
3127
Felipe Lemef0823852016-06-08 13:43:08 -07003128 size = mDefaultRestrictBackgroundWhitelistUids.size();
3129 if (size > 0) {
3130 fout.println("Default restrict background whitelist uids:");
3131 fout.increaseIndent();
3132 for (int i = 0; i < size; i++) {
3133 fout.print("UID=");
3134 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3135 fout.println();
3136 }
3137 fout.decreaseIndent();
3138 }
3139
3140 size = mRestrictBackgroundWhitelistRevokedUids.size();
3141 if (size > 0) {
3142 fout.println("Default restrict background whitelist uids revoked by users:");
3143 fout.increaseIndent();
3144 for (int i = 0; i < size; i++) {
3145 fout.print("UID=");
3146 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3147 fout.println();
3148 }
3149 fout.decreaseIndent();
3150 }
3151
3152 final SparseBooleanArray knownUids = new SparseBooleanArray();
3153 collectKeys(mUidState, knownUids);
3154 collectKeys(mUidRules, knownUids);
3155
3156 fout.println("Status for all known UIDs:");
3157 fout.increaseIndent();
3158 size = knownUids.size();
3159 for (int i = 0; i < size; i++) {
3160 final int uid = knownUids.keyAt(i);
3161 fout.print("UID=");
3162 fout.print(uid);
3163
3164 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3165 fout.print(" state=");
3166 fout.print(state);
3167 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3168 fout.print(" (fg)");
3169 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003170 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003171 ? " (fg svc)" : " (bg)");
3172 }
3173
3174 final int uidRules = mUidRules.get(uid, RULE_NONE);
3175 fout.print(" rules=");
3176 fout.print(uidRulesToString(uidRules));
3177 fout.println();
3178 }
3179 fout.decreaseIndent();
3180
3181 fout.println("Status for just UIDs with rules:");
3182 fout.increaseIndent();
3183 size = mUidRules.size();
3184 for (int i = 0; i < size; i++) {
3185 final int uid = mUidRules.keyAt(i);
3186 fout.print("UID=");
3187 fout.print(uid);
3188 final int uidRules = mUidRules.get(uid, RULE_NONE);
3189 fout.print(" rules=");
3190 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003191 fout.println();
3192 }
3193 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003194
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003195 fout.println("Admin restricted uids for metered data:");
3196 fout.increaseIndent();
3197 size = mMeteredRestrictedUids.size();
3198 for (int i = 0; i < size; ++i) {
3199 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3200 fout.println(mMeteredRestrictedUids.valueAt(i));
3201 }
3202 fout.decreaseIndent();
3203
Sudheer Shanka352dc572017-09-22 17:09:38 -07003204 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003205 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003206 }
3207 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003208
3209 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003210 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003211 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003212 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003213 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003214 }
3215
3216 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003217 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003218 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3219
Felipe Lemef0823852016-06-08 13:43:08 -07003220 synchronized (mUidRulesFirstLock) {
3221 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003222 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003223 }
3224
Felipe Lemef0823852016-06-08 13:43:08 -07003225 private boolean isUidForegroundUL(int uid) {
3226 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003227 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3228 }
3229
Felipe Lemef0823852016-06-08 13:43:08 -07003230 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003231 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003232 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003233 }
3234
Felipe Lemef0823852016-06-08 13:43:08 -07003235 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003236 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3237 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3238 }
3239
Felipe Lemef0823852016-06-08 13:43:08 -07003240 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003241 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003242 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003243 }
3244
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003245 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003246 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003247 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3248 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003249 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003250 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003251 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3252 try {
3253 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3254 if (oldUidState != uidState) {
3255 // state changed, push updated rules
3256 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003257 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3258 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3259 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003260 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003261 if (mDeviceIdleMode) {
3262 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003263 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003264 if (mRestrictPower) {
3265 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003266 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003267 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003268 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003269 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003270 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003271 } finally {
3272 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003273 }
3274 }
3275
Felipe Lemef0823852016-06-08 13:43:08 -07003276 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003277 final int index = mUidState.indexOfKey(uid);
3278 if (index >= 0) {
3279 final int oldUidState = mUidState.valueAt(index);
3280 mUidState.removeAt(index);
3281 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003282 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003283 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003284 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003285 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003286 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003287 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003288 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003289 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003290 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003291 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003292 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003293 }
3294 }
3295
Felipe Lemef28983d2016-03-25 12:18:23 -07003296 // adjust stats accounting based on foreground status
3297 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003298 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3299 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3300 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3301 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003302 try {
3303 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003304 } finally {
3305 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003306 }
3307 }
3308
Sudheer Shankac9d94072017-02-22 22:13:55 +00003309 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3310 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003311 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003312 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003313 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003314 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003315 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003316 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003317 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003318 }
3319
Felipe Lemef0823852016-06-08 13:43:08 -07003320 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003321 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3322 try {
3323 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3324 mUidFirewallPowerSaveRules);
3325 } finally {
3326 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3327 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003328 }
3329
Felipe Lemef0823852016-06-08 13:43:08 -07003330 void updateRuleForRestrictPowerUL(int uid) {
3331 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003332 }
3333
Felipe Lemef0823852016-06-08 13:43:08 -07003334 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003335 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3336 try {
3337 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3338 mUidFirewallDozableRules);
3339 } finally {
3340 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3341 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003342 }
3343
Felipe Lemef0823852016-06-08 13:43:08 -07003344 void updateRuleForDeviceIdleUL(int uid) {
3345 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003346 }
3347
Felipe Lemef28983d2016-03-25 12:18:23 -07003348 // NOTE: since both fw_dozable and fw_powersave uses the same map
3349 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003350 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003351 SparseIntArray rules) {
3352 if (enabled) {
3353 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003354 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003355 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003356 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003357 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003358 for (int ui = users.size() - 1; ui >= 0; ui--) {
3359 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003360 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3361 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3362 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3363 updateRulesForWhitelistedAppIds(uidRules,
3364 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003365 }
3366 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003367 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003368 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003369 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3370 }
3371 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003372 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003373 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003374 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003375 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003376 }
3377
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003378 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3379 final SparseBooleanArray whitelistedAppIds, int userId) {
3380 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3381 if (whitelistedAppIds.valueAt(i)) {
3382 final int appId = whitelistedAppIds.keyAt(i);
3383 final int uid = UserHandle.getUid(userId, appId);
3384 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3385 }
3386 }
3387 }
3388
3389 /**
3390 * @param deviceIdleMode if true then we don't consider
3391 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3392 * whitelisted.
3393 */
3394 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003395 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003396 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3397 || mPowerSaveWhitelistAppIds.get(appId);
3398 if (!deviceIdleMode) {
3399 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3400 }
3401 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003402 }
3403
Felipe Lemef28983d2016-03-25 12:18:23 -07003404 // NOTE: since both fw_dozable and fw_powersave uses the same map
3405 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003406 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003407 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003408 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3409 chain == FIREWALL_CHAIN_DOZABLE);
3410 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003411 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003412 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003413 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003414 }
3415 }
3416 }
3417
Felipe Lemef0823852016-06-08 13:43:08 -07003418 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003419 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3420 try {
3421 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3422 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003423
Felipe Leme873a83a2016-09-07 11:34:10 -07003424 // Fully update the app idle firewall chain.
3425 final List<UserInfo> users = mUserManager.getUsers();
3426 for (int ui = users.size() - 1; ui >= 0; ui--) {
3427 UserInfo user = users.get(ui);
3428 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3429 for (int uid : idleUids) {
3430 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3431 // quick check: if this uid doesn't have INTERNET permission, it
3432 // doesn't have network access anyway, so it is a waste to mess
3433 // with it here.
3434 if (hasInternetPermissions(uid)) {
3435 uidRules.put(uid, FIREWALL_RULE_DENY);
3436 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003437 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003438 }
3439 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003440
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003441 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003442 } finally {
3443 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3444 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003445 }
3446
Felipe Lemef0823852016-06-08 13:43:08 -07003447 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003448 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003449
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003450 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3451 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3452 }
3453 try {
3454 int appId = UserHandle.getAppId(uid);
3455 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3456 && !isUidForegroundOnRestrictPowerUL(uid)) {
3457 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3458 } else {
3459 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3460 }
3461 } finally {
3462 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003463 }
3464 }
3465
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003466 /**
3467 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3468 * changed.
3469 */
Felipe Lemef0823852016-06-08 13:43:08 -07003470 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003471 boolean paroled = mUsageStats.isAppIdleParoleOn();
3472 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003473 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003474
3475 int ruleCount = mUidFirewallStandbyRules.size();
3476 for (int i = 0; i < ruleCount; i++) {
3477 int uid = mUidFirewallStandbyRules.keyAt(i);
3478 int oldRules = mUidRules.get(uid);
3479 if (enableChain) {
3480 // Chain wasn't enabled before and the other power-related
3481 // chains are whitelists, so we can clear the
3482 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3483 // the effective rules result in blocking network access.
3484 oldRules &= MASK_METERED_NETWORKS;
3485 } else {
3486 // Skip if it had no restrictions to begin with
3487 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3488 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003489 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3490 if (newUidRules == RULE_NONE) {
3491 mUidRules.delete(uid);
3492 } else {
3493 mUidRules.put(uid, newUidRules);
3494 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003495 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003496 }
3497
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003498 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003499 * Update rules that might be changed by {@link #mRestrictBackground},
3500 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003501 */
Felipe Lemef0823852016-06-08 13:43:08 -07003502 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003503 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3504 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3505 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3506 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003507 try {
Felipe Leme09700462016-09-08 09:33:48 -07003508 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003509 updateRulesForRestrictPowerUL();
3510 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003511
Felipe Leme873a83a2016-09-07 11:34:10 -07003512 // If the set of restricted networks may have changed, re-evaluate those.
3513 if (restrictedNetworksChanged) {
3514 normalizePoliciesNL();
3515 updateNetworkRulesNL();
3516 }
3517 } finally {
3518 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003519 }
3520 }
3521
Felipe Leme09700462016-09-08 09:33:48 -07003522 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003523 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003524 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3525 try {
3526 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003527 updateRulesForPowerSaveUL();
3528 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3529 } finally {
3530 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3531 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003532 }
3533
Felipe Lemef0823852016-06-08 13:43:08 -07003534 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003535 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3536 try {
3537 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3538 } finally {
3539 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3540 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003541 }
3542
3543 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3544 private static final int TYPE_RESTRICT_POWER = 2;
3545 @Retention(RetentionPolicy.SOURCE)
3546 @IntDef(flag = false, value = {
3547 TYPE_RESTRICT_BACKGROUND,
3548 TYPE_RESTRICT_POWER,
3549 })
3550 public @interface RestrictType {
3551 }
3552
3553 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003554 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003555 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3556 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3557 }
3558 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003559 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003560
3561 final PackageManager pm = mContext.getPackageManager();
3562 final List<UserInfo> users;
3563 final List<ApplicationInfo> apps;
3564
3565 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3566 try {
3567 users = mUserManager.getUsers();
3568 } finally {
3569 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3570 }
3571 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3572 try {
3573 apps = pm.getInstalledApplications(
3574 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3575 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3576 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3577 } finally {
3578 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3579 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003580
Felipe Leme873a83a2016-09-07 11:34:10 -07003581 final int usersSize = users.size();
3582 final int appsSize = apps.size();
3583 for (int i = 0; i < usersSize; i++) {
3584 final UserInfo user = users.get(i);
3585 for (int j = 0; j < appsSize; j++) {
3586 final ApplicationInfo app = apps.get(j);
3587 final int uid = UserHandle.getUid(user.id, app.uid);
3588 switch (type) {
3589 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003590 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003591 break;
3592 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003593 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003594 break;
3595 default:
3596 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3597 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003598 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003599 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003600 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003601 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003602 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003603 }
3604
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003605 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003606 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003607 final int numUsers = users.size();
3608 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003609 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003610 int uid = UserHandle.getUid(user.id, appId);
3611 // Update external firewall rules.
3612 updateRuleForAppIdleUL(uid);
3613 updateRuleForDeviceIdleUL(uid);
3614 updateRuleForRestrictPowerUL(uid);
3615 // Update internal rules.
3616 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003617 }
3618 }
3619
Felipe Leme70c57c22016-03-29 10:45:13 -07003620 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3621 // methods below could be merged into a isUidValidForRules() method.
3622 private boolean isUidValidForBlacklistRules(int uid) {
3623 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003624 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003625 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003626 return true;
3627 }
3628
3629 return false;
3630 }
3631
Felipe Leme70c57c22016-03-29 10:45:13 -07003632 private boolean isUidValidForWhitelistRules(int uid) {
3633 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3634 }
3635
Amith Yamasani15e472352015-04-24 19:06:07 -07003636 private boolean isUidIdle(int uid) {
3637 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3638 final int userId = UserHandle.getUserId(uid);
3639
songjinshi0655edd2016-05-18 19:55:32 +08003640 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003641 for (String packageName : packages) {
3642 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3643 return false;
3644 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003645 }
3646 }
3647 return true;
3648 }
3649
3650 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003651 * Checks if an uid has INTERNET permissions.
3652 * <p>
3653 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003654 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003655 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003656 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003657 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003658 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003659 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003660 }
3661 } catch (RemoteException e) {
3662 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003663 return true;
3664 }
3665
3666 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003667 * Clears all state - internal and external - associated with an UID.
3668 */
3669 private void onUidDeletedUL(int uid) {
3670 // First cleanup in-memory state synchronously...
3671 mUidRules.delete(uid);
3672 mUidPolicy.delete(uid);
3673 mUidFirewallStandbyRules.delete(uid);
3674 mUidFirewallDozableRules.delete(uid);
3675 mUidFirewallPowerSaveRules.delete(uid);
3676 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3677 mPowerSaveWhitelistAppIds.delete(uid);
3678 mPowerSaveTempWhitelistAppIds.delete(uid);
3679
3680 // ...then update iptables asynchronously.
3681 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3682 }
3683
3684 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003685 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003686 *
Felipe Leme781ba142016-05-09 16:24:48 -07003687 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003688 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003689 * <li>Doze mode
3690 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003691 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003692 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003693 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003694 *
3695 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003696 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003697 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003698 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003699 updateRuleForDeviceIdleUL(uid);
3700 updateRuleForAppIdleUL(uid);
3701 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003702
3703 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003704 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003705
3706 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003707 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003708 }
3709
Felipe Leme70c57c22016-03-29 10:45:13 -07003710 /**
3711 * Applies network rules to bandwidth controllers based on process state and user-defined
3712 * restrictions (blacklist / whitelist).
3713 *
3714 * <p>
3715 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3716 * networks:
3717 * <ul>
3718 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3719 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3720 * also blacklisted.
3721 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3722 * no UIDs other those whitelisted will have access.
3723 * <ul>
3724 *
3725 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3726 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3727 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3728 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003729 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003730 * {@link INetworkManagementService}, but this method should also be called in events (like
3731 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3732 * following rules should also be applied:
3733 *
3734 * <ul>
3735 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3736 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3737 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3738 * {@code bw_penalty_box}.
3739 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3740 * </ul>
3741 *
3742 * <p>For optimization, the rules are only applied on user apps that have internet access
3743 * permission, since there is no need to change the {@code iptables} rule if the app does not
3744 * have permission to use the internet.
3745 *
3746 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003747 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003748 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003749 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003750 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3751 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3752 "updateRulesForDataUsageRestrictionsUL: " + uid);
3753 }
3754 try {
3755 updateRulesForDataUsageRestrictionsULInner(uid);
3756 } finally {
3757 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3758 }
3759 }
3760
3761 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003762 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003763 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003764 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003765 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003766
Dianne Hackborn497175b2014-07-01 12:56:08 -07003767 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003768 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003769 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003770 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003771
Felipe Leme781ba142016-05-09 16:24:48 -07003772 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003773 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003774 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3775 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003776
Felipe Leme70c57c22016-03-29 10:45:13 -07003777 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003778 if (isRestrictedByAdmin) {
3779 newRule = RULE_REJECT_METERED;
3780 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003781 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3782 newRule = RULE_TEMPORARY_ALLOW_METERED;
3783 } else if (isWhitelisted) {
3784 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003785 }
3786 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003787 if (isBlacklisted) {
3788 newRule = RULE_REJECT_METERED;
3789 } else if (mRestrictBackground && isWhitelisted) {
3790 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003791 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003792 }
Felipe Leme781ba142016-05-09 16:24:48 -07003793 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003794
Felipe Lemef28983d2016-03-25 12:18:23 -07003795 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003796 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003797 + ": isForeground=" +isForeground
3798 + ", isBlacklisted=" + isBlacklisted
3799 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003800 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003801 + ", oldRule=" + uidRulesToString(oldRule)
3802 + ", newRule=" + uidRulesToString(newRule)
3803 + ", newUidRules=" + uidRulesToString(newUidRules)
3804 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003805 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003806
Felipe Leme46c4fc32016-05-04 09:21:43 -07003807 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003808 mUidRules.delete(uid);
3809 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003810 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003811 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003812
Felipe Leme70c57c22016-03-29 10:45:13 -07003813 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003814 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003815 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003816 // Temporarily whitelist foreground app, removing from blacklist if necessary
3817 // (since bw_penalty_box prevails over bw_happy_box).
3818
3819 setMeteredNetworkWhitelist(uid, true);
3820 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3821 // but ideally it should be just:
3822 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003823 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003824 setMeteredNetworkBlacklist(uid, false);
3825 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003826 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003827 // Remove temporary whitelist from app that is not on foreground anymore.
3828
3829 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3830 // but ideally they should be just:
3831 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3832 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003833 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003834 setMeteredNetworkWhitelist(uid, false);
3835 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003836 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003837 setMeteredNetworkBlacklist(uid, true);
3838 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003839 } else if (hasRule(newRule, RULE_REJECT_METERED)
3840 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003841 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003842 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003843 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003844 // Since blacklist prevails over whitelist, we need to handle the special case
3845 // where app is whitelisted and blacklisted at the same time (although such
3846 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003847 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003848 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003849 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3850 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003851 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003852 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003853 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003854 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003855 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3856 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003857 + ", whitelisted=" + isWhitelisted
3858 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003859 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003860 + ", newRule=" + uidRulesToString(newUidRules)
3861 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003862 }
Felipe Leme781ba142016-05-09 16:24:48 -07003863
Sudheer Shankac9d94072017-02-22 22:13:55 +00003864 // Dispatch changed rule to existing listeners.
3865 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003866 }
3867 }
3868
3869 /**
3870 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3871 * listeners in case of change.
3872 * <p>
3873 * There are 3 power-related rules that affects whether an app has background access on
3874 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3875 * restriction, it's added to the equivalent firewall chain:
3876 * <ul>
3877 * <li>App is idle: {@code fw_standby} firewall chain.
3878 * <li>Device is idle: {@code fw_dozable} firewall chain.
3879 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3880 * </ul>
3881 * <p>
3882 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3883 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3884 * <p>
3885 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3886 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003887 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003888 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3889
Sudheer Shankac9d94072017-02-22 22:13:55 +00003890 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003891
Sudheer Shankac9d94072017-02-22 22:13:55 +00003892 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003893 mUidRules.delete(uid);
3894 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003895 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003896 }
3897 }
3898
3899 /**
3900 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3901 *
3902 * @param uid the uid of the app to update rules for
3903 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3904 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3905 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003906 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003907 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003908 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003909 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3910 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3911 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3912 + (paroled ? "P" : "-"));
3913 }
3914 try {
3915 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3916 } finally {
3917 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3918 }
3919 }
3920
3921 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003922 if (!isUidValidForBlacklistRules(uid)) {
3923 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003924 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003925 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003926
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003927 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003928 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003929 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003930
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003931 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003932 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3933 int newRule = RULE_NONE;
3934
3935 // First step: define the new rule based on user restrictions and foreground state.
3936
3937 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3938 // by considering the foreground and non-foreground states.
3939 if (isForeground) {
3940 if (restrictMode) {
3941 newRule = RULE_ALLOW_ALL;
3942 }
3943 } else if (restrictMode) {
3944 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3945 }
3946
3947 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3948
3949 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003950 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003951 + ", isIdle: " + isIdle
3952 + ", mRestrictPower: " + mRestrictPower
3953 + ", mDeviceIdleMode: " + mDeviceIdleMode
3954 + ", isForeground=" + isForeground
3955 + ", isWhitelisted=" + isWhitelisted
3956 + ", oldRule=" + uidRulesToString(oldRule)
3957 + ", newRule=" + uidRulesToString(newRule)
3958 + ", newUidRules=" + uidRulesToString(newUidRules)
3959 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3960 }
3961
Felipe Leme781ba142016-05-09 16:24:48 -07003962 // Second step: notify listeners if state changed.
3963 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003964 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003965 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003966 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003967 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3968 } else {
3969 // All scenarios should have been covered above
3970 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3971 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003972 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003973 + ", newRule=" + uidRulesToString(newUidRules)
3974 + ", oldRule=" + uidRulesToString(oldUidRules));
3975 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003976 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003977 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003978
Sudheer Shankac9d94072017-02-22 22:13:55 +00003979 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003980 }
3981
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003982 private class AppIdleStateChangeListener
3983 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3984
3985 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08003986 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
3987 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003988 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003989 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3990 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003991 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003992 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003993 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003994 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003995 }
3996 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003997 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003998 }
3999
4000 @Override
4001 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004002 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004003 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004004 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004005 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004006 }
4007 }
4008
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004009 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4010 if (listener != null) {
4011 try {
4012 listener.onUidRulesChanged(uid, uidRules);
4013 } catch (RemoteException ignored) {
4014 }
4015 }
4016 }
4017
4018 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4019 String[] meteredIfaces) {
4020 if (listener != null) {
4021 try {
4022 listener.onMeteredIfacesChanged(meteredIfaces);
4023 } catch (RemoteException ignored) {
4024 }
4025 }
4026 }
4027
4028 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4029 boolean restrictBackground) {
4030 if (listener != null) {
4031 try {
4032 listener.onRestrictBackgroundChanged(restrictBackground);
4033 } catch (RemoteException ignored) {
4034 }
4035 }
4036 }
4037
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004038 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4039 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004040 if (listener != null) {
4041 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004042 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004043 } catch (RemoteException ignored) {
4044 }
4045 }
4046 }
4047
Jeff Sharkey9252b342018-01-19 07:58:35 +09004048 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4049 int overrideMask, int overrideValue) {
4050 if (listener != null) {
4051 try {
4052 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4053 } catch (RemoteException ignored) {
4054 }
4055 }
4056 }
4057
Makoto Onuki8e777332017-03-28 11:25:47 -07004058 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004059 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004060 public boolean handleMessage(Message msg) {
4061 switch (msg.what) {
4062 case MSG_RULES_CHANGED: {
4063 final int uid = msg.arg1;
4064 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004065 final int length = mListeners.beginBroadcast();
4066 for (int i = 0; i < length; i++) {
4067 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4068 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004069 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004070 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004071 return true;
4072 }
4073 case MSG_METERED_IFACES_CHANGED: {
4074 final String[] meteredIfaces = (String[]) msg.obj;
4075 final int length = mListeners.beginBroadcast();
4076 for (int i = 0; i < length; i++) {
4077 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004078 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004079 }
4080 mListeners.finishBroadcast();
4081 return true;
4082 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004083 case MSG_LIMIT_REACHED: {
4084 final String iface = (String) msg.obj;
4085
Felipe Lemef0823852016-06-08 13:43:08 -07004086 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004087 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004088 // force stats update to make sure we have
4089 // numbers that caused alert to trigger.
4090 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004091
Felipe Lemef0823852016-06-08 13:43:08 -07004092 updateNetworkEnabledNL();
4093 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004094 }
4095 }
4096 return true;
4097 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004098 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4099 final boolean restrictBackground = msg.arg1 != 0;
4100 final int length = mListeners.beginBroadcast();
4101 for (int i = 0; i < length; i++) {
4102 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004103 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004104 }
4105 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004106 final Intent intent =
4107 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4108 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4109 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4110 return true;
4111 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004112 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004113 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004114 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004115 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004116 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004117 final int length = mListeners.beginBroadcast();
4118 for (int i = 0; i < length; i++) {
4119 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004120 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004121 }
4122 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004123 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4124 if (notifyApp.booleanValue()) {
4125 broadcastRestrictBackgroundChanged(uid, notifyApp);
4126 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004127 return true;
4128 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004129 case MSG_ADVISE_PERSIST_THRESHOLD: {
4130 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004131 // make sure stats are recorded frequently enough; we aim
4132 // for 2MB threshold for 2GB/month rules.
4133 final long persistThreshold = lowestRule / 1000;
4134 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004135 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004136 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004137 case MSG_UPDATE_INTERFACE_QUOTA: {
4138 removeInterfaceQuota((String) msg.obj);
4139 // int params need to be stitched back into a long
4140 setInterfaceQuota((String) msg.obj,
4141 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4142 return true;
4143 }
4144 case MSG_REMOVE_INTERFACE_QUOTA: {
4145 removeInterfaceQuota((String) msg.obj);
4146 return true;
4147 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004148 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4149 resetUidFirewallRules(msg.arg1);
4150 return true;
4151 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004152 case MSG_SUBSCRIPTION_OVERRIDE: {
4153 final int overrideMask = msg.arg1;
4154 final int overrideValue = msg.arg2;
4155 final int subId = (int) msg.obj;
4156 final int length = mListeners.beginBroadcast();
4157 for (int i = 0; i < length; i++) {
4158 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4159 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4160 }
4161 mListeners.finishBroadcast();
4162 return true;
4163 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004164 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4165 final int userId = msg.arg1;
4166 final Set<String> packageNames = (Set<String>) msg.obj;
4167 setMeteredRestrictedPackagesInternal(packageNames, userId);
4168 return true;
4169 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004170 default: {
4171 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004172 }
4173 }
4174 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004175 };
4176
4177 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4178 @Override
4179 public boolean handleMessage(Message msg) {
4180 switch (msg.what) {
4181 case UID_MSG_STATE_CHANGED: {
4182 final int uid = msg.arg1;
4183 final int procState = msg.arg2;
4184 final long procStateSeq = (Long) msg.obj;
4185
4186 handleUidChanged(uid, procState, procStateSeq);
4187 return true;
4188 }
4189 case UID_MSG_GONE: {
4190 final int uid = msg.arg1;
4191 handleUidGone(uid);
4192 return true;
4193 }
4194 default: {
4195 return false;
4196 }
4197 }
4198 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004199
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004200 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004201
Makoto Onuki8e777332017-03-28 11:25:47 -07004202 void handleUidChanged(int uid, int procState, long procStateSeq) {
4203 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4204 try {
4205 synchronized (mUidRulesFirstLock) {
4206 // We received a uid state change callback, add it to the history so that it
4207 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004208 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004209 // Now update the network policy rules as per the updated uid state.
4210 updateUidStateUL(uid, procState);
4211 // Updating the network rules is done, so notify AMS about this.
4212 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4213 }
4214 } finally {
4215 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4216 }
4217 }
4218
4219 void handleUidGone(int uid) {
4220 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4221 try {
4222 synchronized (mUidRulesFirstLock) {
4223 removeUidStateUL(uid);
4224 }
4225 } finally {
4226 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4227 }
4228 }
4229
Felipe Leme57e3d312016-08-23 14:42:52 -07004230 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4231 final PackageManager pm = mContext.getPackageManager();
4232 final String[] packages = pm.getPackagesForUid(uid);
4233 if (packages != null) {
4234 final int userId = UserHandle.getUserId(uid);
4235 for (String packageName : packages) {
4236 final Intent intent =
4237 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4238 intent.setPackage(packageName);
4239 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4240 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4241 }
4242 }
4243 }
4244
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004245 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4246 // long quotaBytes split up into two ints to fit in message
4247 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4248 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4249 }
4250
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004251 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004252 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004253 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004254 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004255 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004256 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004257 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004258 }
4259 }
4260
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004261 private void removeInterfaceQuotaAsync(String iface) {
4262 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4263 }
4264
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004265 private void removeInterfaceQuota(String iface) {
4266 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004267 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004268 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004269 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004270 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004271 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004272 }
4273 }
4274
Felipe Leme70c57c22016-03-29 10:45:13 -07004275 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4276 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004277 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004278 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004279 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004280 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4281 } catch (RemoteException e) {
4282 // ignored; service lives in system_server
4283 }
4284 }
4285
4286 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4287 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4288 try {
4289 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4290 } catch (IllegalStateException e) {
4291 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004292 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004293 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004294 }
4295 }
4296
Felipe Lemebc853dd2016-09-08 13:26:55 -07004297 private static final int CHAIN_TOGGLE_NONE = 0;
4298 private static final int CHAIN_TOGGLE_ENABLE = 1;
4299 private static final int CHAIN_TOGGLE_DISABLE = 2;
4300 @Retention(RetentionPolicy.SOURCE)
4301 @IntDef(flag = false, value = {
4302 CHAIN_TOGGLE_NONE,
4303 CHAIN_TOGGLE_ENABLE,
4304 CHAIN_TOGGLE_DISABLE
4305 })
4306 public @interface ChainToggleType {
4307 }
4308
4309 /**
4310 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004311 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004312 *
4313 * @param chain firewall chain.
4314 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4315 * @param toggle whether the chain should be enabled, disabled, or not changed.
4316 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004317 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004318 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004319 if (uidRules != null) {
4320 setUidFirewallRulesUL(chain, uidRules);
4321 }
4322 if (toggle != CHAIN_TOGGLE_NONE) {
4323 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4324 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004325 }
4326
Amith Yamasani15e472352015-04-24 19:06:07 -07004327 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004328 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4329 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4330 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004331 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004332 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004333 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004334 int size = uidRules.size();
4335 int[] uids = new int[size];
4336 int[] rules = new int[size];
4337 for(int index = size - 1; index >= 0; --index) {
4338 uids[index] = uidRules.keyAt(index);
4339 rules[index] = uidRules.valueAt(index);
4340 }
4341 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004342 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004343 } catch (IllegalStateException e) {
4344 Log.wtf(TAG, "problem setting firewall uid rules", e);
4345 } catch (RemoteException e) {
4346 // ignored; service lives in system_server
4347 }
4348 }
4349
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004350 /**
4351 * Add or remove a uid to the firewall blacklist for all network ifaces.
4352 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004353 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004354 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4355 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4356 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004357 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004358 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004359 if (chain == FIREWALL_CHAIN_DOZABLE) {
4360 mUidFirewallDozableRules.put(uid, rule);
4361 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4362 mUidFirewallStandbyRules.put(uid, rule);
4363 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4364 mUidFirewallPowerSaveRules.put(uid, rule);
4365 }
4366
4367 try {
4368 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004369 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004370 } catch (IllegalStateException e) {
4371 Log.wtf(TAG, "problem setting firewall uid rules", e);
4372 } catch (RemoteException e) {
4373 // ignored; service lives in system_server
4374 }
4375 } finally {
4376 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004377 }
4378 }
4379
4380 /**
4381 * Add or remove a uid to the firewall blacklist for all network ifaces.
4382 */
Felipe Lemef0823852016-06-08 13:43:08 -07004383 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004384 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4385 mFirewallChainStates.get(chain) == enable) {
4386 // All is the same, nothing to do.
4387 return;
4388 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004389 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004390 try {
4391 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004392 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004393 } catch (IllegalStateException e) {
4394 Log.wtf(TAG, "problem enable firewall chain", e);
4395 } catch (RemoteException e) {
4396 // ignored; service lives in system_server
4397 }
4398 }
4399
Felipe Leme03e95e22016-09-09 09:25:31 -07004400 /**
4401 * Resets all firewall rules associated with an UID.
4402 */
4403 private void resetUidFirewallRules(int uid) {
4404 try {
4405 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4406 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4407 mNetworkManager
4408 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4409 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4410 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4411 } catch (IllegalStateException e) {
4412 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4413 } catch (RemoteException e) {
4414 // ignored; service lives in system_server
4415 }
4416 }
4417
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004418 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004419 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004420 return getNetworkTotalBytes(template, start, end);
4421 }
4422
4423 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004424 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004425 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004426 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004427 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004428 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004429 }
4430 }
4431
4432 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4433 try {
4434 return mNetworkStats.getNetworkUidBytes(template, start, end);
4435 } catch (RuntimeException e) {
4436 Slog.w(TAG, "Failed to read network stats: " + e);
4437 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004438 }
4439 }
4440
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004441 private boolean isBandwidthControlEnabled() {
4442 final long token = Binder.clearCallingIdentity();
4443 try {
4444 return mNetworkManager.isBandwidthControlEnabled();
4445 } catch (RemoteException e) {
4446 // ignored; service lives in system_server
4447 return false;
4448 } finally {
4449 Binder.restoreCallingIdentity(token);
4450 }
4451 }
4452
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004453 private static Intent buildAllowBackgroundDataIntent() {
4454 return new Intent(ACTION_ALLOW_BACKGROUND);
4455 }
4456
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004457 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4458 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004459 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4460 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4461 return intent;
4462 }
4463
4464 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4465 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4466 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004467 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4468 return intent;
4469 }
4470
Wei Liu546cb772016-07-21 16:19:01 -07004471 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004472 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004473 intent.setComponent(ComponentName.unflattenFromString(
4474 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004475 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4476 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4477 return intent;
4478 }
4479
Wei Liu546cb772016-07-21 16:19:01 -07004480 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004481 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004482 intent.setComponent(ComponentName.unflattenFromString(
4483 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004484 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4485 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4486 return intent;
4487 }
4488
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004489 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004490 public void addIdleHandler(IdleHandler handler) {
4491 mHandler.getLooper().getQueue().addIdleHandler(handler);
4492 }
4493
jackqdyulei29c82ab2017-03-10 14:09:16 -08004494 @VisibleForTesting
4495 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4496 mRestrictBackgroundPowerState = result;
4497
4498 boolean restrictBackground = result.batterySaverEnabled;
4499 boolean shouldInvokeRestrictBackground;
4500 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4501 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4502
4503 if (result.globalBatterySaverEnabled) {
4504 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4505 // turn it on.
4506 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4507 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4508 localRestrictBgChangedInBsm = false;
4509 } else {
4510 // Try to restore the restrictBackground if it doesn't change in bsm
4511 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4512 restrictBackground = mRestrictBackgroundBeforeBsm;
4513 }
4514
4515 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004516 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004517 }
4518
4519 // Change it at last so setRestrictBackground() won't affect this variable
4520 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4521 }
4522
Jeff Sharkey1b861272011-05-22 00:34:52 -07004523 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4524 final int size = source.size();
4525 for (int i = 0; i < size; i++) {
4526 target.put(source.keyAt(i), true);
4527 }
4528 }
4529
Stuart Scottf1fb3972015-04-02 18:00:02 -07004530 @Override
4531 public void factoryReset(String subscriber) {
4532 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4533
Stuart Scotte3e314d2015-04-20 14:07:45 -07004534 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4535 return;
4536 }
4537
Stuart Scottf1fb3972015-04-02 18:00:02 -07004538 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004539 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004540 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4541 for (NetworkPolicy policy : policies) {
4542 if (policy.template.equals(template)) {
4543 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4544 policy.inferred = false;
4545 policy.clearSnooze();
4546 }
4547 }
4548 setNetworkPolicies(policies);
4549
4550 // Turn restrict background data off
4551 setRestrictBackground(false);
4552
Stuart Scotte3e314d2015-04-20 14:07:45 -07004553 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4554 // Remove app's "restrict background data" flag
4555 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4556 setUidPolicy(uid, POLICY_NONE);
4557 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004558 }
4559 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004560
Sudheer Shankab8f23162017-08-04 13:30:10 -07004561 @Override
4562 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4563 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4564 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4565 }
4566
4567 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4568 final int uidRules;
4569 final boolean isBackgroundRestricted;
4570 synchronized (mUidRulesFirstLock) {
4571 uidRules = mUidRules.get(uid, RULE_NONE);
4572 isBackgroundRestricted = mRestrictBackground;
4573 }
4574 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004575 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004576 return true;
4577 }
4578 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004579 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004580 return false;
4581 }
4582 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004583 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004584 return true;
4585 }
4586 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004587 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004588 return false;
4589 }
4590 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004591 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004592 return false;
4593 }
4594 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004595 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004596 return true;
4597 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004598 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004599 return false;
4600 }
4601
Felipe Lemed17fda42016-04-29 11:12:45 -07004602 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4603
4604 @Override
4605 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004606 synchronized (mUidRulesFirstLock) {
4607 boolean changed = removeUserStateUL(userId, false);
4608 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004609 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004610 synchronized (mNetworkPoliciesSecondLock) {
4611 writePolicyAL();
4612 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004613 }
4614 }
4615 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004616
4617 /**
4618 * @return true if the given uid is restricted from doing networking on metered networks.
4619 */
4620 @Override
4621 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4622 final int uidRules;
4623 final boolean isBackgroundRestricted;
4624 synchronized (mUidRulesFirstLock) {
4625 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4626 isBackgroundRestricted = mRestrictBackground;
4627 }
4628 return isBackgroundRestricted
4629 && !hasRule(uidRules, RULE_ALLOW_METERED)
4630 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4631 }
4632
4633 /**
4634 * @return true if networking is blocked on the given interface for the given uid according
4635 * to current networking policies.
4636 */
4637 @Override
4638 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004639 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004640 synchronized (mNetworkPoliciesSecondLock) {
4641 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004642 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004643 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004644 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004645
4646 @Override
4647 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4648 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004649 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004650 if (added) {
4651 mPowerSaveTempWhitelistAppIds.put(appId, true);
4652 } else {
4653 mPowerSaveTempWhitelistAppIds.delete(appId);
4654 }
4655 updateRulesForTempWhitelistChangeUL(appId);
4656 }
4657 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004658
4659 @Override
4660 public SubscriptionPlan getSubscriptionPlan(Network network) {
4661 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004662 final int subId = getSubIdLocked(network);
4663 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004664 }
4665 }
4666
4667 @Override
4668 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4669 synchronized (mNetworkPoliciesSecondLock) {
4670 // TODO: handle splitting quota between use-cases
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004671 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
4672 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004673 }
4674 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004675
4676 @Override
4677 public void onAdminDataAvailable() {
4678 mAdminDataAvailableLatch.countDown();
4679 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004680
4681 @Override
4682 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4683 setMeteredRestrictedPackagesInternal(packageNames, userId);
4684 }
4685
4686 @Override
4687 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4688 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4689 userId, 0, packageNames).sendToTarget();
4690 }
4691 }
4692
4693 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4694 synchronized (mUidRulesFirstLock) {
4695 final Set<Integer> newRestrictedUids = new ArraySet<>();
4696 for (String packageName : packageNames) {
4697 final int uid = getUidForPackage(packageName, userId);
4698 if (uid >= 0) {
4699 newRestrictedUids.add(uid);
4700 }
4701 }
4702 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4703 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4704 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4705 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4706 }
4707 }
4708
4709 private int getUidForPackage(String packageName, int userId) {
4710 try {
4711 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4712 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4713 } catch (NameNotFoundException e) {
4714 return -1;
4715 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004716 }
4717
4718 private int parseSubId(NetworkState state) {
4719 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4720 int subId = INVALID_SUBSCRIPTION_ID;
4721 if (state != null && state.networkCapabilities != null
4722 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4723 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4724 if (spec instanceof StringNetworkSpecifier) {
4725 try {
4726 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4727 } catch (NumberFormatException e) {
4728 }
4729 }
4730 }
4731 return subId;
4732 }
4733
Andreas Gampea36dc622018-02-05 17:19:22 -08004734 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004735 private int getSubIdLocked(Network network) {
4736 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004737 }
4738
Andreas Gampea36dc622018-02-05 17:19:22 -08004739 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004740 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4741 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4742 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4743 }
4744
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004745 /**
4746 * This will only ever be called once - during device boot.
4747 */
4748 private void waitForAdminData() {
4749 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4750 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4751 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4752 }
4753 }
4754
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004755 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4756 Set<Integer> newRestrictedUids) {
4757 if (oldRestrictedUids == null) {
4758 for (int uid : newRestrictedUids) {
4759 updateRulesForDataUsageRestrictionsUL(uid);
4760 }
4761 return;
4762 }
4763 for (int uid : oldRestrictedUids) {
4764 if (!newRestrictedUids.contains(uid)) {
4765 updateRulesForDataUsageRestrictionsUL(uid);
4766 }
4767 }
4768 for (int uid : newRestrictedUids) {
4769 if (!oldRestrictedUids.contains(uid)) {
4770 updateRulesForDataUsageRestrictionsUL(uid);
4771 }
4772 }
4773 }
4774
4775 private boolean isRestrictedByAdminUL(int uid) {
4776 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4777 UserHandle.getUserId(uid));
4778 return restrictedUids != null && restrictedUids.contains(uid);
4779 }
4780
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004781 private static boolean hasRule(int uidRules, int rule) {
4782 return (uidRules & rule) != 0;
4783 }
4784
Jeff Sharkey2e471452018-01-19 18:02:47 +09004785 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4786 return (val != null) ? val : new NetworkState[0];
4787 }
4788
Chris Wren193ae6b2017-03-31 15:17:11 -04004789 private class NotificationId {
4790 private final String mTag;
4791 private final int mId;
4792
4793 NotificationId(NetworkPolicy policy, int type) {
4794 mTag = buildNotificationTag(policy, type);
4795 mId = type;
4796 }
4797
4798 @Override
4799 public boolean equals(Object o) {
4800 if (this == o) return true;
4801 if (!(o instanceof NotificationId)) return false;
4802 NotificationId that = (NotificationId) o;
4803 return Objects.equals(mTag, that.mTag);
4804 }
4805
4806 @Override
4807 public int hashCode() {
4808 return Objects.hash(mTag);
4809 }
4810
4811 /**
4812 * Build unique tag that identifies an active {@link NetworkPolicy}
4813 * notification of a specific type, like {@link #TYPE_LIMIT}.
4814 */
4815 private String buildNotificationTag(NetworkPolicy policy, int type) {
4816 return TAG + ":" + policy.template.hashCode() + ":" + type;
4817 }
4818
4819 public String getTag() {
4820 return mTag;
4821 }
4822
4823 public int getId() {
4824 return mId;
4825 }
4826 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004827}